I found this to work flawlessly if you want to share whole screen.
@IBAction func shareButton(_ sender: Any) {
let bounds = UIScreen.main.bounds
UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
self.view.drawHierarchy(in: bounds, afterScreenUpdates: false)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let activityViewController = UIActivityViewController(activityItems: [img!], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
This problem happened with me and sovled by just add
respond_to :html, :json
to ApplicationController file
You can Check Devise issues on Github: https://github.com/plataformatec/devise/issues/2667
I've your same requirements on a public API for which I used rails-api.
I've also set header in a before filter. It looks like this:
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
It seems you missed the Access-Control-Request-Method header.
Adding the following line into the form worked for me:
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
If you ended here googling, this is a simple configuration to prevent this error full the web server logs:
Apache virtualhost
Redirect 404 /apple-touch-icon-precomposed.png
<Location /apple-touch-icon-precomposed.png>
ErrorDocument 404 "apple-touch-icon-precomposed does not exist"
</Location>
Nginx server block:
location =/apple-touch-icon-precomposed.png {
log_not_found off;
access_log off;
}
PS: Is possible you want to add apple-touch-icon.png
and favicon.ico
too.
This is a block of Ruby code that takes advantage of a Rails helper method. If you aren't familiar with blocks yet, you will see them a lot in Ruby.
respond_to
is a Rails helper method that is attached to the Controller class (or rather, its super class). It is referencing the response that will be sent to the View (which is going to the browser).
The block in your example is formatting data - by passing in a 'format' paramater in the block - to be sent from the controller to the view whenever a browser makes a request for html or json data.
If you are on your local machine and you have your Post scaffold set up, you can go to http://localhost:3000/posts
and you will see all of your posts in html format. But, if you type in this: http://localhost:3000/posts.json
, then you will see all of your posts in a json object sent from the server.
This is very handy for making javascript heavy applications that need to pass json back and forth from the server. If you wanted, you could easily create a json api on your rails back-end, and only pass one view - like the index view of your Post controller. Then you could use a javascript library like Jquery or Backbone (or both) to manipulate data and create your own interface. These are called asynchronous UIs and they are becomming really popular (Gmail is one). They are very fast and give the end-user a more desktop-like experience on the web. Of course, this is just one advantage of formatting your data.
The Rails 3 way of writing this would be this:
class PostsController < ApplicationController
# GET /posts
# GET /posts.xml
respond_to :html, :xml, :json
def index
@posts = Post.all
respond_with(@posts)
end
#
# All your other REST methods
#
end
By putting respond_to :html, :xml, :json
at the top of the class, you can declare all the formats that you want your controller to send to your views.
Then, in the controller method, all you have to do is respond_with(@whatever_object_you_have)
It just simplifies your code a little more than what Rails auto-generates.
If you want to know about the inner-workings of this...
From what I understand, Rails introspects the objects to determine what the actual format is going to be. The 'format' variables value is based on this introspection. Rails can do a whole lot with a little bit of info. You'd be surprised at how far a simple @post or :post will go.
For example, if I had a _user.html.erb partial file that looked like this:
_user.html.erb
<li>
<%= link_to user.name, user %>
</li>
Then, this alone in my index view would let Rails know that it needed to find the 'users' partial and iterate through all of the 'users' objects:
index.html.erb
<ul class="users">
<%= render @users %>
</ul>
would let Rails know that it needed to find the 'user' partial and iterate through all of the 'users' objects:
You may find this blog post useful: http://archives.ryandaigle.com/articles/2009/8/6/what-s-new-in-edge-rails-cleaner-restful-controllers-w-respond_with
You can also peruse the source: https://github.com/rails/rails
I had the same issue on localhost. I have changed the domain for the app, but in URLs and hosts file there was still the old domain. Updated my browser bookmarks and hosts file to use new domain and now everything works fine.
Thanks to everyone above, but this is now fixed. For the benefit of others the most significant error was in aligning the three namespaces as suggested by Ian.
For completeness, here is the corrected XML and XSD
Here is the XML, with the typos corrected (sorry for any confusion caused by tardiness)
<?xml version="1.0" encoding="UTF-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="urn:Test.Namespace"
xsi:schemaLocation="urn:Test.Namespace Test1.xsd">
<element1 id="001">
<element2 id="001.1">
<element3 id="001.1" />
</element2>
</element1>
</Root>
and, here is the Schema
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="urn:Test.Namespace"
xmlns="urn:Test.Namespace"
elementFormDefault="qualified">
<xsd:element name="Root">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="element1" maxOccurs="unbounded" type="element1Type"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="element1Type">
<xsd:sequence>
<xsd:element name="element2" maxOccurs="unbounded" type="element2Type"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
<xsd:complexType name="element2Type">
<xsd:sequence>
<xsd:element name="element3" type="element3Type"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
<xsd:complexType name="element3Type">
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
</xsd:schema>
Thanks again to everyone, I hope this is of use to somebody else in the future.
To do the conversion in respect of the current locale, you can use the strftime
function:
setlocale(LC_TIME, 'fr_FR.UTF-8');
$monthName = strftime('%B', mktime(0, 0, 0, $monthNumber));
date
doesn't respect the locale, strftime
does.
I don't think that solution would work anyways because you will see some error message in your error log file.
The solution was a lot easier than what I thought.
simply, open the following path to your php5-fpm
sudo nano /etc/php5/fpm/pool.d/www.conf
or if you're the admin 'root'
nano /etc/php5/fpm/pool.d/www.conf
Then find this line and uncomment it:
listen.allowed_clients = 127.0.0.1
This solution will make you be able to use listen = 127.0.0.1:9000 in your vhost blocks
like this: fastcgi_pass 127.0.0.1:9000;
after you make the modifications, all you need is to restart or reload both Nginx and Php5-fpm
Php5-fpm
sudo service php5-fpm restart
or
sudo service php5-fpm reload
Nginx
sudo service nginx restart
or
sudo service nginx reload
From the comments:
Also comment
;listen = /var/run/php5-fpm.sock
and add
listen = 9000
Greybox cannot handle forms inside it on its own. It requires a forms plugin. No iframes or external html files needed. Don't forget to download the greybox.css file too as the page misses that bit out.
Kiss Jquery UI goodbye and a lightbox hello. You can get it here.
Using the @WebFilter annotation, it can be done as follows:
@WebFilter(urlPatterns = {"/*" })
public class AuthenticationFilter implements Filter{
private static Logger logger = Logger.getLogger(AuthenticationFilter.class);
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
logger.info("checking client id in filter");
HttpServletRequest request = (HttpServletRequest) arg0;
String clientId = request.getHeader("clientId");
if (StringUtils.isNotEmpty(clientId)) {
chain.doFilter(request, response);
} else {
logger.error("client id missing.");
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
Swift 4.1
Create a "Character Set" based on the option you want (urlQueryAllowed). Then remove the additional characters you do not want (+&). Then pass that character set to "addingPercentEncoding".
var address = "American Tourister, Abids Road, Bogulkunta, Hyderabad, Andhra Pradesh, India"
var queryCharSet = NSCharacterSet.urlQueryAllowed
queryCharSet.remove(charactersIn: "+&")
let escapedAddress = address.addingPercentEncoding(withAllowedCharacters: queryCharSet)!
let urlpath = String(format: "http://maps.googleapis.com/maps/api/geocode/json?address=\(escapedAddress)")
The install.packages command looks through the .libPaths variable. Here's what mine defaults to on OSX:
> .libPaths()
[1] "/Library/Frameworks/R.framework/Resources/library"
I don't install packages there by default, I prefer to have them installed in my home directory. In my .Rprofile, I have this line:
.libPaths( "/Users/tex/lib/R" )
This adds the directory "/Users/tex/lib/R" to the front of the .libPaths variable.
- Collect (Action) - Return all the elements of the dataset as an array at the driver program. This is usually useful after a filter or other operation that returns a sufficiently small subset of the data.
select(*cols) (transformation) - Projects a set of expressions and returns a new DataFrame.
Parameters: cols – list of column names (string) or expressions (Column). If one of the column names is ‘*’, that column is expanded to include all columns in the current DataFrame.**
df.select('*').collect() [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')] df.select('name', 'age').collect() [Row(name=u'Alice', age=2), Row(name=u'Bob', age=5)] df.select(df.name, (df.age + 10).alias('age')).collect() [Row(name=u'Alice', age=12), Row(name=u'Bob', age=15)]
Execution select(column-name1,column-name2,etc)
method on a dataframe, returns a new dataframe which holds only the columns which were selected in the select()
function.
e.g. assuming df
has several columns including "name" and "value" and some others.
df2 = df.select("name","value")
df2
will hold only two columns ("name" and "value") out of the entire columns of df
df2 as the result of select
will be in the executors and not in the driver (as in the case of using collect()
)
df.printSchema()
# root
# |-- age: long (nullable = true)
# |-- name: string (nullable = true)
# Select only the "name" column
df.select("name").show()
# +-------+
# | name|
# +-------+
# |Michael|
# | Andy|
# | Justin|
# +-------+
You can running collect()
on a dataframe (spark docs)
>>> l = [('Alice', 1)]
>>> spark.createDataFrame(l).collect()
[Row(_1=u'Alice', _2=1)]
>>> spark.createDataFrame(l, ['name', 'age']).collect()
[Row(name=u'Alice', age=1)]
To print all elements on the driver, one can use the collect() method to first bring the RDD to the driver node thus: rdd.collect().foreach(println). This can cause the driver to run out of memory, though, because collect() fetches the entire RDD to a single machine; if you only need to print a few elements of the RDD, a safer approach is to use the take(): rdd.take(100).foreach(println).
The solution was, after making a backup of the src/test folder, removing it from the filesystem, then creating it again.
That's after I did the "Remove from build path" hint and it screwed the folders when opening the project in STS 4.
Now Update word-wrap is replace by :
overflow-wrap:break-word;
Compatible old navigator and css 3 it's good alternative !
it's evolution of word-wrap ( since 2012... )
See more information : https://www.w3.org/TR/css-text-3/#overflow-wrap
See compatibility full : http://caniuse.com/#search=overflow-wrap
You can Try using :- git ls-files -s
But boost::filesystem
can do that: http://www.boost.org/doc/libs/1_37_0/libs/filesystem/example/simple_ls.cpp
This is my utils service:
angular.module('myApp', []).service('Utils', function Utils($timeout) {
var Super = this;
this.doWhenReady = function(scope, callback, args) {
if(!scope.$$phase) {
if (args instanceof Array)
callback.apply(scope, Array.prototype.slice.call(args))
else
callback();
}
else {
$timeout(function() {
Super.doWhenReady(scope, callback, args);
}, 250);
}
};
});
and this is an example for it's usage:
angular.module('myApp').controller('MyCtrl', function ($scope, Utils) {
$scope.foo = function() {
// some code here . . .
};
Utils.doWhenReady($scope, $scope.foo);
$scope.fooWithParams = function(p1, p2) {
// some code here . . .
};
Utils.doWhenReady($scope, $scope.fooWithParams, ['value1', 'value2']);
};
The original variables you listed can be declared and assigned to the same value in a short line of code using destructuring assignment. The keywords let
, const
, and var
can all be used for this type of assignment.
let [moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown] = Array(6).fill(false);
If you are experiencing the OP's problem where your cookies have been set using JavaScript - for example:
document.cookie = "my_cookie_name=my_cookie_value; expires=Thu, 11 Jun 2070 11:11:11 UTC; path=/";
you could instead use:
document.cookie = "my_cookie_name=my_cookie_value; expires=Thu, 11 Jun 2070 11:11:11 UTC; path=/; SameSite=None; Secure";
It worked for me. More info here.
Standard C doesn't define binary constants. There's a GNU (I believe) extension though (among popular compilers, clang adapts it as well): the 0b
prefix:
int foo = 0b1010;
If you want to stick with standard C, then there's an option: you can combine a macro and a function to create an almost readable "binary constant" feature:
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
And then you can use it like this:
int foo = B(1010);
If you turn on heavy compiler optimizations, the compiler will most likely eliminate the function call completely (constant folding) or will at least inline it, so this won't even be a performance issue.
Proof:
The following code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
int main()
{
int foo = B(001100101);
printf("%d\n", foo);
return 0;
}
has been compiled using clang -o baz.S baz.c -Wall -O3 -S
, and it produced the following assembly:
.section __TEXT,__text,regular,pure_instructions
.globl _main
.align 4, 0x90
_main: ## @main
.cfi_startproc
## BB#0:
pushq %rbp
Ltmp2:
.cfi_def_cfa_offset 16
Ltmp3:
.cfi_offset %rbp, -16
movq %rsp, %rbp
Ltmp4:
.cfi_def_cfa_register %rbp
leaq L_.str1(%rip), %rdi
movl $101, %esi ## <= This line!
xorb %al, %al
callq _printf
xorl %eax, %eax
popq %rbp
ret
.cfi_endproc
.section __TEXT,__cstring,cstring_literals
L_.str1: ## @.str1
.asciz "%d\n"
.subsections_via_symbols
So clang
completely eliminated the call to the function, and replaced its return value with 101
. Neat, huh?
I just got this error and i came to know that it is about the local variable alias
at the end of the stored procedure i had like
select @localvariable1,@localvariable2
it was working fine in sql but when i ran this in ssrs it was always throwing error but after I gave alias it is fixed
select @localvariable1 as A,@localvariable2 as B
Sqlite helper class helps us to manage database creation and version management.
SQLiteOpenHelper takes care of all database management activities. To use it,
1.Override onCreate(), onUpgrade()
methods of SQLiteOpenHelper
. Optionally override onOpen() method.
2.Use this subclass to create either a readable or writable database and use the SQLiteDatabase's four API methods insert(), execSQL(), update(), delete()
to create, read, update and delete rows of your table.
Example to create a MyEmployees table and to select and insert records:
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "DBName";
private static final int DATABASE_VERSION = 2;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table MyEmployees
( _id integer primary key,name text not null);";
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
// Method is called during an upgrade of the database,
@Override
public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
Log.w(MyDatabaseHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS MyEmployees");
onCreate(database);
}
}
Now you can use this class as below,
public class MyDB{
private MyDatabaseHelper dbHelper;
private SQLiteDatabase database;
public final static String EMP_TABLE="MyEmployees"; // name of table
public final static String EMP_ID="_id"; // id value for employee
public final static String EMP_NAME="name"; // name of employee
/**
*
* @param context
*/
public MyDB(Context context){
dbHelper = new MyDatabaseHelper(context);
database = dbHelper.getWritableDatabase();
}
public long createRecords(String id, String name){
ContentValues values = new ContentValues();
values.put(EMP_ID, id);
values.put(EMP_NAME, name);
return database.insert(EMP_TABLE, null, values);
}
public Cursor selectRecords() {
String[] cols = new String[] {EMP_ID, EMP_NAME};
Cursor mCursor = database.query(true, EMP_TABLE,cols,null
, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor; // iterate to get each value.
}
}
Now you can use MyDB class in you activity to have all the database operations. The create records will help you to insert the values similarly you can have your own functions for update and delete.
Checkout the pre-release notes about Swift and Objective C in the same project
You should be importing
#import "SCLAlertView-Swift.h"
Is Button1
visible? I mean, from the server side. Make sure Button1.Visible is true.
Controls that aren't Visible
won't be rendered in HTML, so although they are assigned a ClientID
, they don't actually exist on the client side.
For errors like this you should involve oracle support. Unfortunately you do not mention what oracle release you are using. The error can be related to optimizer bind peeking. Depending on the oracle version different workarounds apply.
You have two ways to address this:
_optim_peek_user_binds = false
Of course underscore parameters should only be set if advised by oracle support
I got the same errors but could not figure out what I was doing wrong.
So I fixed it by running auto-indent on my code and allowing the machine to fix my fault.
If anyone is wondering how I did that. Simple. Go in vim. Type in G=gg.
This will automatically fix everything. Good luck :)
may be in your case you could reach this with the following:
mv excluded_dir ..\
ls -R
mv ..\excluded_dir .
Here's an accessible solution
label {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
label input {_x000D_
position: absolute;_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
label:focus-within {_x000D_
outline: 1px solid orange;_x000D_
}
_x000D_
<div class="radio-toolbar">_x000D_
<label><input type="radio" value="all" checked>All</label>_x000D_
<label><input type="radio" value="false">Open</label>_x000D_
<label><input type="radio" value="true">Archived</label>_x000D_
</div>
_x000D_
I found using css opacity is better for a simple show/hide hover, and you can add css3 transitions to make a nice finished hover effect. The transitions will just be dropped by older IE browsers, so it degrades gracefully to.
#stuff {
opacity: 0.0;
-webkit-transition: all 500ms ease-in-out;
-moz-transition: all 500ms ease-in-out;
-ms-transition: all 500ms ease-in-out;
-o-transition: all 500ms ease-in-out;
transition: all 500ms ease-in-out;
}
#hover {
width:80px;
height:20px;
background-color:green;
margin-bottom:15px;
}
#hover:hover + #stuff {
opacity: 1.0;
}
<div id="hover">Hover</div>
<div id="stuff">stuff</div>
First solution
Avoid System.IO.File.Move
solutions posted here (marked answer included).
It fails over networks. However, copy/delete pattern works locally and over networks. Follow one of the move solutions, but replace it with Copy instead. Then use File.Delete to delete the original file.
You can create a Rename method to simplify it.
Ease of use
Use the VB assembly in C#. Add reference to Microsoft.VisualBasic
Then to rename the file:
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(myfile, newName);
Both are strings. Note that myfile has the full path. newName does not. For example:
a = "C:\whatever\a.txt";
b = "b.txt";
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(a, b);
The C:\whatever\
folder will now contain b.txt
.
If you want to split you dataframe into two different ones, do two selects on it with the different columns you want.
val sourceDf = spark.read.csv(...)
val df1 = sourceDF.select("first column", "second column", "third column")
val df2 = sourceDF.select("first column", "second column", "third column")
Note that this of course means that the sourceDf would be evaluated twice, so if it can fit into distributed memory and you use most of the columns across both dataframes it might be a good idea to cache it. It it has many extra columns that you don't need, then you can do a select on it first to select on the columns you will need so it would store all that extra data in memory.
//assuming b is BOOL. ternary operator helps us in any language.
NSLog(@"result is :%@",((b==YES)?@"YES":@"NO"));
You want this - enter N and then take N number of elements.I am considering your input case is just like this
5
2 3 6 6 5
have this in this way in python 3.x (for python 2.x use raw_input()
instead if input()
)
n = int(input())
arr = input() # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])
n = int(raw_input())
arr = raw_input() # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])
The bash script "corstest" below works for me. It is based on Jun's comment above.
usage
corstest [-v] url
examples
./corstest https://api.coindesk.com/v1/bpi/currentprice.json
https://api.coindesk.com/v1/bpi/currentprice.json Access-Control-Allow-Origin: *
the positive result is displayed in green
./corstest https://github.com/IonicaBizau/jsonrequest
https://github.com/IonicaBizau/jsonrequest does not support CORS
you might want to visit https://enable-cors.org/ to find out how to enable CORS
the negative result is displayed in red and blue
the -v option will show the full curl headers
corstest
#!/bin/bash
# WF 2018-09-20
# https://stackoverflow.com/a/47609921/1497139
#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'
red='\033[0;31m'
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'
#
# a colored message
# params:
# 1: l_color - the color of the message
# 2: l_msg - the message to display
#
color_msg() {
local l_color="$1"
local l_msg="$2"
echo -e "${l_color}$l_msg${endColor}"
}
#
# show the usage
#
usage() {
echo "usage: [-v] $0 url"
echo " -v |--verbose: show curl result"
exit 1
}
if [ $# -lt 1 ]
then
usage
fi
# commandline option
while [ "$1" != "" ]
do
url=$1
shift
# optionally show usage
case $url in
-v|--verbose)
verbose=true;
;;
esac
done
if [ "$verbose" = "true" ]
then
curl -s -X GET $url -H 'Cache-Control: no-cache' --head
fi
origin=$(curl -s -X GET $url -H 'Cache-Control: no-cache' --head | grep -i access-control)
if [ $? -eq 0 ]
then
color_msg $green "$url $origin"
else
color_msg $red "$url does not support CORS"
color_msg $blue "you might want to visit https://enable-cors.org/ to find out how to enable CORS"
fi
A command that would copy in any case
xcopy "path\source" "path\destination" /s/h/e/k/f/c/y
Changing the value property does not change the defaultValue
. In the code (retrieved with .html()
or innerHTML
) the value attribute will contain the defaultValue
, not the value property.
The accepted answer gave two locations:
here
C:\Documents and Settings\Administrator\Local Settings\Temp\VWDWebCache
and possibly here
C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\WebsiteCache
Did you try those?
Edited to add
On my Windows Vista machine, it's located in
%Temp%\VWDWebCache
and in
%LocalAppData%\Microsoft\WebsiteCache
From your additional information (regarding team edition) this comes from Clear Client TFS Cache:
Clear Client TFS Cache
Visual Studio and Team Explorer provide a caching mechanism which can get out of sync. If I have multiple instances of a single TFS which can be connected to from a single Visual Studio client, that client can become confused.
To solve it..
For Windows Vista delete contents of this folder
%LocalAppData%\Microsoft\Team Foundation\1.0\Cache
Let's take a look at the start
command.
Open Windows command prompt
To open a new Chrome window (blank), type the following:
start chrome --new-window
or
start chrome
To open a URL in Chrome, type the following:
start chrome --new-window "http://www.iot.qa/2018/02/narrowband-iot.html"
To open a URL in Chrome in incognito mode, type the following:
start chrome --new-window --incognito "http://www.iot.qa/2018/02/narrowband-iot.html"
or
start chrome --incognito "http://www.iot.qa/2018/02/narrowband-iot.html"
To make Python not return to me "Attempted relative import in non-package". package/
init.py subpackage1/ init.py moduleX.py moduleY.py subpackage2/ init.py moduleZ.py moduleA.py
This error occurs only if you are applying relative import to the parent file. For example parent file already returns main after you code "print(name)" in moduleA.py .so THIS file is already main it cannot return any parent package further on. relative imports are required in files of packages subpackage1 and subpackage2 you can use ".." to refer to the parent directory or module .But parent is if already top level package it cannot go further above that parent directory(package). Such files where you are applying relative importing to parents can only work with the application of absolute import. If you will use ABSOLUTE IMPORT IN PARENT PACKAGE NO ERROR will come as python knows who is at the top level of package even if your file is in subpackages because of the concept of PYTHON PATH which defines the top level of the project
To use the java -jar selenium-server-standalone-2.45.0.jar
command-line tool you need to install a JDK.
You need to download and install the JDK and the standalone selenium server.
Whenever changes are made in dockerfile or compose or requirements , re-Run it using docker-compose up --build
. So that images get rebuild and refreshed
C++11 added alias declarations, which are generalization of typedef
, allowing templates:
template <size_t N>
using Vector = Matrix<N, 1>;
The type Vector<3>
is equivalent to Matrix<3, 1>
.
In C++03, the closest approximation was:
template <size_t N>
struct Vector
{
typedef Matrix<N, 1> type;
};
Here, the type Vector<3>::type
is equivalent to Matrix<3, 1>
.
console.log( 'You are running jQuery version: ' + $.fn.jquery );
You need to git push -f
assuming that nobody has pulled the other commit before. Beware, you're changing history.
If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.
Although <input>
ignores the rows
attribute, you can take advantage of the fact that <textarea>
doesn't have to be inside <form>
tags, but can still be a part of a form by referencing the form's id:
<form method="get" id="testformid">
<input type="submit" />
</form>
<textarea form ="testformid" name="taname" id="taid" cols="35" wrap="soft"></textarea>
Of course, <textarea>
now appears below "submit" button, but maybe you'll find a way to reposition it.
I happen to miss spaces in my query and this error comes.
Ex: $sql= "SELECT * FROM";
$sql .= "table1";
Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".
Also, note that you can add to a namespace. This is clearer with an example, what I mean is that you can have:
namespace MyNamespace
{
double square(double x) { return x * x; }
}
in a file square.h
, and
namespace MyNamespace
{
double cube(double x) { return x * x * x; }
}
in a file cube.h
. This defines a single namespace MyNamespace
(that is, you can define a single namespace across multiple files).
As of v1.1.0-alpha1 (pre release package) the framework uses the VirtualPathProvider
to access files rather than touching the physical file system.
The updated transformer can be seen below:
public class StyleRelativePathTransform
: IBundleTransform
{
public void Process(BundleContext context, BundleResponse response)
{
Regex pattern = new Regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", RegexOptions.IgnoreCase);
response.Content = string.Empty;
// open each of the files
foreach (var file in response.Files)
{
using (var reader = new StreamReader(file.Open()))
{
var contents = reader.ReadToEnd();
// apply the RegEx to the file (to change relative paths)
var matches = pattern.Matches(contents);
if (matches.Count > 0)
{
var directoryPath = VirtualPathUtility.GetDirectory(file.VirtualPath);
foreach (Match match in matches)
{
// this is a path that is relative to the CSS file
var imageRelativePath = match.Groups[2].Value;
// get the image virtual path
var imageVirtualPath = VirtualPathUtility.Combine(directoryPath, imageRelativePath);
// convert the image virtual path to absolute
var quote = match.Groups[1].Value;
var replace = String.Format("url({0}{1}{0})", quote, VirtualPathUtility.ToAbsolute(imageVirtualPath));
contents = contents.Replace(match.Groups[0].Value, replace);
}
}
// copy the result into the response.
response.Content = String.Format("{0}\r\n{1}", response.Content, contents);
}
}
}
}
All the explanations above doesn't work if you work with .js files. If you want to parse PHP into .js files, you have to make changes on your server by modfiying the .htaccess in which the .js files reside using the following commands:
<FilesMatch "\.(js)$">
AddHandler application/x-httpd-php .js
</FilesMatch>
Then, a file test.js files containing the following code will execute .JS on client side with the parsed PHP on server-side:
<html>
<head>
<script>
function myFunction(){
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()"><?php echo "My button";?></button>
</body>
</html>
Memory allocated on the heap can be subject to high-water marks. This is complicated by Python's internal optimizations for allocating small objects (PyObject_Malloc
) in 4 KiB pools, classed for allocation sizes at multiples of 8 bytes -- up to 256 bytes (512 bytes in 3.3). The pools themselves are in 256 KiB arenas, so if just one block in one pool is used, the entire 256 KiB arena will not be released. In Python 3.3 the small object allocator was switched to using anonymous memory maps instead of the heap, so it should perform better at releasing memory.
Additionally, the built-in types maintain freelists of previously allocated objects that may or may not use the small object allocator. The int
type maintains a freelist with its own allocated memory, and clearing it requires calling PyInt_ClearFreeList()
. This can be called indirectly by doing a full gc.collect
.
Try it like this, and tell me what you get. Here's the link for psutil.Process.memory_info.
import os
import gc
import psutil
proc = psutil.Process(os.getpid())
gc.collect()
mem0 = proc.get_memory_info().rss
# create approx. 10**7 int objects and pointers
foo = ['abc' for x in range(10**7)]
mem1 = proc.get_memory_info().rss
# unreference, including x == 9999999
del foo, x
mem2 = proc.get_memory_info().rss
# collect() calls PyInt_ClearFreeList()
# or use ctypes: pythonapi.PyInt_ClearFreeList()
gc.collect()
mem3 = proc.get_memory_info().rss
pd = lambda x2, x1: 100.0 * (x2 - x1) / mem0
print "Allocation: %0.2f%%" % pd(mem1, mem0)
print "Unreference: %0.2f%%" % pd(mem2, mem1)
print "Collect: %0.2f%%" % pd(mem3, mem2)
print "Overall: %0.2f%%" % pd(mem3, mem0)
Output:
Allocation: 3034.36%
Unreference: -752.39%
Collect: -2279.74%
Overall: 2.23%
Edit:
I switched to measuring relative to the process VM size to eliminate the effects of other processes in the system.
The C runtime (e.g. glibc, msvcrt) shrinks the heap when contiguous free space at the top reaches a constant, dynamic, or configurable threshold. With glibc you can tune this with mallopt
(M_TRIM_THRESHOLD). Given this, it isn't surprising if the heap shrinks by more -- even a lot more -- than the block that you free
.
In 3.x range
doesn't create a list, so the test above won't create 10 million int
objects. Even if it did, the int
type in 3.x is basically a 2.x long
, which doesn't implement a freelist.
Well, it's this my DRY installation:
[Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache
)*.gems
files" to a computer without gems in own gem cache place (by default the same patron path of first step: [Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache
)[Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache
) and fire the gem install anygemwithdependencieshere
(by example cucumber-2.99.0
)It's DRY because after install any gem, by default rubygems put the gem file in the cache gem directory and not make sense duplicate thats files, it's more easy if you want both computer has the same versions (or bloqued by paranoic security rules :v)
Edit: In some versions of ruby or rubygems, it don't work and fire alerts or error, you can put gems in other place but not get DRY, other alternative is using launch integrated command
gem server
and add the localhost url in gem sources, more information in: https://guides.rubygems.org/run-your-own-gem-server/
I wasn't able to use the answers here as-is. For starters, as noted, the Travis help document on running jobs locally has been taken down. All of the blog entries and articles I found are based on that. The new "debug" mode doesn't appeal to me because I want to avoid the queue times and the Travis infrastructure until I've got some confidence I have gotten somewhere with my changes.
In my case I'm updating a Puppet module and I'm not an expert in Puppet, nor particularly experienced in Ruby, Travis, or their ecosystems. But I managed to build a workable test image out of tips and ideas in this article and elsewhere, and by examining the Travis CI build logs pretty closely.
I was unable to find recent images matching the names in the CI logs (for example, I could find travisci/ci-sardonyx, but could not find anything with "xenial" or with the same build name). From the logs it appears images are now transferred via AMQP instead of a mechanism more familiar to me.
I was able to find an image travsci/ubuntu-ruby:16.04
which matches the OS I'm targeting for my particular case. It does not have all the components used in the Travis CI, so I built a new one based on this, with some components added to the image and others added in the container at runtime depending on the need.
So I can't offer a clear procedure, sorry. But what I did, essentially boiled down:
Find a recent Travis CI image in Docker Hub matching your target OS as closely as possible.
Clone the repository to a build directory, and launch the container with the build directory mounted as a volume, with the working directory set to the target volume
Now the hard work: go through the Travis build log and set up the environment. In my case, this meant setting up RVM, and then using bundle
to install the project's dependencies. RVM appeared to be already present in the Travis environment but I had to install it; everything else came from reproducing the commands in the build log.
Run the tests.
If the results don't match what you saw in the Travis CI logs, go back to (3) and see where to go.
Optionally, create a reusable image.
Dev and test locally and then push and hopefully your Travis results will be as expected.
I know this is not concrete and may be obvious, and your mileage will definitely vary, but hopefully this is of some use to somebody. The Dockerfile and a README for my image are on GitHub for reference.
onmouseover="$('.play-detail').stop().animate({'height': '84px'},'300');"
onmouseout="$('.play-detail').stop().animate({'height': '44px'},'300');"
Just put two stops -- one onmouseover and one onmouseout.
Here's how to do it in Squarespace using the embed block classes to create responsiveness.
Put this into a code block:
<div class="sqs-block embed-block sqs-block-embed" data-block-type="22" >
<div class="sqs-block-content"><div class="intrinsic" style="max-width:100%">
<div class="embed-block-wrapper embed-block-provider-YouTube" style="padding-bottom:56.20609%;">
<iframe allow="autoplay; fullscreen" scrolling="no" data-image-dimensions="854x480" allowfullscreen="true" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID_HERE" width="854" data-embed="true" frameborder="0" title="YouTube embed" class="embedly-embed" height="480">
</iframe>
</div>
</div>
</div>
Tweak however you'd like!
If you are manually assembling the XML string use var.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffZ"));
That will output the official XML Date Time format. But you don't have to worry about format if you use the built-in serialization methods.
gbk's solution in swift 3
PlayerView
import AVFoundation
import UIKit
class PlayerView: UIView {
override class var layerClass: AnyClass {
return AVPlayerLayer.self
}
var player:AVPlayer? {
set {
if let layer = layer as? AVPlayerLayer {
layer.player = player
}
}
get {
if let layer = layer as? AVPlayerLayer {
return layer.player
} else {
return nil
}
}
}
}
VideoPlayer
import AVFoundation
import Foundation
protocol VideoPlayerDelegate {
func downloadedProgress(progress:Double)
func readyToPlay()
func didUpdateProgress(progress:Double)
func didFinishPlayItem()
func didFailPlayToEnd()
}
let videoContext:UnsafeMutableRawPointer? = nil
class VideoPlayer : NSObject {
private var assetPlayer:AVPlayer?
private var playerItem:AVPlayerItem?
private var urlAsset:AVURLAsset?
private var videoOutput:AVPlayerItemVideoOutput?
private var assetDuration:Double = 0
private var playerView:PlayerView?
private var autoRepeatPlay:Bool = true
private var autoPlay:Bool = true
var delegate:VideoPlayerDelegate?
var playerRate:Float = 1 {
didSet {
if let player = assetPlayer {
player.rate = playerRate > 0 ? playerRate : 0.0
}
}
}
var volume:Float = 1.0 {
didSet {
if let player = assetPlayer {
player.volume = volume > 0 ? volume : 0.0
}
}
}
// MARK: - Init
convenience init(urlAsset: URL, view:PlayerView, startAutoPlay:Bool = true, repeatAfterEnd:Bool = true) {
self.init()
playerView = view
autoPlay = startAutoPlay
autoRepeatPlay = repeatAfterEnd
if let playView = playerView, let playerLayer = playView.layer as? AVPlayerLayer {
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
}
initialSetupWithURL(url: urlAsset)
prepareToPlay()
}
override init() {
super.init()
}
// MARK: - Public
func isPlaying() -> Bool {
if let player = assetPlayer {
return player.rate > 0
} else {
return false
}
}
func seekToPosition(seconds:Float64) {
if let player = assetPlayer {
pause()
if let timeScale = player.currentItem?.asset.duration.timescale {
player.seek(to: CMTimeMakeWithSeconds(seconds, timeScale), completionHandler: { (complete) in
self.play()
})
}
}
}
func pause() {
if let player = assetPlayer {
player.pause()
}
}
func play() {
if let player = assetPlayer {
if (player.currentItem?.status == .readyToPlay) {
player.play()
player.rate = playerRate
}
}
}
func cleanUp() {
if let item = playerItem {
item.removeObserver(self, forKeyPath: "status")
item.removeObserver(self, forKeyPath: "loadedTimeRanges")
}
NotificationCenter.default.removeObserver(self)
assetPlayer = nil
playerItem = nil
urlAsset = nil
}
// MARK: - Private
private func prepareToPlay() {
let keys = ["tracks"]
if let asset = urlAsset {
asset.loadValuesAsynchronously(forKeys: keys, completionHandler: {
DispatchQueue.main.async {
self.startLoading()
}
})
}
}
private func startLoading(){
var error:NSError?
guard let asset = urlAsset else {return}
let status:AVKeyValueStatus = asset.statusOfValue(forKey: "tracks", error: &error)
if status == AVKeyValueStatus.loaded {
assetDuration = CMTimeGetSeconds(asset.duration)
let videoOutputOptions = [kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)]
videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: videoOutputOptions)
playerItem = AVPlayerItem(asset: asset)
if let item = playerItem {
item.addObserver(self, forKeyPath: "status", options: .initial, context: videoContext)
item.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.new, .old], context: videoContext)
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didFailedToPlayToEnd), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: nil)
if let output = videoOutput {
item.add(output)
item.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithmVarispeed
assetPlayer = AVPlayer(playerItem: item)
if let player = assetPlayer {
player.rate = playerRate
}
addPeriodicalObserver()
if let playView = playerView, let layer = playView.layer as? AVPlayerLayer {
layer.player = assetPlayer
print("player created")
}
}
}
}
}
private func addPeriodicalObserver() {
let timeInterval = CMTimeMake(1, 1)
if let player = assetPlayer {
player.addPeriodicTimeObserver(forInterval: timeInterval, queue: DispatchQueue.main, using: { (time) in
self.playerDidChangeTime(time: time)
})
}
}
private func playerDidChangeTime(time:CMTime) {
if let player = assetPlayer {
let timeNow = CMTimeGetSeconds(player.currentTime())
let progress = timeNow / assetDuration
delegate?.didUpdateProgress(progress: progress)
}
}
@objc private func playerItemDidReachEnd() {
delegate?.didFinishPlayItem()
if let player = assetPlayer {
player.seek(to: kCMTimeZero)
if autoRepeatPlay == true {
play()
}
}
}
@objc private func didFailedToPlayToEnd() {
delegate?.didFailPlayToEnd()
}
private func playerDidChangeStatus(status:AVPlayerStatus) {
if status == .failed {
print("Failed to load video")
} else if status == .readyToPlay, let player = assetPlayer {
volume = player.volume
delegate?.readyToPlay()
if autoPlay == true && player.rate == 0.0 {
play()
}
}
}
private func moviewPlayerLoadedTimeRangeDidUpdated(ranges:Array<NSValue>) {
var maximum:TimeInterval = 0
for value in ranges {
let range:CMTimeRange = value.timeRangeValue
let currentLoadedTimeRange = CMTimeGetSeconds(range.start) + CMTimeGetSeconds(range.duration)
if currentLoadedTimeRange > maximum {
maximum = currentLoadedTimeRange
}
}
let progress:Double = assetDuration == 0 ? 0.0 : Double(maximum) / assetDuration
delegate?.downloadedProgress(progress: progress)
}
deinit {
cleanUp()
}
private func initialSetupWithURL(url: URL) {
let options = [AVURLAssetPreferPreciseDurationAndTimingKey : true]
urlAsset = AVURLAsset(url: url, options: options)
}
// MARK: - Observations
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == videoContext {
if let key = keyPath {
if key == "status", let player = assetPlayer {
playerDidChangeStatus(status: player.status)
} else if key == "loadedTimeRanges", let item = playerItem {
moviewPlayerLoadedTimeRangeDidUpdated(ranges: item.loadedTimeRanges)
}
}
}
}
}
We have had to determine if C# was comparable to C++ in performance and I wrote some test programs for that (using Visual Studio 2005 for both languages). It turned out that without garbage collection and only considering the language (not the framework) C# has basically the same performance as C++. Memory allocation is way faster in C# than in C++ and C# has a slight edge in determinism when data sizes are increased beyond cache line boundaries. However, all of this had eventually to be paid for and there is a huge cost in the form of non-deterministic performance hits for C# due to garbage collection.
Just doing like @Kjartan.
Steps are as follows:
Right click your C# project name in Visual Studio's "Solution Explorer";
Then, select "add -> Reference -> COM -> Type Libraries " in order;
Find the "Microsoft Office 16.0 Object Library", and add it to reference (Note: the version number may vary with the OFFICE you have installed);
After doing this, you will see "Microsoft.Office.Interop.Word" under the "Reference" item in your project.
Based on you kernel status (upper right beside "Python 3", the one that is a circle). It seems that it is still busy. It might be trapped in an endless loop or maybe you've run/display something that is not closed.
You can toggle filterstatus
value like this
filterstatus ^= 1;
So your function looks like
function showFilterItem(objButton) {
if (filterstatus == 0) {
$find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().showFilterItem();
objButton.value = "Hide Filter";
}
else {
$find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().hideFilterItem();
objButton.value = "Show filter";
}
filterstatus ^= 1;
}
I'm guessing you're using the date_select
helper to generate the tags for the date. Another way you could do it is to use select form helper for the day, month, year fields. Like this (example I used is the created_at date field):
<%= f.select :month, (1..12).to_a, selected: @user.created_at.month %>
<%= f.select :day, (1..31).to_a, selected: @user.created_at.day %>
<%= f.select :year, ((Time.now.year - 20)..Time.now.year).to_a, selected: @user.created_at.year %>
And in the model, you validate the date:
attr_accessor :month, :day, :year
validate :validate_created_at
private
def convert_created_at
begin
self.created_at = Date.civil(self.year.to_i, self.month.to_i, self.day.to_i)
rescue ArgumentError
false
end
end
def validate_created_at
errors.add("Created at date", "is invalid.") unless convert_created_at
end
If you're looking for a plugin solution, I'd checkout the validates_timeliness plugin. It works like this (from the github page):
class Person < ActiveRecord::Base
validates_date :date_of_birth, on_or_before: lambda { Date.current }
# or
validates :date_of_birth, timeliness: { on_or_before: lambda { Date.current }, type: :date }
end
The list of validation methods available are as follows:
validates_date - validate value as date
validates_time - validate value as time only i.e. '12:20pm'
validates_datetime - validate value as a full date and time
validates - use the :timeliness key and set the type in the hash.
All of the answers so far are good, and get at different aspects of how a hashtable works. Here is a simple example that might be helpful. Lets say we want to store some items with lower case alphabetic strings as a keys.
As simon explained, the hash function is used to map from a large space to a small space. A simple, naive implementation of a hash function for our example could take the first letter of the string, and map it to an integer, so "alligator" has a hash code of 0, "bee" has a hash code of 1, "zebra" would be 25, etc.
Next we have an array of 26 buckets (could be ArrayLists in Java), and we put the item in the bucket that matches the hash code of our key. If we have more than one item that has a key that begins with the same letter, they will have the same hash code, so would all go in the bucket for that hash code so a linear search would have to be made in the bucket to find a particular item.
In our example, if we just had a few dozen items with keys spanning the alphabet, it would work very well. However, if we had a million items or all the keys all started with 'a' or 'b', then our hash table would not be ideal. To get better performance, we would need a different hash function and/or more buckets.
As the Php Manual say,
print_r — Prints human-readable information about a variable
When we use json_decode();
, we get an object of type stdClass as return type.
The arguments, which are to be passed inside of print_r()
should either be an array or a string. Hence, we cannot pass an object inside of print_r()
. I found 2 ways to deal with this.
Cast the object to array.
This can be achieved as follows.
$a = (array)$object;
By accessing the key of the Object
As mentioned earlier, when you use json_decode();
function, it returns an Object of stdClass. you can access the elements of the object with the help of ->
Operator.
$value = $object->key;
One, can also use multiple keys to extract the sub elements incase if the object has nested arrays.
$value = $object->key1->key2->key3...;
Their are other options to print_r()
as well, like var_dump();
and var_export();
P.S : Also, If you set the second parameter of the json_decode();
to true
, it will automatically convert the object to an array();
Here are some references:
http://php.net/manual/en/function.print-r.php
http://php.net/manual/en/function.var-dump.php
http://php.net/manual/en/function.var-export.php
this is an another way:
<html>
<head>
<title>Echo</title>
<style type="text/css">
#result{
border: 1px solid #000000;
min-height: 250px;
max-height: 100%;
padding: 5px;
font-family: sans-serif;
font-size: 12px;
}
</style>
<script type="text/javascript" lang="ja">
function start(){
function echo(text){
lastResultAreaText = document.getElementById('result').innerHTML;
resultArea = document.getElementById('result');
if(lastResultAreaText==""){
resultArea.innerHTML=text;
}
else{
resultArea.innerHTML=lastResultAreaText+"</br>"+text;
}
}
echo("Hello World!");
}
</script>
</head>
<body onload="start()">
<pre id="result"></pre>
</body>
I know this already has a great answer by BalusC but here is a little trick I use to get the container to tell me the correct clientId.
Here is code example as my words may not describe it best.
<p:tabView id="tabs">
<p:tab id="search" title="Search">
<h:form id="insTable">
<p:dataTable id="table" var="lndInstrument" value="#{instrumentBean.instruments}">
<p:column>
<p:commandLink id="select"
Remove the failing update within this component
oncomplete="dlg.show()">
<f:setPropertyActionListener value="#{lndInstrument}"
target="#{instrumentBean.selectedInstrument}" />
<h:outputText value="#{lndInstrument.name}" />
</p:commandLink>
</p:column>
</p:dataTable>
<p:dialog id="dlg" modal="true" widgetVar="dlg">
<h:panelGrid id="display">
Add a component within the component of the id you are trying to update using an update that will fail
<p:commandButton id="BogusButton" update="BogusUpdate"></p:commandButton>
<h:outputText value="Name:" />
<h:outputText value="#{instrumentBean.selectedInstrument.name}" />
</h:panelGrid>
</p:dialog>
</h:form>
</p:tab>
</p:tabView>
Hit this page and view the error. The error is: javax.servlet.ServletException: Cannot find component for expression "BogusUpdate" referenced from tabs:insTable: BogusButton
So the correct clientId to use would then be the bold plus the id of the target container (display in this case)
tabs:insTable:display
When a file is uploaded to github you can use it as external source or free hosting. Troy Alford has explained it well above. But to make it easier let me tell you some easy steps then you can use a github raw file in your site:
Here is your file's link:
https://raw.githubusercontent.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js
Now to execute it you have to remove https:// and the dot( . ) between raw and githubusercontent
Like this:
rawgithubusercontent.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js
Now when you will visit this link you will get a link that can be used to call your javascript:
Here is the final link:
https://rawgit.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js
Similarly if you host a css file you have to do it as mentioned above. It is the easiest way to get simple link to call your external css or javascript file hosted on github.
I hope this is helpful.
Referance URL: http://101helper.blogspot.com/2015/11/store-blogger-codes-on-github-boost-blogger-speed.html
The input.files
attribute is an HTML5 feature. That's why some browsers din't return anything.
Simply add a fallback to the plain old input.value
(string) if files
doesn't exist.
reference: http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-apis.html#dom-input-files
I encountered this error using MySQL in a different context (not within phpMyAdmin). GRANT and SET PASSWORD commands failed on a particular existing user, who was listed in the mysql.user table. In my case, it was fixed by running
FLUSH PRIVILEGES;
The documentation for this command says
Reloads the privileges from the grant tables in the mysql database.
The server caches information in memory as a result of GRANT and CREATE USER statements. This memory is not released by the corresponding REVOKE and DROP USER statements, so for a server that executes many instances of the statements that cause caching, there will be an increase in memory use. This cached memory can be freed with FLUSH PRIVILEGES.
Apparently the user table cache had reached an inconsistent state, causing this weird error message. More information is available here.
To achieve this we can use this formatter:
DecimalFormat df = new DecimalFormat("#.00");
String resultado = df.format(valor)
or:
DecimalFormat df = new DecimalFormat("0.00"); :
Use this method to get always two decimals:
private static String getTwoDecimals(double value){
DecimalFormat df = new DecimalFormat("0.00");
return df.format(value);
}
Defining this values:
91.32
5.22
11.5
1.2
2.6
Using the method we can get this results:
91.32
5.22
11.50
1.20
2.60
New Direction on VS 2017 (x64 systems)
"C:\Program Files (x86)\Microsoft Visual Studio\2017\*your lic type*\Common7\IDE\WcfTestClient.exe"
I had the same problem and I searched for 2-3 days, but the solution for me was really stupid.
Restart the mysql
$ sudo service mysql restart
Now tables become accessible.
I know i am probably the only one that will have this problem in this way. but if you deleted the mdf files in the C:/{user}/ directory, you will get this error too. restore it and you are golden
From the DOCS
Formats a number as text. Group sizing and separator and other locale-specific configurations are based on the active locale.
SYNTAX:
number_expression | number[:digitInfo[:locale]]
where expression
is a number:
digitInfo
is a string which has a following format:
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
Swift 3 & Xcode 8.3.2
This code will help you, i add an explanation too
// Create custom class, this will make your life easier
class CustomDelay {
static let cd = CustomDelay()
// This is your custom delay function
func runAfterDelay(_ delay:Double, closure:@escaping ()->()) {
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
}
// here how to use it (Example 1)
class YourViewController: UIViewController {
// example delay time 2 second
let delayTime = 2.0
override func viewDidLoad() {
super.viewDidLoad()
CustomDelay.cd.runAfterDelay(delayTime) {
// This func will run after 2 second
// Update your UI here, u don't need to worry to bring this to the main thread because your CustomDelay already make this to main thread automatically :)
self.runFunc()
}
}
// example function 1
func runFunc() {
// do your method 1 here
}
}
// here how to use it (Example 2)
class YourSecondViewController: UIViewController {
// let say you want to user run function shoot after 3 second they tap a button
// Create a button (This is programatically, you can create with storyboard too)
let shootButton: UIButton = {
let button = UIButton(type: .system)
button.frame = CGRect(x: 15, y: 15, width: 40, height: 40) // Customize where do you want to put your button inside your ui
button.setTitle("Shoot", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
// create an action selector when user tap shoot button
shootButton.addTarget(self, action: #selector(shoot), for: .touchUpInside)
}
// example shoot function
func shoot() {
// example delay time 3 second then shoot
let delayTime = 3.0
// delay a shoot after 3 second
CustomDelay.cd.runAfterDelay(delayTime) {
// your shoot method here
// Update your UI here, u don't need to worry to bring this to the main thread because your CustomDelay already make this to main thread automatically :)
}
}
}
if myfile.closed == False:
print("File is still open ################")
The following sample code works well (locale need to be obtained dynamically)
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.util.Locale;
class TestBigDecimal {
public static void main(String[] args) {
String str = "0,00";
Locale in_ID = new Locale("in","ID");
//Locale in_ID = new Locale("en","US");
DecimalFormat nf = (DecimalFormat)NumberFormat.getInstance(in_ID);
nf.setParseBigDecimal(true);
BigDecimal bd = (BigDecimal)nf.parse(str, new ParsePosition(0));
System.out.println("bd value : " + bd);
}
}
run - Create a container using image and Start the same. (Create & Start)
start - Start the container(s) in docker list which was in stopped state.
I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\test.xls " & _
";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
strNaam = rs.Fields(0).Value
Next
rs.MoveNext
Loop
rs.Close
There are other ways, depending on what you want to do, such as GetString (GetString Method Description).
I use:
logger = logging.getLogger()
logger.disabled = True
... whatever you want ...
logger.disabled = False
Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country
, X-AppEngine-Region
, X-AppEngine-City
and X-AppEngine-CityLatLong
headers.
An example looks like this:
X-AppEngine-Country:US
X-AppEngine-Region:ca
X-AppEngine-City:norwalk
X-AppEngine-CityLatLong:33.902237,-118.081733
I think it is because %
has often be associated with the modulus operator in many programming languages.
It is the case, e.g., in C, C++, C# and Java, and many other languages which derive their syntax from C (C itself took it from B).
After clicking on Properties of any installer(.exe) which block your application to install (Windows Defender SmartScreen prevented an unrecognized app ) for that issue i found one solution
- Right click on installer(.exe)
- Select properties option.
- Click on checkbox to check Unblock at the bottom of Properties.
This solution work for Heroku CLI (heroku-x64) installer(.exe)
Late Answer but worth it .
You need to load the lines in array or list object where each line will be assign to an index ,then simply call any range of lines by their index in for loop .
Solution is pretty Good ,but there is a memory consumption in between .
give it try ...Its worth it
Ref: https://garbagevalue.com/blog/4-simle-ways-to-check-ip-adress-in-centos-7
I'm using CentOS 7 and command
ip a
is enough to do the job.
Just slice out the IP address part from that test.
ip a | grep 192
You can use the Partial
mapped type as explained in the documentation:
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html
In your example, you'll have:
interface IX {
a: string;
b: any;
c: AnotherType;
}
let x: Partial<IX> = {
a: 'abc'
}
Another simple way would be add some log statement to the bar.someMethod() and then ascertain you can see the said message when your test executed, see examples here: How to do a JUnit assert on a message in a logger
That is especially handy when your Bar.someMethod() is private
.
This should do the trick:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
} // Author: silentnuke
Don't forget to add the internet permission in your manifest.
There are only two steps required, and the full XCode.app is not required at all:
sudo rm -rf /Library/Developer/CommandLineTools
xcode-select --install
At this point the "Installing Softwre" dialog pops up:
That's it!
We recently encountered this error, root cause turned out to be an expired SSL cert on the IIS server. The Load Balancer (infront of our web tier) found the SSL expired, and instead of handling the HTTP traffic over to one of the IIS servers, started showing this error. So basically IIS unable to server requests, for a totally different reason :)
Actually, even if your variable (SongLength) is numeric, you will still have to format it with %s in order to bind the parameter correctly. If you try to use %d, you will get an error. Here's a small excerpt from this link http://mysql-python.sourceforge.net/MySQLdb.html:
To perform a query, you first need a cursor, and then you can execute queries on it:
c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
WHERE price < %s""", (max_price,))
In this example, max_price=5 Why, then, use %s in the string? Because MySQLdb will convert it to a SQL literal value, which is the string '5'. When it's finished, the query will actually say, "...WHERE price < 5".
if x
is numeric, then add scale_x_continuous()
; if x
is character/factor, then add scale_x_discrete()
. This might solve your problem.
Android uses hexadecimal ARGB values, which are formatted as #AARRGGBB. That first pair of letters, the AA, represent the alpha channel. You must convert your decimal opacity values to a hexadecimal value. Here are the steps:
Alpha Hex Value Process
That's how you find the alpha channel value. I've taken the liberty to put together a list of values for you. Enjoy!
Hex Opacity Values
Another veneration of find_elements_by_xpath(".//*")
is:
from selenium.webdriver.common.by import By
find_elements(By.XPATH, ".//*")
The CSS table model is based on the HTML table model http://www.w3.org/TR/CSS21/tables.html
A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.
"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).
Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.
The table itself is always structured the same way it is in HTML.
In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):
<table ..>
<col .. />
<col .. />
<tr ..>
<td ..></td>
<td ..></td>
</tr>
<tr ..>
<td ..></td>
<td ..></td>
</tr>
</table>
Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):
.mytable {_x000D_
display: table;_x000D_
}_x000D_
.myrow {_x000D_
display: table-row;_x000D_
}_x000D_
.mycell {_x000D_
display: table-cell;_x000D_
}_x000D_
.column1 {_x000D_
display: table-column;_x000D_
background-color: green;_x000D_
}_x000D_
.column2 {_x000D_
display: table-column;_x000D_
}
_x000D_
<div class="mytable">_x000D_
<div class="column1"></div>_x000D_
<div class="column2"></div>_x000D_
<div class="myrow">_x000D_
<div class="mycell">contents of first cell in row 1</div>_x000D_
<div class="mycell">contents of second cell in row 1</div>_x000D_
</div>_x000D_
<div class="myrow">_x000D_
<div class="mycell">contents of first cell in row 2</div>_x000D_
<div class="mycell">contents of second cell in row 2</div>_x000D_
</div>_x000D_
</div>
_x000D_
OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:
//Useful css declarations, depending on what you want to affect, include:_x000D_
_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
}_x000D_
_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
}_x000D_
_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
}
_x000D_
<div class="mytable">_x000D_
<div class="column1"></div>_x000D_
<div class="column2"></div>_x000D_
<div class="myrow row1">_x000D_
<div class="mycell cell1">contents of first cell in row 1</div>_x000D_
<div class="mycell cell2">contents of second cell in row 1</div>_x000D_
</div>_x000D_
<div class="myrow row2">_x000D_
<div class="mycell cell1">contents of first cell in row 2</div>_x000D_
<div class="mycell cell2">contents of second cell in row 2</div>_x000D_
</div>_x000D_
</div>
_x000D_
In today's flexible designs, which use <div>
for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr>
in HTML became class myrow
, and <td>
became class mycell
. This convention is what makes the above CSS selectors useful.
PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *
, such as .row1 *
or even .row1 > *
. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 *
first does *
, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1
. This might be slow in a complex document on a slow device. .row1 > *
is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1
. (.row1 > .cell1
is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >
.)
The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *
.
This issue seems to like the following.
How to resolve repository certificate error in Gradle build
Below steps may help:
1. Add certificate to keystore-
Import some certifications into Android Studio JDK cacerts from Android Studio’s cacerts.
Android Studio’s cacerts may be located in
{your-home-directory}/.AndroidStudio3.0/system/tasks/cacerts
I used the following import command.
$ keytool -importkeystore -v -srckeystore {src cacerts} -destkeystore {dest cacerts}
2. Add modified cacert path to gradle.properties-
systemProp.javax.net.ssl.trustStore={your-android-studio-directory}\\jre\\jre\\lib\\security\\cacerts
systemProp.javax.net.ssl.trustStorePassword=changeit
Get process explorer from sysinternals (now Microsoft)
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
What about
android:background="@drawable/your_image"
on the main layout of your activity?
This way you can also have different images for different screen densities by placing them in the appropriate res/drawable-**dpi
folders.
For anyone stumbling across this question that is not on a Mac: assuming you know that your server is running on port 3000, you can do this in one shot by executing the following:
fuser -k 3000/tcp
But as Toby has mentioned, the implementation of fuser in Mac OS is rather primitive and this command will not work on mac.
If you want to avoid blocking, which is only necessary for very large loops, then wrap the contents of your loop in a function called like this: process.nextTick(function(){<contents of loop>})
, which will defer execution until the next tick, giving an opportunity for pending calls from other asynchronous functions to be processed.
The reason reset
and revert
tend to come up a lot in the same conversations is because different version control systems use them to mean different things.
In particular, people who are used to SVN or P4 who want to throw away uncommitted changes to a file will often reach for revert
before being told that they actually want reset
.
Similarly, the revert
equivalent in other VCSes is often called rollback
or something similar - but "rollback" can also mean "I want to completely discard the last few commits", which is appropriate for reset
but not revert
. So, there's a lot of confusion where people know what they want to do, but aren't clear on which command they should be using for it.
As for your actual questions about revert...
Okay, you're going to use git revert but how?
git revert first-bad-commit..last-bad-commit
And after running git revert do you have to do something else after? Do you have to commit the changes revert made or does revert directly commit to the repo or what??
By default, git revert
prompts you for a commit message and then commits the results. This can be overridden. I quote the man page:
--edit
With this option, git revert will let you edit the commit message prior to committing the revert. This is the default if you run the command from a terminal.
--no-commit
Usually the command automatically creates some commits with commit log messages stating which commits were reverted. This flag applies the changes necessary to revert the named commits to your working tree and the index, but does not make the commits. In addition, when this option is used, your index does not have to match the HEAD commit. The revert is done against the beginning state of your index.
This is useful when reverting more than one commits' effect to your index in a row.
In particular, by default it creates a new commit for each commit you're reverting. You can use revert --no-commit
to create changes reverting all of them without committing those changes as individual commits, then commit at your leisure.
div {_x000D_
display: flex;_x000D_
_x000D_
width: 200px;_x000D_
height: 80px;_x000D_
background-color: yellow;_x000D_
}_x000D_
_x000D_
a {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
text-align: center; /* only important for multiple lines */_x000D_
_x000D_
padding: 0 20px;_x000D_
background-color: silver;_x000D_
border: 2px solid blue;_x000D_
}
_x000D_
<div>_x000D_
<a href="#">text</a>_x000D_
<a href="#">text with two lines</a>_x000D_
</div>
_x000D_
A short one Liner of this is:
NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)
Or to cancel all notifications is:
NotificationManagerCompat.from(context).cancelAll()
Made for AndroidX or Support Libraries.
While the accepted answer to this question is correct, it really doesn't do much to explain why it works, and since the syntax is not immediately clear I did a quick google to find out what was actually going on. In the hopes that this information is helpful to others, I'm posting it here.
Taken from MS Support KB 110930.
Redirecting Error Messages from Command Prompt: STDERR/STDOUT
Summary
When redirecting output from an application using the '>' symbol, error messages still print to the screen. This is because error messages are often sent to the Standard Error stream instead of the Standard Out stream.
Output from a console (Command Prompt) application or command is often sent to two separate streams. The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the ">" symbol, you are only redirecting STDOUT. In order to redirect STDERR you have to specify '2>' for the redirection symbol. This selects the second output stream which is STDERR.
Example
The command
dir file.xxx
(wherefile.xxx
does not exist) will display the following output:Volume in drive F is Candy Cane Volume Serial Number is 34EC-0876 File Not Found
If you redirect the output to the
NUL
device usingdir file.xxx > nul
, you will still see the error message part of the output, like this:File Not Found
To redirect (only) the error message to
NUL
, use the following command:dir file.xxx 2> nul
Or, you can redirect the output to one place, and the errors to another.
dir file.xxx > output.msg 2> output.err
You can print the errors and standard output to a single file by using the "&1" command to redirect the output for STDERR to STDOUT and then sending the output from STDOUT to a file:
dir file.xxx 1> output.msg 2>&1
public Image byteArrayToImage(byte[] bytesArr)
{
using (MemoryStream memstr = new MemoryStream(bytesArr))
{
Image img = Image.FromStream(memstr);
return img;
}
}
You can do
jQuery.fn.reverse = function() {
return this.pushStack(this.get().reverse(), arguments);
};
followed by
$(selector).reverse().each(...)
You can convert like this.
date = datetime.datetime.strptime('2019-3-16T5-49-52-595Z','%Y-%m-%dT%H-%M-%S-%f%z')
date_time = date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
For me, a 2-step solution (combination of formatting the title and adding the style) worked, as follows:
1) Format the title
attrbiute:
<a ref="#" title="First Line
Second Line
Third line">Hover Me</a>
2) Add this style to the tips
element:
white-space: pre-line;
Tested in IE8, Firefox 22, and Safari 5.1.7.
C is a macro assembler! And it's the best one!
It can do nearly everything assembly can, it can be portable and in most of the rare cases where it can't do something you can still use embedded assembly code. This leaves only a small fraction of programs that you absolutely need to write in assembly and nothing but assembly.
And the higher level abstractions and the portability make it more worthwhile for most people to write system software in C. And although you might not need portability now if you invest a lot of time and money in writing some program you might not want to limit yourself in what you'll be able to use it for in the future.
Is your syslog.conf set up to handle facility=user?
You can set the facility used by the python logger with the facility argument, something like this:
handler = logging.handlers.SysLogHandler(facility=SysLogHandler.LOG_DAEMON)
Comparable
is Fegan
.The method compareTo
you are overidding in it should have a Fegan
object as a parameter whereas you are casting it to a FoodItems
. Your compareTo
implementation should describe how a Fegan
compare to another Fegan
.
FoodItems
implement Comparable
aswell and copy paste your actual compareTo
logic in it.Do not forget that to draw shadow you must use hardwareAccelerated
drawing
hardwareAccelerated = true
hardwareAccelerated = false
See Android Hardware Acceleration for details
Except first answer form Bathsheba, except MSDN information for:
you could analyse these tables for better understanding of differences between analysed properties.
%x
is a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.
%02x
means if your provided value is less than two digits then 0
will be prepended.
You provided value 16843009
and it has been converted to 1010101
which a hex value.
Yes, You can do it this way too
List<String> listTab = new List();
map.forEach((key, val) {
listTab.add(val);
});
//your widget//
bottom: new TabBar(
controller: _controller,
isScrollable: true,
tabs: listTab
,
),
Try something like this to convert JToken to JArray:
static public JArray convertToJArray(JToken obj)
{
// if ((obj).Type == JTokenType.Null) --> You can check if it's null here
if ((obj).Type == JTokenType.Array)
return (JArray)(obj);
else
return new JArray(); // this will return an empty JArray
}
You could use IllegalArgumentException:
public void speedDown(int decrement)
{
if(speed - decrement < 0){
throw new IllegalArgumentException("Final speed can not be less than zero");
}else{
speed -= decrement;
}
}
var textValue = $("input[type=text]").val()
this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form $('form[name=form1] input[type=text]') Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.
It's all about the order of the scripts. Try to reorder them, place jquery.datetimepicker.js to be last of all scripts!
Use the "REPLACE" string function on the column in question:
UPDATE (yourTable)
SET YourColumn = REPLACE(YourColumn, '*', '')
WHERE (your conditions)
Replace the "*" with the character you want to strip out and specify your WHERE clause to match the rows you want to apply the update to.
Of course, the REPLACE function can also be used - as other answerer have shown - in a SELECT statement - from your question, I assumed you were trying to update a table.
Marc
preferredLayoutAttributesFittingAttributes
renamed to preferredLayoutAttributesFitting
and use auto sizing
systemLayoutSizeFittingSize
renamed to systemLayoutSizeFitting
After seeing my GitHub solution break under iOS 9 I finally got the time to investigate the issue fully. I have now updated the repo to include several examples of different configurations for self sizing cells. My conclusion is that self sizing cells are great in theory but messy in practice. A word of caution when proceeding with self sizing cells.
TL;DR
Check out my GitHub project
Self sizing cells are only supported with flow layout so make sure thats what you are using.
There are two things you need to setup for self sizing cells to work.
estimatedItemSize
on UICollectionViewFlowLayout
Flow layout will become dynamic in nature once you set the estimatedItemSize
property.
self.flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
This comes in 2 flavours; Auto-Layout or custom override of preferredLayoutAttributesFittingAttributes
.
I won't go to in to detail about this as there's a brilliant SO post about configuring constraints for a cell. Just be wary that Xcode 6 broke a bunch of stuff with iOS 7 so, if you support iOS 7, you will need to do stuff like ensure the autoresizingMask is set on the cell's contentView and that the contentView's bounds is set as the cell's bounds when the cell is loaded (i.e. awakeFromNib
).
Things you do need to be aware of is that your cell needs to be more seriously constrained than a Table View Cell. For instance, if you want your width to be dynamic then your cell needs a height constraint. Likewise, if you want the height to be dynamic then you will need a width constraint to your cell.
preferredLayoutAttributesFittingAttributes
in your custom cellWhen this function is called your view has already been configured with content (i.e. cellForItem
has been called). Assuming your constraints have been appropriately set you could have an implementation like this:
//forces the system to do one layout pass
var isHeightCalculated: Bool = false
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
//Exhibit A - We need to cache our calculation to prevent a crash.
if !isHeightCalculated {
setNeedsLayout()
layoutIfNeeded()
let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
var newFrame = layoutAttributes.frame
newFrame.size.width = CGFloat(ceilf(Float(size.width)))
layoutAttributes.frame = newFrame
isHeightCalculated = true
}
return layoutAttributes
}
NOTE On iOS 9 the behaviour changed a bit that could cause crashes on your implementation if you are not careful (See more here). When you implement preferredLayoutAttributesFittingAttributes
you need to ensure that you only change the frame of your layout attributes once. If you don't do this the layout will call your implementation indefinitely and eventually crash. One solution is to cache the calculated size in your cell and invalidate this anytime you reuse the cell or change its content as I have done with the isHeightCalculated
property.
At this point you should have 'functioning' dynamic cells in your collectionView. I haven't yet found the out-of-the box solution sufficient during my tests so feel free to comment if you have. It still feels like UITableView
wins the battle for dynamic sizing IMHO.
Be very mindful that if you are using prototype cells to calculate the estimatedItemSize - this will break if your XIB uses size classes. The reason for this is that when you load your cell from a XIB its size class will be configured with Undefined
. This will only be broken on iOS 8 and up since on iOS 7 the size class will be loaded based on the device (iPad = Regular-Any, iPhone = Compact-Any). You can either set the estimatedItemSize without loading the XIB, or you can load the cell from the XIB, add it to the collectionView (this will set the traitCollection), perform the layout, and then remove it from the superview. Alternatively you could also make your cell override the traitCollection
getter and return the appropriate traits. It's up to you.
Let me know if I missed anything, hope I helped and good luck coding
If you want to make sure that last row does not wrap and thus size the way you want it, have a look at
td {
white-space: nowrap;
}
There is a little "hack" on CSS that also allows you to disable scrolling:
.lock-screen {
height: 100%;
overflow: hidden;
width: 100%;
position: fixed;
}
Adding that class to the body will prevent scrolling.
Try closing and reopening the file, then press Ctrl+F11
.
Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.
Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.
solution is based on these things:
what does it do:
when first time toolbar is executing #setTitle, it creates AppCompatTextView and uses it to display title text.
when the AppCompatTextView is created, toolbar (as ViewGroup), adds it into it's own hierarchy with #addView method.
also, while trying to find solution i noticed that the textview has layout width set to "wrap_content", so i decided to make it "match_parent" and assign textalignment to "center".
MyToolbar.kt, skipping unrelated stuff (constructors/imports):
class MyToolbar : Toolbar {
override fun addView(child: View, params: ViewGroup.LayoutParams) {
if (child is TextView) {
params.width = ViewGroup.LayoutParams.MATCH_PARENT
child.textAlignment= View.TEXT_ALIGNMENT_CENTER
}
super.addView(child, params)
}
}
possible "side effects" - this will apply to "subtitle" too
In case you wish to keep the current version of angular, you can visit this version compatibility checker to check which version of angular-material is best for your current angular version. You can also check peer dependencies of angular-material using angular-material compatibility.
Try this:
import tkinter as tk
from PIL import ImageTk, Image
#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')
path = "Aaron.jpg"
#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img = ImageTk.PhotoImage(Image.open(path))
#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)
#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")
#Start the GUI
window.mainloop()
Related docs: ImageTk Module, Tkinter Label Widget, Tkinter Pack Geometry Manager
In my case it was a copy/paste problem. I somehow ended up with a PRIVATE constructor for my mapping profile:
using AutoMapper;
namespace Your.Namespace
{
public class MappingProfile : Profile
{
MappingProfile()
{
CreateMap<Animal, AnimalDto>();
}
}
}
(take note of the missing "public" in front of the ctor)
which compiled perfectly fine, but when AutoMapper tries to instantiate the profile it can't (of course!) find the constructor!
Here is an API which was written to smooth over the nasty browser cookie "API"
I faced this while using jQuery FileUpload plugin.
Then I took a look in their documentation, most exactly in the Content-Type Negotiation section and followed their suggestion for Ruby/Rails.
render(json: <some-data>, content_type: request.format)
Which fixed the issue for me.
Quick Explanation: for old IE/Opera versions, this plugin will use an iframe with text/plain
or text/html
content-type, so if you force the response to json
, browser will try download it. Using the same content-type as in the request will make it work for any browser.
To view open ports, use the following command.
firewall-cmd --list-ports
We use the following to see services whose ports are open.
firewall-cmd --list-services
We use the following to see services whose ports are open and see open ports
firewall-cmd --list-all
To add a service to the firewall, we use the following command, in which case the service will use any port to open in the firewall.
firewall-cmd --add-services=ntp
For this service to be permanently open we use the following command.
firewall-cmd —add-service=ntp --permanent
To add a port, use the following command
firewall-cmd --add-port=132/tcp --permanent
To run the firewall must be reloaded using the following command.
firewall-cmd --reload
Ya Ali
If you need it with random unique values from 0...length range:
const randomRange = length => {
const results = []
const possibleValues = Array.from({ length }, (value, i) => i)
for (let i = 0; i < length; i += 1) {
const possibleValuesRange = length - (length - possibleValues.length)
const randomNumber = Math.floor(Math.random() * possibleValuesRange)
const normalizedRandomNumber = randomNumber !== possibleValuesRange ? randomNumber : possibleValuesRange
const [nextNumber] = possibleValues.splice(normalizedRandomNumber, 1)
results.push(nextNumber)
}
return results
}
randomRange(5) // [3, 0, 1, 4, 2]
Use boost::hash
#include <boost\functional\hash.hpp>
...
std::string a = "ABCDE";
size_t b = boost::hash_value(a);
If you are using Qt, try rerunning qmake. If this error is in the widget's class, qmake might have failed to notice that the ui class vtable should be regenerated. This fixed the issue for me.
Create a list of lists:
with open("/path/to/file") as file:
lines = []
for line in file:
# The rstrip method gets rid of the "\n" at the end of each line
lines.append(line.rstrip().split(","))
I propose following solution:
DataView view = new DataView(myDataTable);
view.RowFilter = "RowNo = 1";
DataTable results = view.ToTable(true);
Looking at the DataView Documentation, the first thing we can see is this:
Represents a databindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation.
What I am getting from this is that DataTable is meant to only store data and DataView is there enable us to "query" against the DataTable.
Here is how this works in this particular case:
You try to implement the SQL Statement
SELECT *
FROM myDataTable
WHERE RowNo = 1
in "DataTable language". In C# we would read it like this:
FROM myDataTable
WHERE RowNo = 1
SELECT *
which looks in C# like this:
DataView view = new DataView(myDataTable); //FROM myDataTable
view.RowFilter = "RowNo = 1"; //WHERE RowNo = 1
DataTable results = view.ToTable(true); //SELECT *
server {
server_name example.com;
root /path/to/root;
location / {
# bla bla
}
location /demo {
alias /path/to/root/production/folder/here;
}
}
If you need to use try_files
inside /demo
you'll need to replace alias
with a root
and do a rewrite because of the bug explained here
You could skip the use of buttord, and instead just pick an order for the filter and see if it meets your filtering criterion. To generate the filter coefficients for a bandpass filter, give butter() the filter order, the cutoff frequencies Wn=[low, high]
(expressed as the fraction of the Nyquist frequency, which is half the sampling frequency) and the band type btype="band"
.
Here's a script that defines a couple convenience functions for working with a Butterworth bandpass filter. When run as a script, it makes two plots. One shows the frequency response at several filter orders for the same sampling rate and cutoff frequencies. The other plot demonstrates the effect of the filter (with order=6) on a sample time series.
from scipy.signal import butter, lfilter
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
b, a = butter(order, [low, high], btype='band')
return b, a
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
y = lfilter(b, a, data)
return y
if __name__ == "__main__":
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import freqz
# Sample rate and desired cutoff frequencies (in Hz).
fs = 5000.0
lowcut = 500.0
highcut = 1250.0
# Plot the frequency response for a few different orders.
plt.figure(1)
plt.clf()
for order in [3, 6, 9]:
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)
plt.plot((fs * 0.5 / np.pi) * w, abs(h), label="order = %d" % order)
plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)],
'--', label='sqrt(0.5)')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Gain')
plt.grid(True)
plt.legend(loc='best')
# Filter a noisy signal.
T = 0.05
nsamples = T * fs
t = np.linspace(0, T, nsamples, endpoint=False)
a = 0.02
f0 = 600.0
x = 0.1 * np.sin(2 * np.pi * 1.2 * np.sqrt(t))
x += 0.01 * np.cos(2 * np.pi * 312 * t + 0.1)
x += a * np.cos(2 * np.pi * f0 * t + .11)
x += 0.03 * np.cos(2 * np.pi * 2000 * t)
plt.figure(2)
plt.clf()
plt.plot(t, x, label='Noisy signal')
y = butter_bandpass_filter(x, lowcut, highcut, fs, order=6)
plt.plot(t, y, label='Filtered signal (%g Hz)' % f0)
plt.xlabel('time (seconds)')
plt.hlines([-a, a], 0, T, linestyles='--')
plt.grid(True)
plt.axis('tight')
plt.legend(loc='upper left')
plt.show()
Here are the plots that are generated by this script:
You can find your Firebase Web API Key in the follwing way .
Go To project overview -> general -> web API key
Try this:
function normal_chars($string)
{
$string = htmlentities($string, ENT_QUOTES, 'UTF-8');
$string = preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', $string);
$string = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
$string = preg_replace(array('~[^0-9a-z]~i', '~[ -]+~'), ' ', $string);
return trim($string, ' -');
}
Examples:
echo normal_chars('Álix----_Ãxel!?!?'); // Alix Axel
echo normal_chars('áéíóúÁÉÍÓÚ'); // aeiouAEIOU
echo normal_chars('üÿÄËÏÖÜŸåÅ'); // uyAEIOUYaA
Based on the selected answer in this thread: URL Friendly Username in PHP?
Here is a better version with better output formatting and C++ 11 features:
void subset_sum_rec(std::vector<int> & nums, const int & target, std::vector<int> & partialNums)
{
int currentSum = std::accumulate(partialNums.begin(), partialNums.end(), 0);
if (currentSum > target)
return;
if (currentSum == target)
{
std::cout << "sum([";
for (auto it = partialNums.begin(); it != std::prev(partialNums.end()); ++it)
cout << *it << ",";
cout << *std::prev(partialNums.end());
std::cout << "])=" << target << std::endl;
}
for (auto it = nums.begin(); it != nums.end(); ++it)
{
std::vector<int> remaining;
for (auto it2 = std::next(it); it2 != nums.end(); ++it2)
remaining.push_back(*it2);
std::vector<int> partial = partialNums;
partial.push_back(*it);
subset_sum_rec(remaining, target, partial);
}
}
You can take a reference on the control on the ItemCreated event, and then use it later.
const args = ['p0', 'p1', 'p2'];
call_me.apply(this, args);
See MDN docs for Function.prototype.apply()
.
If the environment supports ECMAScript 6, you can use a spread argument instead:
call_me(...args);
Just want to add, that if you have multiple dropdowns (as I do) you should write:
ul.nav li.dropdown:hover > ul.dropdown-menu {
display: block;
}
And it'll work properly.
I have the same problem with Yandex Maps server, JDK 1.6 and Apache HttpClient 4.2.1. The error was
javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
with enabled debug by -Djavax.net.debug=all
there was a message in a log
Could not generate DH keypair
I have fixed this problem by adding BouncyCastle library bcprov-jdk16-1.46.jar
and registering a provider in a map service class
public class MapService {
static {
Security.addProvider(new BouncyCastleProvider());
}
public GeocodeResult geocode() {
}
}
A provider is registered at the first usage of MapService
.
As the compiler says, grid
was not declared in the scope of your function :) "Scope" basically means a set of curly braces. Every variable is limited to the scope in which it is declared (it cannot be accessed outside that scope). In your case, you're declaring the grid
variable in your main()
function and trying to use it in nonrecursivecountcells()
. You seem to be passing it as the argument colors
however, so I suggest you just rename your uses of grid
in nonrecursivecountcells()
to colors
. I think there may be something wrong with trying to pass the array that way, too, so you should probably investigate passing it as a pointer (unless someone else says something to the contrary).
Create a python dictionary to return as the response:
response = {'key': 'value'}
Then you can use json.dumps() or flask.jsonify() to turn a python dictionary into JSON:
from json import dumps
return dumps(response)
from flask import jsonify
return jsonify(response)
Note that flask.jsonify() is made for flask and also it has some more advatages. You can use it like in the following code:
from flask import jsonify
params = {
'key': 'value'
}
return jsonify(**params)
This is like using the following line:
return jsonify(key='value')
Remeber in this code you don't need the response dictionary!
If you are looking for a library to carry out client-side image compression, you can check this out:compress.js. This will basically help you compress multiple images purely with JavaScript and convert them to base64 string. You can optionally set the maximum size in MB and also the preferred image quality.
Since you are asking for lambdas, you can use the following syntax with Java 8:
Date maxDate = list.stream().map(u -> u.date).max(Date::compareTo).get();
or, if you have a getter for the date:
Date maxDate = list.stream().map(User::getDate).max(Date::compareTo).get();
I had the same problem and just solved it. I had posted my own question on stackoverflow:
Can't PUT to my IHttpHandler, GET works fine
The solution was to set runManagedModulesForWebDavRequests to true in the modules element. My guess is that once you install WebDAV then all PUT requests are associated with it. If you need the PUT to go to your handler, you need to remove the WebDAV module and set this attribute to true.
<modules runManagedModulesForWebDavRequests="true">
...
</modules>
So if you're running into the problem when you use the PUT verb and you have installed WebDAV then hopefully this solution will fix your problem.
Here is a solution I wrote using the builder tactic:
#include <string>
#include <sstream>
using std::string;
using std::stringstream;
string stringReplace (const string& source,
const string& toReplace,
const string& replaceWith)
{
size_t pos = 0;
size_t cursor = 0;
int repLen = toReplace.length();
stringstream builder;
do
{
pos = source.find(toReplace, cursor);
if (string::npos != pos)
{
//copy up to the match, then append the replacement
builder << source.substr(cursor, pos - cursor);
builder << replaceWith;
// skip past the match
cursor = pos + repLen;
}
}
while (string::npos != pos);
//copy the remainder
builder << source.substr(cursor);
return (builder.str());
}
Tests:
void addTestResult (const string&& testId, bool pass)
{
...
}
void testStringReplace()
{
string source = "123456789012345678901234567890";
string toReplace = "567";
string replaceWith = "abcd";
string result = stringReplace (source, toReplace, replaceWith);
string expected = "1234abcd8901234abcd8901234abcd890";
bool pass = (0 == result.compare(expected));
addTestResult("567", pass);
source = "123456789012345678901234567890";
toReplace = "123";
replaceWith = "-";
result = stringReplace(source, toReplace, replaceWith);
expected = "-4567890-4567890-4567890";
pass = (0 == result.compare(expected));
addTestResult("start", pass);
source = "123456789012345678901234567890";
toReplace = "0";
replaceWith = "";
result = stringReplace(source, toReplace, replaceWith);
expected = "123456789123456789123456789";
pass = (0 == result.compare(expected));
addTestResult("end", pass);
source = "123123456789012345678901234567890";
toReplace = "123";
replaceWith = "-";
result = stringReplace(source, toReplace, replaceWith);
expected = "--4567890-4567890-4567890";
pass = (0 == result.compare(expected));
addTestResult("concat", pass);
source = "1232323323123456789012345678901234567890";
toReplace = "323";
replaceWith = "-";
result = stringReplace(source, toReplace, replaceWith);
expected = "12-23-123456789012345678901234567890";
pass = (0 == result.compare(expected));
addTestResult("interleaved", pass);
source = "1232323323123456789012345678901234567890";
toReplace = "===";
replaceWith = "-";
result = utils_stringReplace(source, toReplace, replaceWith);
expected = source;
pass = (0 == result.compare(expected));
addTestResult("no match", pass);
}
Trying to do things as smooth as possible - I here suggest modifying GuyWhoLikesPowershell's suggestion slightly.
I replaced the if and until with one while - and I check for "Stopped", since I don't want to start if status is "starting" or " Stopping".
$Service = 'ServiceName'
while ((Get-Service $Service).Status -eq 'Stopped')
{
Start-Service $Service -ErrorAction SilentlyContinue
Start-Sleep 10
}
Return "$($Service) has STARTED"
I have also faced the same issue, The solution for it is : the file for which you are getting the error is probably a duplicated file of the actual file with another version. So just the removal of a particular file on which errors are thrown can resolve the issue.
You can use Microsoft's MapPoint Web Services.
I created a blog entry on how to convert an address to a GeoCode (lat/long).
Also possible by looking for substring with index() function:
awk '(index($3, "snow") != 0) {print}' dummy_file
Shorter version:
awk 'index($3, "snow")' dummy_file
Wrong:
case AnotherClass.MyEnum.VALUE_A
Right:
case VALUE_A:
Secondary data files are optional, are user-defined, and store user data. Secondary files can be used to spread data across multiple disks by putting each file on a different disk drive. Additionally, if a database exceeds the maximum size for a single Windows file, you can use secondary data files so the database can continue to grow.
Source: MSDN: Understanding Files and Filegroups
The recommended file name extension for secondary data files is .ndf
, but this is not enforced.
This library is the easiest and quickest solution to the problem.
Words in a text are always a source of randomness. Given a certain word, nothing can be inferred about the next word. For each word, we can take the ASCII codes of its letters, add those codes to form a number. The parity of this number is a good candidate for a random boolean.
Possible drawbacks:
this strategy is based upon using a text file as a source for the words. At some point, the end of the file will be reached. However, you can estimate how many times you are expected to call the randomBoolean() function from your app. If you will need to call it about 1 million times, then a text file with 1 million words will be enough. As a correction, you can use a stream of data from a live source like an online newspaper.
using some statistical analysis of the common phrases and idioms in a language, one can estimate the next word in a phrase, given the first words of the phrase, with some degree of accuracy. But statistically, these cases are rare, when we can accuratelly predict the next word. So, in most cases, the next word is independent on the previous words.
package p01;
import java.io.File; import java.nio.file.Files; import java.nio.file.Paths;
public class Main {
String words[];
int currentIndex=0;
public static String readFileAsString()throws Exception
{
String data = "";
File file = new File("the_comedy_of_errors");
//System.out.println(file.exists());
data = new String(Files.readAllBytes(Paths.get(file.getName())));
return data;
}
public void init() throws Exception
{
String data = readFileAsString();
words = data.split("\\t| |,|\\.|'|\\r|\\n|:");
}
public String getNextWord() throws Exception
{
if(currentIndex>words.length-1)
throw new Exception("out of words; reached end of file");
String currentWord = words[currentIndex];
currentIndex++;
while(currentWord.isEmpty())
{
currentWord = words[currentIndex];
currentIndex++;
}
return currentWord;
}
public boolean getNextRandom() throws Exception
{
String nextWord = getNextWord();
int asciiSum = 0;
for (int i = 0; i < nextWord.length(); i++){
char c = nextWord.charAt(i);
asciiSum = asciiSum + (int) c;
}
System.out.println(nextWord+"-"+asciiSum);
return (asciiSum%2==1) ;
}
public static void main(String args[]) throws Exception
{
Main m = new Main();
m.init();
while(true)
{
System.out.println(m.getNextRandom());
Thread.sleep(100);
}
}
}
In Eclipse, in the root of my project, there is a file called 'the_comedy_of_errors' (no extension) - created with File> New > File , where I pasted some content from here: http://shakespeare.mit.edu/comedy_errors/comedy_errors.1.1.html
When you use find()
, it automatically assumes your primary key column is going to be id
. In order for this to work correctly, you should set your primary key in your model.
So in Song.php
, within the class, add the line...
protected $primaryKey = 'SongID';
If there is any possibility of changing your schema, I'd highly recommend naming all your primary key columns id
, it's what Laravel assumes and will probably save you from more headaches down the road.
#Variables
$computername = Get-Content 'M:\Applications\Powershell\comp list\Test.txt'
$sourcefile = "\\server\Apps\LanSchool 7.7\Windows\Student.msi"
#This section will install the software
foreach ($computer in $computername)
{
$destinationFolder = "\\$computer\C$\download\LanSchool"
#This section will copy the $sourcefile to the $destinationfolder. If the Folder does not exist it will create it.
if (!(Test-Path -path $destinationFolder))
{
New-Item $destinationFolder -Type Directory
}
Copy-Item -Path $sourcefile -Destination $destinationFolder
Invoke-Command -ComputerName $computer -ScriptBlock { & cmd /c "msiexec.exe /i c:\download\LanSchool\Student.msi" /qn ADVANCED_OPTIONS=1 CHANNEL=100}
}
I've searched all over for this myself and came up with zilch but have finally cobbled this working script together. It's working great! Thought I'd post here hopefully someone else can benefit. It pulls in a list of computers, copies the files down to the local machines and runs it. :) party on!
You have to add the python executable in your SYSTEM PATH, do the following, My Computer > Properties > Advanced System Settings > Environment Variables
> Then under system variables I create a new Variable called "PythonPath". In this variable I have "C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\other-foolder-on-the-path"
.
There's a setSeconds
method as well:
var t = new Date();
t.setSeconds(t.getSeconds() + 10);
For a list of the other Date
functions, you should check out MDN
setSeconds
will correctly handle wrap-around cases:
var d;_x000D_
d = new Date('2014-01-01 10:11:55');_x000D_
alert(d.getMinutes() + ':' + d.getSeconds()); //11:55_x000D_
d.setSeconds(d.getSeconds() + 10);_x000D_
alert(d.getMinutes() + ':0' + d.getSeconds()); //12:05
_x000D_
Install opencv-python
(which is an unofficial pre-built OpenCV package for Python) by issuing the following command:
pip install opencv-python
If not done yet, you need to integrate Tomcat in your Servers view. Rightclick there and choose New > Server. Select the appropriate Tomcat version from the list and complete the wizard.
When you create a new Dynamic Web Project, you should select the integrated server from the list as Targeted Runtime in the 1st wizard step.
Or when you have an existing Dynamic Web Project, you can set/change it in Targeted Runtimes entry in project's properties. Eclipse will then automagically add all its libraries to the build path (without having a copy of them in the project!).
With arrays in php, the foreach loop is always a pretty solution.
In this case it could be for example:
foreach($my_array as $number => $number_array)
{
foreach($number_array as $data = > $user_data)
{
print "Array number: $number, contains $data with $user_data. <br>";
}
}
main() {
double a;
a=3669.0;
int b;
b=a;
printf("b is %d",b);
}
output is :b is 3669
when you write b=a; then its automatically converted in int
see on-line compiler result :
This is called Implicit Type Conversion Read more here https://www.geeksforgeeks.org/implicit-type-conversion-in-c-with-examples/
Not all view are listed directly in every perspective ... choose:
Window->Show View->Other...->Java->Package Explorer
Swift 3.0, Xcode 8
With the following code you can ask an instance for its class. You can also compare two instances, wether having the same class.
// CREATE pure SWIFT class
class MySwiftClass {
var someString : String = "default"
var someInt : Int = 5
}
// CREATE instances
let firstInstance = MySwiftClass()
let secondInstance = MySwiftClass()
secondInstance.someString = "Donald"
secondInstance.someInt = 24
// INSPECT instances
if type(of: firstInstance) === MySwiftClass.self {
print("SUCCESS with ===")
} else {
print("PROBLEM with ===")
}
if type(of: firstInstance) == MySwiftClass.self {
print("SUCCESS with ==")
} else {
print("PROBLEM with ==")
}
// COMPARE CLASS OF TWO INSTANCES
if type(of: firstInstance) === type(of: secondInstance) {
print("instances have equal class")
} else {
print("instances have NOT equal class")
}
The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.
Also, I didn't understand when the accepted answer said "it defaults to node server.js
". I think the documentation clarifies the default behavior:
npm-start
Start a package
Synopsis
npm start [-- <args>]
Description
This runs an arbitrary command specified in the package's "
start
" property of its "scripts
" object. If no "start
" property is specified on the "scripts
" object, it will runnode server.js
.
In summary, running npm start
could do one of two things:
npm start {command_name}
: Run an arbitrary command (i.e. if such command is specified in the start
property of package.json's scripts
object)npm start
: Else if no start
property exists (or no command_name
is passed): Run node server.js
, (which may not be appropriate, for example the OP doesn't have server.js
; the OP runs node
app.js
)package.json
in the directory where you run npm start
, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'
scanf("%s",str)
scans only until it finds a whitespace character. With the input "A 1"
, it will scan only the first character, hence s2
points at the garbage that happened to be in str
, since that array wasn't initialised.
The problem here is your user doesn't have proper rights/permissions to open the file this means that you'd need to grant some administrative privileges to your python ide before you run that command.
As you are a windows user you just need to right click on python ide => select option 'Run as Administrator' and then run your command.
And if you are using the command line to run the codes, do the same open the command prompt with admin rights. Hope it helps
When I try:
<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!" />
It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.
Pls try:
<script type="text/javascript">
function moreFields() {
alert("The text will be show");
}
</script>
<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!" />
Hope it helped.
I think the code is something like:
int rgb = red;
rgb = (rgb << 8) + green;
rgb = (rgb << 8) + blue;
Also, I believe you can get the individual values using:
int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = rgb & 0xFF;
Plus operator is perfectly fine solution to concatenate two Python strings. But if you keep adding more than two strings (n > 25) , you might want to think something else.
''.join([a, b, c])
trick is a performance optimization.
I would suggest using inline CSS styling.
<table border="1" style="padding-right: 10px;">
<tr>
<td>Content</td>
</tr>
</table>
or
<table border="1">
<tr style="padding-right: 10px;">
<td>Content</td>
</tr>
</table>
or
<table border="1">
<tr>
<td style="padding-right: 10px;">Content</td>
</tr>
</table>
I don't quite follow what you need, but this is what I would do, assuming I understand you needs.
You can find answer in depth here.
But in general with float
you need to be aware and take care of the surrounding elements and inline-block
simple way to line elements.
Thanks
When Python2.x sees a == b
, it tries the following.
type(b)
is a new-style class, and type(b)
is a subclass of type(a)
, and type(b)
has overridden __eq__
, then the result is b.__eq__(a)
.type(a)
has overridden __eq__
(that is, type(a).__eq__
isn't object.__eq__
), then the result is a.__eq__(b)
.type(b)
has overridden __eq__
, then the result is b.__eq__(a)
.__cmp__
. If it exists, the objects are equal iff it returns zero
.object.__eq__(a, b)
, which is True
iff a
and b
are the same object.If any of the special methods return NotImplemented
, Python acts as though the method didn't exist.
Note that last step carefully: if neither a
nor b
overloads ==
, then a == b
is the same as a is b
.
Your DemoApplication
class is in the com.ag.digital.demo.boot
package and your LoginBean
class is in the com.ag.digital.demo.bean
package. By default components (classes annotated with @Component
) are found if they are in the same package or a sub-package of your main application class DemoApplication
. This means that LoginBean
isn't being found so dependency injection fails.
There are a couple of ways to solve your problem:
LoginBean
into com.ag.digital.demo.boot
or a sub-package.scanBasePackages
attribute of @SpringBootApplication
that should be on DemoApplication
.A few of other things that aren't causing a problem, but are not quite right with the code you've posted:
@Service
is a specialisation of @Component
so you don't need both on LoginBean
@RestController
is a specialisation of @Component
so you don't need both on DemoRestController
DemoRestController
is an unusual place for @EnableAutoConfiguration
. That annotation is typically found on your main application class (DemoApplication
) either directly or via @SpringBootApplication
which is a combination of @ComponentScan
, @Configuration
, and @EnableAutoConfiguration
.Well, Process Explorer has a suspend option. You can right click a process in the process column and select suspend. Once you are ready to resume it again right click and this time select resume. Process Explorer can be obtained from here:
http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
I used this code:
ws.Range("A:A").FormulaR1C1 = "=DATEVALUE(RC[1])"
column A will be mm/dd/yyyy
RC[1] is column B, the TEXT string, eg, 01/30/12, THIS IS NOT DATE TYPE
I've read lots of blogs on this subject going back to 2005!!
I'm sure that Paul Simon is right (see his submission to this thread) and it's a question of finding which program on your machine is locking the clipboard. I do not run the programs listed in various solutons suggested (eg on Microsoft website) nor am I in a networked or virtual environment so for me those aren't the locking programs (but might be for you). Similarly I don't have the RDP task going in my processes. For me the locking program is the Skype Add-in.
I am not a sophisticated user and am scared of altering my registry so didn't want to go there.
I have now been able to reproduce accurately the "cannot clear the clipboard" message by turning on and off the skype addins in internet explorer. This is easy for amateurs to do and might be one of the more common clipboard locking programs:
I first confirmed that I can turn on/off the problem in Excel by opening/closing internet explorer.
Then I disabled the skype addins:
Internet Explorer: Tools menu --> Internet Options ; Programs Tab ; Manage Add-ons button; Toolbars and Extensions selected in panel on left - scroll down to find skype add ons. Press Disable button.
NB have to restart Internet explorer before this works.
.... 4 days later.... it's still working
Why are you not using this?
int[] array = { 12, 56, 89, 65, 61, 36, 45, 23 };
int max = array.Max();
int min = array.Min();
You can assign a const
object to a non-const
object just fine. Because you're copying and thus creating a new object, const
ness is not violated.
int main() {
const int a = 3;
int b = a;
}
It's different if you want to obtain a pointer or reference to the original, const
object:
int main() {
const int a = 3;
int& b = a; // or int* b = &a;
}
// error: invalid initialization of reference of type 'int&' from
// expression of type 'const int'
You can use const_cast
to hack around the type safety if you really must, but recall that you're doing exactly that: getting rid of the type safety. It's still undefined to modify a
through b
in the below example:
int main() {
const int a = 3;
int& b = const_cast<int&>(a);
b = 3;
}
Although it compiles without errors, anything can happen including opening a black hole or transferring all your hard-earned savings into my bank account.
If you have arrived at what you think is a requirement to do this, I'd urgently revisit your design because something is very wrong with it.
If you have a newer distro with a newer systemd
(systemd
version 236 or newer), you can set the values of StandardOutput
or StandardError
to file:YOUR_ABSPATH_FILENAME
.
Long story:
In newer versions of systemd
there is a relatively new option (the github request is from 2016 ish and the enhancement is merged/closed 2017 ish) where you can set the values of StandardOutput
or StandardError
to file:YOUR_ABSPATH_FILENAME
. The file:path
option is documented in the most recent systemd.exec
man page.
This new feature is relatively new and so is not available for older distros like centos-7 (or any centos before that).
in my case I updated the SDK (on the settings in genymotion), or then the genymotion update
Do this:
if (denominator == 0) throw new ArithmeticException("denominator == 0");
ArithmeticException is the exception which is normally thrown when you divide by 0.
var hiddenFieldID = "input[id$=" + hiddenField + "]";
var requiredVal= $(hiddenFieldID).val();
My favorite register is the ':'
register. Running @:
in Normal mode allows me to repeat the previously ran ex command.
There are some easy steps to make Dump file of your Tables,Users and Procedures:
Goto sqlplus or any sql*plus
connect by your username or password
using System.Text.RegularExpressions;
string str = Regex.Replace(HttpUtility.HtmlDecode(HTMLString), "<.*?>", string.Empty);
An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables. There is no runtime or compile time performance difference.
There isn't so much an advantage or disadvantage aside from "do I want this variable, function, class, etc. to be public or private?"
Presenting to you
left.merge(right, how='cross')
import pandas as pd
pd.__version__
# '1.2.0'
left = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
right = pd.DataFrame({'col3': [5, 6]})
left.merge(right, how='cross')
col1 col2 col3
0 1 3 5
1 1 3 6
2 2 4 5
3 2 4 6
Indexes are ignored in the result.
Implementation wise, this uses the join on common key column method as described in the accepted answer. The upsides of using the API is that it saves you a lot of typing and handles some corner cases pretty well. I'd almost always recommend this syntax as my first preference for cartesian product in pandas unless you're looking for something more performant.
Although my MySQL background is limited, I don't think you have much luck doing that. However, you should be able to migrate over all of your data by restoring the db to a MSSQL server, then creating a SSIS or DTS package to send your tables and data to the MySQL server.
hope this helps
A simpler way to think about it, perhaps: when main returns, your process will not exit if there are non-daemon threads still running.
A bit of advice: Clean shutdown is easy to get wrong when threads and synchronization are involved - if you can avoid it, do so. Use daemon threads whenever possible.
This worked for me:
body {
background-image:url(../IMAGES/background.jpg);
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
Here is the notes (from Brian Goetz book) I made, that might be of help to you
AtomicXXX classes
provide Non-blocking Compare-And-Swap implementation
Takes advantage of the support provide by hardware (the CMPXCHG instruction on Intel) When lots of threads are running through your code that uses these atomic concurrency API, they will scale much better than code which uses Object level monitors/synchronization. Since, Java's synchronization mechanisms makes code wait, when there are lots of threads running through your critical sections, a substantial amount of CPU time is spent in managing the synchronization mechanism itself (waiting, notifying, etc). Since the new API uses hardware level constructs (atomic variables) and wait and lock free algorithms to implement thread-safety, a lot more of CPU time is spent "doing stuff" rather than in managing synchronization.
not only offer better throughput, but they also provide greater resistance to liveness problems such as deadlock and priority inversion.
Since GDB 7.5 you can use these native Convenience Functions:
$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)
Seems quite less problematic than having to execute a "foreign" strcmp()
on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.
Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running
show configuration
inside GDB and searching for--with-python
. This little oneliner does the trick, too:$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python' --with-python=/usr (relocatable)
For your demo case, the usage would be
break <where> if $_streq(x, "hello")
or, if your breakpoint already exists and you just want to add the condition to it
condition <breakpoint number> $_streq(x, "hello")
$_streq
only matches the whole string, so if you want something more cunning you should use $_regex
, which supports the Python regular expression syntax.
First I recommand you can try use print and observe the action:
for i in range(0, 5, 1):
print i
the result:
0
1
2
3
4
You can understand the function principle.
In fact, range
scan range is from 0
to 5-1
.
It equals 0 <= i < 5
When you really understand for-loop in python, I think its time we get back to business. Let's focus your problem.
You want to use a DECREMENT for-loop in python. I suggest a for-loop tutorial for example.
for i in range(5, 0, -1):
print i
the result:
5
4
3
2
1
Thus it can be seen, it equals 5 >= i > 0
You want to implement your java code in python:
for (int index = last-1; index >= posn; index--)
It should code this:
for i in range(last-1, posn-1, -1)
Based on existing responses on this post, this simplify the implementation :)
namespace System
{
public static class BaseTypesExtensions
{
/// <summary>
/// Just a simple wrapper to simplify the process of splitting a string using another string as a separator
/// </summary>
/// <param name="s"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static string[] Split(this string s, string separator)
{
return s.Split(new string[] { separator }, StringSplitOptions.None);
}
}
}
I faced the same issue in Android Studio version 3.5.3. This is how i fixed it.
I updated the dependecy com.android.tools.build:gradle in my project level build.gradle file from a lower version to 3.5.3 as below.
classpath 'com.android.tools.build:gradle:3.5.3'
I then went ahead and edited the value of distributionUrl in gradle-wrapper.properties file as below. This file is in the directory /gradle/wrapper/ from the root of your project folder.
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip