I dont know about XamGrid
but that's what i'll do with a standard wpf DataGrid
:
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Since the TextBlock
and the TextBox
specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.
The best option I found is a plugin called jMenu.
Main: http://www.myjqueryplugins.com/jquery-plugin/jmenu
Demo: http://demos.myjqueryplugins.com/jmenu/
GitHub: https://github.com/alpixel/jMenu
Screenshot:
FWIW, sp_test will not be returning anything but an integer (all SQL Server stored procs just return an integer) and no result sets on the wire (since no SELECT statements). To get the output of the PRINT statements, you normally use the InfoMessage event on the connection (not the command) in ADO.NET.
After much digging, I fixed this on debian 8.3 using information here: https://www.bountysource.com/issues/18142073-can-t-install-gem-on-ubuntu-15-04 Specifically:
sudo apt-get purge graphicsmagick graphicsmagick-dbg imagemagick-common imagemagick imagemagick-6.q16 libmagickcore-6-headers libmagickwand-dev
sudo apt-get autoremove
sudo apt-get install imagemagick libmagickwand-dev
gem install rmagick
First of all, you're testing fp
twice. so printf("Error Reading File\n");
never gets executed.
Then, the output of fscanf
should be equal to 2
since you're reading two values.
I have a simple approach to stopping spammers which is 100% effective, at least in my experience, and avoids the use of reCAPTCHA and similar approaches. I went from close to 100 spams per day on one of my sites' html forms to zero for the last 5 years once I implemented this approach.
It works by taking advantage of the e-mail ALIAS capabilities of most html form handling scripts (I use FormMail.pl), along with a graphic submission "code", which is easily created in the most simple of graphics programs. One such graphic includes the code M19P17nH and the prompt "Please enter the code at left".
This particular example uses a random sequence of letters and numbers, but I tend to use non-English versions of words familiar to my visitors (e.g. "pnofrtay"). Note that the prompt for the form field is built into the graphic, rather than appearing on the form. Thus, to a robot, that form field presents no clue as to its purpose.
The only real trick here is to make sure that your form html assigns this code to the "recipient" variable. Then, in your mail program, make sure that each such code you use is set as an e-mail alias, which points to whatever e-mail addresses you want to use. Since there is no prompt of any kind on the form for a robot to read and no e-mail addresses, it has no idea what to put in the blank form field. If it puts nothing in the form field or anything except acceptable codes, the form submission fails with a "bad recipient" error. You can use a different graphic on different forms, although it isn't really necessary in my experience.
Of course, a human being can solve this problem in a flash, without all the problems associated with reCAPTCHA and similar, more elegant, schemes. If a human spammer does respond to the recipient failure and programs the image code into the robot, you can change it easily, once you realize that the robot has been hard-coded to respond. In five years of using this approach, I've never had a spam from any of the forms on which I use it nor have I ever had a complaint from any human user of the forms. I'm certain that this could be beaten with OCR capability in the robot, but I've never had it happen on any of my sites which use html forms. I have also used "spam traps" (hidden "come hither" html code which points to my anti-spam policies) to good effect, but they were only about 90% effective.
I know this is an old question. This is a neat way I came across if you are on a liunx machine.
import subprocess
print(subprocess.check_output(["ls", "/"]).decode("utf8"))
I know this was asked a while ago, but I was just stumbling over this issue and thought my findings might help others. As pointed out, the error message is basically a result of the out folder. That's because, when you're trying to run the program, it compiles the code first, and puts the compiled result to the out location, and then it tries to load the compiled code from the out location. If the compiled code is not in the location expected, you'll get the error.
The point I'm particularly wanting to share is that some times, the code is not compiled (built), even though your run configuration specifies "Build" in the "Before launch" section of the configuration panel.
When can this happen? One situation that can cause this to happen is if you're using modules and you manually delete the module out directory. For example, if I have a module named "foo", there should be a directory named foo under out/production. If you manually delete it, the build system may not know that it needs to be rebuilt.
Even worse, if you select Build | Build module 'foo', it still may not rebuild the module. If that's the case, you should select a file in the module, for example 'bar.java' and then select Build | Recompile 'bar.java'. Now the out directory out/production/foo should be restored.
Since IntelliJ typically knows about any changes going on, this surprised me, and took me a little time to figure out, so I thought I'd share.
If you want to handle your webapp's timeout with an apache load balancer, you first have to understand the different meaning of timeout
.
I try to condense the discussion I found here: http://apache-http-server.18135.x6.nabble.com/mod-proxy-When-does-a-backend-be-considered-as-failed-td5031316.html :
It appears that
mod_proxy
considers a backend as failed only when the transport layer connection to that backend fails. Unlessfailonstatus/failontimeout
is used. ...
So, setting failontimeout
is necessary for apache to consider a timeout of the webapp (e.g. served by tomcat) as a fail (and consecutively switch to the hot spare server). For the proper configuration, note the following misconfiguration:
ProxyPass / balancer://localbalance/ failontimeout=on timeout=10 failonstatus=50
This is a misconfiguration because:
You are defining a
balancer
here, so thetimeout
parameter relates to thebalancer
(like the two others). However for abalancer
, thetimeout
parameter is not a connection timeout (like the one used withBalancerMember
), but the maximum time to wait for a free worker/member (e.g. when all the workers are busy or in error state, the default being to not wait).
So, a proper configuration is done like this
timeout
at the BalanceMember
level: <Proxy balancer://mycluster>
BalancerMember http://member1:8080/svc timeout=6
... more BalanceMembers here
</Proxy>
failontimeout
on the balancer
ProxyPass /svc balancer://mycluster failontimeout=on
Restart apache.
final File open = new File("PicDic.exe");
if (open.exists() == true) {
if (Desktop.isDesktopSupported()) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Desktop.getDesktop().open(open);
} catch (IOException ex) {
return;
}
}
});
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
//DocumentEditorView.this.getFrame().dispose();
System.exit(0);
}
});
} else {
JOptionPane.showMessageDialog(this.getFrame(), "Desktop is not support to open editor\n You should try manualy");
}
} else {
JOptionPane.showMessageDialog(this.getFrame(), "PicDic.exe is not found");
}
//you can start another apps by using it and can slit your whole project in many apps. it will work lot
This command works like a charm for me:
for /r "$(SolutionDir)libraries" %%f in (*.dll, *.exe) do @xcopy "%%f" "$(TargetDir)"
It recursively copies every dll
and exe
file from MySolutionPath\libraries
into the bin\debug
or bin\release
.
You can find more info in here
For completeness -- also check phpCallGraph.
I have a minor improvement on Ross Drew's answer.
For a small array, a simple loop is faster than the System.arraycopy approach, because of the overhead associated with setting up System.arraycopy. Therefore, it's better to fill the first few bytes of the array using a simple loop, and only move to System.arraycopy when the filled array has a certain size.
The optimal size of the initial loop will be JVM specific and system specific of course.
private static final int SMALL = 16;
public static void arrayFill(byte[] array, byte value) {
int len = array.length;
int lenB = len < SMALL ? len : SMALL;
for (int i = 0; i < lenB; i++) {
array[i] = value;
}
for (int i = SMALL; i < len; i += i) {
System.arraycopy(array, 0, array, i, len < i + i ? len - i : i);
}
}
You need to initialize it first:
p = Pump().getPumps()
Try this code, Let $ be defined
(function ($, Drupal) {
'use strict';
Drupal.behaviors.module_name = {
attach: function (context, settings) {
jQuery(document).ready(function($) {
$("#search_text").autocomplete({
source:results,
minLength:2,
position: { offset:'-30 0' },
select: function(event, ui ) {
goTo(ui.item.value);
return false;
}
});
});
}
};
})(jQuery, Drupal);
The communication with the emulator or your Android device might have problems. This communication is handled by the Android Debug Bridge (adb).
Eclipse allows you to reset the adb in case this causes problems. Select therefore the DDMS perspective via Window ? Open Perspective ? Other... ? DDMS
To restart the adb, select the "Reset adb" in the Device View.
I know im very late to answer this. But it will help others, I was also stucked on this.
Here is what i did to get it work.
String[] namesArr = (String[]) names.toArray(new String[names.size()]);
I wrote a mixin for some syntactic sugar ;)
Maybe someone likes this way of writing if-then-else better than using guards
depends on Less 1.7.0
https://github.com/pixelass/more-or-less/blob/master/less/fn/_if.less
.if(isnumber(2), {
.-then(){
log {
isnumber: true;
}
}
.-else(){
log {
isnumber: false;
}
}
});
.if(lightness(#fff) gt (20% * 2), {
.-then(){
log {
is-light: true;
}
}
});
using on example from above
.if(@debug, {
.-then(){
header {
background-color: yellow;
#title {
background-color: orange;
}
}
article {
background-color: red;
}
}
});
This is my way to solve your task:
str = "0b110100001100101011011000110110001101111"
str = "0" + str[2:]
message = ""
while str != "":
i = chr(int(str[:8], 2))
message = message + i
str = str[8:]
print message
It is very simple just look at their names @RequestParam it consist of two parts one is "Request" which means it is going to deal with request and other part is "Param" which itself makes sense it is going to map only the parameters of requests to java objects. Same is the case with @RequestBody it is going to deal with the data that has been arrived with request like if client has send json object or xml with request at that time @requestbody must be used.
Docotic.Pdf library can be easily used to create PDF files at runtime. The library can also modify existing PDF documents (extract text/images, append pages, fill form fields, etc.)
Samples for common tasks are available on the library site.
Disclaimer: I work for Bit Miracle.
What is gone is gone. The only protection I know of is regular backup.
in ScrollView
use
keyboardShouldPersistTaps="handled"
This will do your job.
The API appears to have changed (or at least, it doesn't work for me).
Running the following in the Package Manager Console works as expected:
Update-Database -Script -SourceMigration:0
Better example is here
try {
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " (Field1 VARCHAR, Field2 INT(3));");
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ TableName
+ " (Field1, Field2)"
+ " VALUES ('Saranga', 22);");
/*retrieve data from database */
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);
int Column1 = c.getColumnIndex("Field1");
int Column2 = c.getColumnIndex("Field2");
// Check if our result was valid.
c.moveToFirst();
if (c != null) {
// Loop through all Results
do {
String Name = c.getString(Column1);
int Age = c.getInt(Column2);
Data =Data +Name+"/"+Age+"\n";
}while(c.moveToNext());
}
Had a simular issue getting the same exception. Took some time locating. In my case I had a static utility class with a constructor that threw the exception (wrapping it). So my issue was in the static constructor.
def month_num2abbr(month):
month = int(month)
import calendar
months_abbr = {month: index for index, month in enumerate(calendar.month_abbr) if month}
for abbr, month_num in months_abbr.items():
if month_num==month:
return abbr
return False
print(month_num2abbr(7))
DBEngine.CompactDatabase source, dest
Try this, it will do the work:
log_file=$curr_dir/log_file.txt
exec > >(tee -a ${log_file} )
exec 2> >(tee -a ${log_file} >&2)
YES!....always style textarea using CSS and avoid the attributes, unless you need to support some very old agent that does not support style sheets. Otherwise, you have full power to use CSS. Below is my default CSS formatting for textarea that looks beautiful in any website. Customize it as you like. Comments are included below so you can see why I chose those CSS properties and values:
textarea {
display: inline-block;
margin: 0;
padding: .2em;
width: auto;
min-width: 30em;
/* The max-width "100%" value fixes a weird issue where width is too wide by default and extends beyond 100% of the parent in some agents. */
max-width: 100%;
/* Height "auto" will allow the text area to expand vertically in size with a horizontal scrollbar if pre-existing content is added to the box before rendering. Remove this if you want a pre-set height. Use "em" to match the font size set in the website. */
height: auto;
/* Use "em" to define the height based on the text size set in your website and the text rows in the box, not a static pixel value. */
min-height: 10em;
/* Do not use "border" in textareas unless you want to remove the 3D box most browsers assign and flatten the box design. */
/*border: 1px solid black;*/
cursor: text;
/* Some textareas have a light gray background by default anyway. */
background-color: #eee;
/* Overflow "auto" allows the box to start with no scrollbars but add them as content fills the box. */
overflow: auto;
/* Resize creates a tab in the lower right corner of textarea for most modern browsers and allows users to resize the box manually. Note: Resize isn't supported by most older agents and IE. */
resize: both;
}
In my "reset" element style sheet I set these values as defaults for "textarea" by default, which give all your textareas a nice look and feel with scrolling when detected, a resizing tab (non-IE browsers), and fixes for dimensions, including a height that allows the box to size itself based on existing content you put in it for the user and a width that does not break out beyond its parent containers limitations.
This first removes all non-letter characters, folds to lowercase, then splits the input, doing all the work in a single line:
String[] words = instring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
Spaces are initially left in the input so the split will still work.
By removing the rubbish characters before splitting, you avoid having to loop through the elements.
Supernova answer for django/boto3/django-storages worked with me:
AWS_S3_REGION_NAME = "ap-south-1"
Or previous to boto3 version 1.4.4:
AWS_S3_REGION_NAME = "ap-south-1"
AWS_S3_SIGNATURE_VERSION = "s3v4"
just add them to your settings.py and change region code accordingly
you can check aws regions from: enter link description here
A string needs no encoding. It is simply a sequence of Unicode characters.
You need to encode when you want to turn a String into a sequence of bytes. The charset the you choose (UTF-8, cp1255, etc.) determines the Character->Byte mapping. Note that a character is not necessarily translated into a single byte. In most charsets, most Unicode characters are translated to at least two bytes.
Encoding of a String is carried out by:
String s1 = "some text";
byte[] bytes = s1.getBytes("UTF-8"); // Charset to encode into
You need to decode when you have ? sequence of bytes and you want to turn them into a String. When y?u d? that you need to specify, again, the charset with which the byt?s were originally encoded (otherwise you'll end up with garbl?d t?xt).
Decoding:
String s2 = new String(bytes, "UTF-8"); // Charset with which bytes were encoded
If you want to understand this better, a great text is "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)"
Eclipse:
Having code higlighting, compiling in the background, pointing out my errors as I go along.
Integration with javadoc, suggesting variable names with ctrl-Space.
When I compile, I get errors right there. I can double click on an error, and it displays the appropriate line.
Really well integrated with JUnit, ctrl-F11 runs the test, tells me the tests have failed. If there is an exception in the output window, I can double click on a line, and takes me to the line that failed. Not only that, but ctrl-F11 makes sure everything is compiled before it runs the tests (which means I never forget to do that).
Integration with ant. One command to build and deploy the application.
Integration with debuggers, including remote debugging of web servers.
FANTASTIC refactoring tools, searching for references to a section of code. Helps me know the impact of a change.
All in all, it makes me more productive.
While some of these solutions may work, none of them follow best practices. Many assign global variables and you may find yourself making calls to multiple parent variables or functions, leading to a cluttered, vulnerable namespace.
To avoid this, use a module pattern. In the parent window:
var myThing = {
var i = 0;
myFunction : function () {
// do something
}
};
var newThing = Object.create(myThing);
Then, in the iframe:
function myIframeFunction () {
parent.myThing.myFunction();
alert(parent.myThing.i);
};
This is similar to patterns described in the Inheritance chapter of Crockford's seminal text, "Javascript: The Good Parts." You can also learn more at w3's page for Javascript's best practices. https://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals
When is del useful in python?
You can use it to remove a single element of an array instead of the slice syntax x[i:i+1]=[]
. This may be useful if for example you are in os.walk
and wish to delete an element in the directory. I would not consider a keyword useful for this though, since one could just make a [].remove(index)
method (the .remove
method is actually search-and-remove-first-instance-of-value).
In the case of my Cordova-project, uninstalling and installing cordova -g fixed the problem for me.
npm uninstall -g cordova
npm install -g cordova
Try using this : iframeTracker jQuery Plugin, like that :
jQuery(document).ready(function($){
$('.iframe_wrap iframe').iframeTracker({
blurCallback: function(){
// Do something when iframe is clicked (like firing an XHR request)
}
});
});
There is no specific event for capturing browser close event.
You can only capture on unload of the current page.
By this method, it will be effected while refreshing / navigating the current page.
Even calculating of X Y postion of the mouse event doesn't give you good result.
Laravel Server Requirements mention that BCMath
, Ctype
, JSON
, Mbstring
, OpenSSL
, PDO
, Tokenizer
, and XML
extensions are required. Most of the extensions are installed and enabled by default.
You can run the following command in Ubuntu to make sure the extensions are installed.
sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip
PHP version specific installation (if PHP 7.4 installed)
sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring
You may need other PHP extensions for your composer packages. Find from links below.
PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)
PHP extensions for Ubuntu 18.04 LTS (Bionic)
PHP extensions for Ubuntu 16.04 LTS (Xenial)
Why does the error mention tuples?
Others have explained that the problem was the missing ,
, but the final mystery is why does the error message talk about tuples?
The reason is that your:
["pennies", '2.5', '50.0', '.01']
["nickles", '5.0', '40.0', '.05']
can be reduced to:
[][1, 2]
as mentioned by 6502 with the same error.
But then __getitem__
, which deals with []
resolution, converts object[1, 2]
to a tuple:
class C(object):
def __getitem__(self, k):
return k
# Single argument is passed directly.
assert C()[0] == 0
# Multiple indices generate a tuple.
assert C()[0, 1] == (0, 1)
and the implementation of __getitem__
for the list built-in class cannot deal with tuple arguments like that.
More examples of __getitem__
action at: https://stackoverflow.com/a/33086813/895245
You might find useful microsoft msdn article How To: Use Regular Expressions to Constrain Input in ASP.NET. Take a look at "Common Regular Expressions" Table. It has validation example for
Non- negative integer
^\d+$
This expression validates that the field contains an integer greater than zero.
I think it is the domain that you run your app.
For example, your canvas URL is facebook.yourdomain.com, you should give App domain as .yourdomain.com
Basically, you're trying to use int
as if it was an Object
, which it isn't (well...it's complicated)
id.equals(list[pos].getItemNumber())
Should be...
id == list[pos].getItemNumber()
I think it's worth mentioning how the Underscore's _.each() works internally. The _.each(list, iteratee) checks if the passed list is an array object, or an object.
In the case that the list is an array, iteratee arguments will be a list element and index as in the following example:
var a = ['I', 'like', 'pancakes', 'a', 'lot', '.'];
_.each( a, function(v, k) { console.log( k + " " + v); });
0 I
1 like
2 pancakes
3 a
4 lot
5 .
On the other hand, if the list argument is an object the iteratee will take a list element and a key:
var o = {name: 'mike', lastname: 'doe', age: 21};
_.each( o, function(v, k) { console.log( k + " " + v); });
name mike
lastname doe
age 21
For reference this is the _.each() code from Underscore.js 1.8.3
_.each = _.forEach = function(obj, iteratee, context) {
iteratee = optimizeCb(iteratee, context);
var i, length;
if (isArrayLike(obj)) {
for (i = 0, length = obj.length; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
You could return Enumerable.Empty<T>()
.
first finish your application using method finish();
and then add below lines in onDestroy for Removing Force close
android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();
In Eclipse Select Help -> Marketplace
Enter "Maven" in Find box and click on Go button
Click on "Install" button for Maven Integration for Eclipse (Juno and newer)
With this, maven should get install without any problem.
From reading the socket.io source code it looks like the "listen" method takes arguments (server, options, fn) and if "server" is an instance of an HTTP/S server it will simply wrap it for you.
So you could presumably give it an empty server which listens for the 'connection' event and handles the socket remoteAddress; however, things might be very difficult if you need to associate that address with an actual socket.io Socket object.
var http = require('http')
, io = require('socket.io');
io.listen(new http.Server().on('connection', function(sock) {
console.log('Client connected from: ' + sock.remoteAddress);
}).listen(80));
Might be easier to submit a patch to socket.io wherein their own Socket object is extended with the remoteAddress property assigned at connection time...
Neither of the first two answers worked for me with multiple elements that can open dialogs that point to different pages.
This feels like the cleanest solution, only creates the dialog object once on load and then uses the events to open/close/display appropriately:
$(function () {
var ajaxDialog = $('<div id="ajax-dialog" style="display:hidden"></div>').appendTo('body');
ajaxDialog.dialog({autoOpen: false});
$('a.ajax-dialog-opener').live('click', function() {
// load remote content
ajaxDialog.load(this.href);
ajaxDialog.dialog("open");
//prevent the browser from following the link
return false;
});
});
You can clean your project with gradle wrapper of your project. In linux:
$./gradlew clean
In windows:
>gradlew.bat clean
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
public static int [] locations={1,2,3};
public static test dot=new test();
Declare the above variables above the main method and the code compiles fine.
public static void main(String[] args){
In addition to @Vitaliy Terziev answer
try touch .bash_profile
and then add alias into the file.
On Windows:
Assign value to PGPASSWORD: C:\>set PGPASSWORD=pass
Run command: C:\>psql -d database -U user
Ready
Or in one line,
set PGPASSWORD=pass&& psql -d database -U user
Note the lack of space before the && !
The first row:
$result = mysql_query($query);
return php db resource.
The second row
while ($row = mysql_fetch_array($result))
Loops all the records returned by the query.
Use mysql_fetch_assoc instead
In that case the row has key=>value pairs.
In the while just put this:
print_r($row)
and you will understand
If you use mysql_fetch_assoc the format of the row will be:
$row["column1_name"] = column1_value;
$row["column2_name"] = column2_value;
For this one:
$row = mysql_fetch_assoc($result)
foreach ($row as $columnName => $columnValue) {
...
}
You will get the firs row from the query and you will iterate all columns in the first result of the query.
Click on the Settings icon and then click on the Restore defaults and reload button. This worked for me whereas the accepted answer didn't.
you are calling a script file not a command so you have to use -file eg :
powershell -executionPolicy bypass -noexit -file "c:\temp\test.ps1" "c:\test with space"
for PS V2
powershell.exe -noexit &'c:\my scripts\test.ps1'
(check bottom of this technet page http://technet.microsoft.com/en-us/library/ee176949.aspx )
I solved the issue using
ln -s libncursesw.so.5 /lib/x86_64-linux-gnu/libncursesw.so.6
on ubunutu 18.10
It's not supported correctly yet.
Chrome 31 (and possibly an earlier version) supports some parts of the attribute, but it is not fully supported.
Bootstrap uses the variable:
$font-size-base: 1rem; // Assumes the browser default, typically 16px
I don't recommend mucking with this, but you can. Best practice is to override the browser default base font size with:
html {
font-size: 14px;
}
Bootstrap will then take that value and use it via rems to set values for all kinds of things.
Mark's solution can be quite expensive since it needs to synchronize everytime.
We can get around the need for synchronization by using the thread-specific storage pattern:
public class RandomNumber : IRandomNumber
{
private static readonly Random Global = new Random();
[ThreadStatic] private static Random _local;
public int Next(int max)
{
var localBuffer = _local;
if (localBuffer == null)
{
int seed;
lock(Global) seed = Global.Next();
localBuffer = new Random(seed);
_local = localBuffer;
}
return localBuffer.Next(max);
}
}
Measure the two implementations and you should see a significant difference.
Just remove ()
at the end.
List<string> optionList = new List<string>
{ "AdditionalCardPersonAdressType", /* rest of elements */ };
Why is this happening?
The entire ext/mysql
PHP extension, which provides all functions named with the prefix mysql_
, was officially deprecated in PHP v5.5.0 and removed in PHP v7.
It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.
How can I fix it?
As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql
. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.
They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.
Hashphp.org has an excellent tutorial on migrating from ext/mysql
to PDO.
I understand that it's possible to suppress deprecation errors by setting
error_reporting
inphp.ini
to excludeE_DEPRECATED
:error_reporting = E_ALL ^ E_DEPRECATED
What will happen if I do that?
Yes, it is possible to suppress such error messages and continue using the old ext/mysql
extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.
Note also that this technique will suppress all E_DEPRECATED
messages, not just those to do with the ext/mysql
extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @
—however this will suppress all errors raised by that expression, not just E_DEPRECATED
ones.
You are starting a new project.
There is absolutely no reason to use ext/mysql
—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.
You have (your own) legacy codebase that currently depends upon ext/mysql
.
It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.
Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.
Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.
The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.
Consider whether you really need to upgrade to PHP v5.5 at this time.
You should begin planning to replace ext/mysql
with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.
However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
You are using a third party project that depends upon ext/mysql
.
Consider whether you really need to upgrade to PHP v5.5 at this time.
Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
It is absolutely essential to perform regression testing.
Easiest solution
<button type="button" onclick="window.location.href='{{ url_for( 'move_forward') }}';">Forward</button>
FWIW Here is a quick-n-dirty code I wrote for inserting to an arbitrary index position. Not necessarily efficient but it works in-place.
class OrderedDictInsert(OrderedDict):
def insert(self, index, key, value):
self[key] = value
for ii, k in enumerate(list(self.keys())):
if ii >= index and k != key:
self.move_to_end(k)
Further to the answer from Diodeus above, you need the font-family: FontAwesome
rule (assuming you have the @font-face
rule for FontAwesome declared already in your CSS). Then it is a matter of knowing which CSS content value corresponds to which icon.
I have listed them all here: http://astronautweb.co/snippet/font-awesome/
Hibernate logging has to be also enabled in hibernate configuration.
Add lines
hibernate.show_sql=true
hibernate.format_sql=true
either to
server\default\deployers\ejb3.deployer\META-INF\jpa-deployers-jboss-beans.xml
or to application's persistence.xml
in <persistence-unit><properties>
tag.
Anyway hibernate logging won't include (in useful form) info on actual prepared statements' parameters.
There is an alternative way of using log4jdbc for any kind of sql logging.
The above answer assumes that you run the code that uses hibernate on JBoss, not in IDE. In this case you should configure logging also on JBoss in server\default\deploy\jboss-logging.xml, not in local IDE classpath.
Note that JBoss 6 doesn't use log4j by default. So adding log4j.properties to ear won't help. Just try to add to jboss-logging.xml:
<logger category="org.hibernate">
<level name="DEBUG"/>
</logger>
Then change threshold for root logger. See SLF4J logger.debug() does not get logged in JBoss 6.
If you manage to debug hibernate queries right from IDE (without deployment), then you should have log4j.properties, log4j, slf4j-api and slf4j-log4j12 jars on classpath. See http://www.mkyong.com/hibernate/how-to-configure-log4j-in-hibernate-project/.
def flatten_it(d):
if isinstance(d, list) or isinstance(d, tuple):
return tuple([flatten_it(item) for item in d])
elif isinstance(d, dict):
return tuple([(flatten_it(k), flatten_it(v)) for k, v in sorted(d.items())])
else:
return d
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 1}
print set(flatten_it(dict1)) - set(flatten_it(dict2)) # set([('b', 2), ('c', 3)])
# or
print set(flatten_it(dict2)) - set(flatten_it(dict1)) # set([('b', 1)])
When you want to sort a List which include the Object Foo, the Foo class has to implement the Comparable interface, because the sort methode of the List is using this methode.
When you want to write a Util class which compares two other classes you can implement the Comparator class.
you can try this.
data_you_need=pd.DataFrame()
for infile in glob.glob("*.xlsx"):
data = pandas.read_excel(infile)
data_you_need=data_you_need.append(data,ignore_index=True)
I hope it can help.
The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or '[email protected]'
It also allows the placeholder to depend on the instance for ModelForms with instance specified.
Even though, the best approach for this situation is set custom CSS styles - an alternative could be:
Width
property and set the percentaje as you see more suitable for your purposes.In my desired scenario, I need set (2) radiobuttons/items as follows:
o Item 1 | o Item 2 |
Example:
<asp:RadioButtonList ID="rbtnLstOptionsGenerateCertif" runat="server"
BackColor="Transparent" BorderColor="Transparent" RepeatDirection="Horizontal"
EnableTheming="False" Width="40%">
<asp:ListItem Text="Item 1" Value="0" />
<asp:ListItem Text="Item 2" Value="1" />
</asp:RadioButtonList>
Rendered result:
<table id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif" class="chxbx2" border="0" style="background-color:Transparent;border-color:Transparent;width:40%;">
<tbody>
<tr>
<td>
<input id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_0" type="radio" name="ctl00$ContentPlaceHolder$rbtnLstOptionsGenerateCertif" value="0" checked="checked">
<label for="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_0">Item 1</label>
</td>
<td>
<input id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_1" type="radio" name="ctl00$ContentPlaceHolder$rbtnLstOptionsGenerateCertif" value="1">
<label for="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_1">Item 2</label>
</td>
</tr>
</tbody>
</table>
_x000D_
I guess ssh
is the best secured way for this, for example :
ssh -OPTIONS -p SSH_PORT user@remote_server "remote_command1; remote_command2; remote_script.sh"
where the OPTIONS have to be deployed according to your specific needs (for example, binding to ipv4 only) and your remote command could be starting your tomcat daemon.
Note:
If you do not want to be prompt at every ssh run, please also have a look to ssh-agent, and optionally to keychain
if your system allows it. Key is... to understand the ssh keys exchange process. Please take a careful look to ssh_config (i.e. the ssh client config file) and sshd_config (i.e. the ssh server config file). Configuration filenames depend on your system, anyway you'll find them somewhere like /etc/sshd_config
. Ideally, pls do not run ssh as root obviously but as a specific user on both sides, servers and client.
Some extra docs over the source project main pages :
ssh and ssh-agent
man ssh
http://www.snailbook.com/index.html
https://help.ubuntu.com/community/SSH/OpenSSH/Configuring
keychain
http://www.gentoo.org/doc/en/keychain-guide.xml
an older tuto in French (by myself :-) but might be useful too :
http://hornetbzz.developpez.com/tutoriels/debian/ssh/keychain/
You can use a try-except
try:
print(str.to.id)
except AttributeError: # Not a Retweet
print('null')
For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.
Another way of doing this:
Dim strings() As String = {}
Testing that it is an empty string array:
MessageBox.Show("count: " + strings.Count.ToString)
Will show a message box saying "count: 0".
yourList = ["a", "b", "a", "c", "c", "a", "c"]
expected outputs {a: 3, b: 1,c:3}
duplicateFrequencies = {}
for i in set(yourList):
duplicateFrequencies[i] = yourList.count(i)
Cheers!! Reference
Use the LayoutInflater
to create a view based on your layout template, and then inject it into the view where you need it.
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);
// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");
// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
You may have to adjust the index where you want to insert the view.
Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT
, or MATCH_PARENT
, etc.
I would like to make a addon for tiago's answer:
Suppose you're hiding element using ng-show
and adding a required
attribute on the same:
<div ng-show="false">
<input required name="something" ng-model="name"/>
</div>
will throw an error something like :
An invalid form control with name='' is not focusable
This is because you just cannot impose required
validation on hidden
elements. Using ng-required
makes it easier to conditionally apply required validation which is just awesome!!
You are right - you need to implement IComparable. To do this, simply declare your class:
public MyClass : IComparable
{
int IComparable.CompareTo(object obj)
{
}
}
In CompareTo, you just implement your custom comparison algorithm (you can use DateTime objects to do this, but just be certain to check the type of "obj" first). For further information, see here and here.
How not to do it:
When building an image, you could also tag it this way.
docker build -t ubuntu:14.04 .
Then you build it again with another tag:
docker build -t ubuntu:latest .
If your Dockerfile makes good use of the cache, the same image should come out, and it effectively does the same as retagging the same image. If you do docker images
then you will see that they have the same ID.
There's probably a case where this goes wrong though... But like @david-braun said, you can't create tags with Dockerfiles themselves, just with the docker command.
C99 has log2
(as well as log2f
and log2l
for float and long double).
Instead of [(ngModel)] you can use:
// view
<input type="date" #myDate [value]="demoUser.date | date:'yyyy-MM-dd'" (input)="demoUser.date=parseDate($event.target.value)" />
// controller
parseDate(dateString: string): Date {
if (dateString) {
return new Date(dateString);
}
return null;
}
You can also choose not to use parseDate function. In this case the date will be saved as string format like "2016-10-06" instead of Date type (I haven't tried whether this has negative consequences when manipulating the data or saving to database for example).
I think documentation has a great explanation of else, continue
[...] it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement."
I'm not sure that I fully understand the question, but from the title of your question, I'm guessing that what you're looking for is pager.setCurrentItem( num )
. That allows you to programatically switch to another page within the ViewPager
.
I'd need to see a stack trace from logcat to be more specific if this is not the problem.
If you don't mind doing this in two operations.
Steps:
1) Add new items with "INSERT OR IGNORE"
2) Update existing items with "UPDATE"
The input to both steps is the same collection of new or update-able items. Works fine with existing items that need no changes. They will be updated, but with the same data and therefore net result is no changes.
Sure, slower, etc. Inefficient. Yep.
Easy to write the sql and maintain and understand it? Definitely.
It's a trade-off to consider. Works great for small upserts. Works great for those that don't mind sacrificing efficiency for code maintainability.
To avoid having to type additional .catch(function () {})
in your code in multiple places, you could add a decorator
to the $exceptionHandler
.
This is a more verbose option than the others but you only have to make the change in one place.
angular
.module('app')
.config(configDecorators);
configDecorators.$inject = ["$provide"];
function configDecorators($provide) {
$provide.decorator("$exceptionHandler", exceptionHandler);
exceptionHandler.$inject = ['$delegate', '$injector'];
function exceptionHandler($delegate, $injector) {
return function (exception, cause) {
if ((exception.toString().toLowerCase()).includes("Possibly unhandled rejection".toLowerCase())) {
console.log(exception); /* optional to log the "Possibly unhandled rejection" */
return;
}
$delegate(exception, cause);
};
}
};
I had the exact same error, Installing zlib-devel solved my problem, Type the command and install zlib package.
On linux:
sudo apt-get install zlib*
On Centos:
sudo yum install zlib*
When working with Spring boot 2.1.x this warning message appears when starting up the application.
As indicated here, maybe this problem didn't show up in earlier versions because the related property was set to true by default and now it is false:
https://github.com/spring-projects/spring-boot/issues/12007
In consequence, solving this is as simple as adding the following property to the spring application.property file.
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation = true
Even though this question is answered, providing an example as to what "theirs" and "ours" means in the case of git rebase vs merge. See this link
Git Rebase
theirs
is actually the current branch in the case of rebase. So the below set of commands are actually accepting your current branch changes over the remote branch.
# see current branch
$ git branch
...
* branch-a
# rebase preferring current branch changes during conflicts
$ git rebase -X theirs branch-b
Git Merge
For merge, the meaning of theirs
and ours
is reversed. So, to get the same effect during a merge, i.e., keep your current branch changes (ours
) over the remote branch being merged (theirs
).
# assuming branch-a is our current version
$ git merge -X ours branch-b # <- ours: branch-a, theirs: branch-b
You can use include=FALSE
to exclude everything in a chunk.
```{r include=FALSE}
source("C:/Rscripts/source.R")
```
If you only want to suppress messages, use message=FALSE
instead:
```{r message=FALSE}
source("C:/Rscripts/source.R")
```
TOP (100) PERCENT is completely meaningless in recent versions of SQL Server, and it (along with the corresponding ORDER BY, in the case of a view definition or derived table) is ignored by the query processor.
You're correct that once upon a time, it could be used as a trick, but even then it wasn't reliable. Sadly, some of Microsoft's graphical tools put this meaningless clause in.
As for why this might appear in dynamic SQL, I have no idea. You're correct that there's no reason for it, and the result is the same without it (and again, in the case of a view definition or derived table, without both the TOP and ORDER BY clauses).
there is data export option in MySQL workbech
Android studio has option to manage dependencies. Follow path.
FYI check link stackoverflow.com/a/33414287/1280397
Just wanted to add to this since I ran into the same problem and nothing I could find anywhere would work (e.g downloading the cacert.pem file, setting cafile in php.ini etc.)
If you are using NGINX and your SSL certificate comes with an "intermediate certificate", you need to combine the intermediate cert file with your main "mydomain.com.crt" file and it should work. Apache has a setting specific for intermediate certs, but NGINX does not so it must be within same file as your regular cert.
The duplicate values in any column can be deleted with a simple for loop.
Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub
By reading your exception , It's sure that you forgot to autowire customerService
You should autowire your customerservice .
make following changes in your controller class
@Controller
public class CustomerController{
@Autowired
private Customerservice customerservice;
......other code......
}
Again your service implementation class
write
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
private CustomerDAO customerDAO;
......other code......
.....add transactional methods
}
If you are using hibernate make necessary changes in your applicationcontext xml file(configuration of session factory is needed).
you should autowire sessionFactory set method in your DAO mplementation
please find samle application context :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<context:component-scan base-package="com.sparkle" />
<!-- Configures the @Controller programming model -->
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="0" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<!-- <bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" /> -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/jdbc.properties</value>
</list>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
</beans>
note that i am using jdbc.properties file for jdbc url and driver specification
Is it possible to add onclick to a div and have it occur if any area of the div is clicked.
Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work
If yes then why is the onclick method not going through to my div.
You are assigning a string where a function is expected.
divTag.onclick = printWorking;
There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.
That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener
Check your .bashrc
file for aliases.
Have you tried using the HTML indentation script on the Vim site?
The for loop is definitely more pythonic, as it uses Python's higher level built in functionality to convey what you're doing both more clearly and concisely. The overhead of range vs xrange, and assigning an unused i
variable, stem from the absence of a statement like Verilog's repeat
statement. The main reason to stick to the for range solution is that other ways are more complex. For instance:
from itertools import repeat
for unused in repeat(None, 10):
del unused # redundant and inefficient, the name is clear enough
print "This is run 10 times"
Using repeat instead of range here is less clear because it's not as well known a function, and more complex because you need to import it. The main style guides if you need a reference are PEP 20 - The Zen of Python and PEP 8 - Style Guide for Python Code.
We also note that the for range version is an explicit example used in both the language reference and tutorial, although in that case the value is used. It does mean the form is bound to be more familiar than the while expansion of a C-style for loop.
This works for me:
android {
packagingOptions {
exclude 'LICENSE.txt'
}
}
Here is the answer:
Download the "Windows Mobile Device Center" for your machine type, likely 64bit.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=3182
Before you run the install, change the compatibility settings to 'Windows 7'. Then install it... Then run it: You'll find it under 'WMDC'.. Your device should now recognize, when plugged in, mine did!
I wanted to have a centered table with the labels right aligned and the values left aligned. The extra space should be around the table. After much experimenting and not following what the documentation said I should do, I came up with something that works. Here's what I did:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="vertical" >
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnCount="2"
android:orientation="horizontal"
android:useDefaultMargins="true" >
<TextView
android:layout_gravity="right"
android:text="Short label:" />
<TextView
android:id="@+id/start_time"
android:layout_gravity="left"
android:text="Long extended value" />
<TextView
android:layout_gravity="right"
android:text="A very long extended label:" />
<TextView
android:id="@+id/elapsed_time"
android:layout_gravity="left"
android:text="Short value" />
</GridLayout>
This seems to work but the GridLayout shows the message:
"This GridLayout layout or its LinearLayout parent is useless"
Not sure why it is "useless" when it works for me.
I'm not sure why this works or if this is a good idea, but if you try it and can provide a better idea, small improvement or explain why it works (or won't work) I'd appreciate the feedback.
Thanks.
The ApplicationSettings
class doesn't support saving settings to the app.config file. That's very much by design; applications that run with a properly secured user account (think Vista UAC) do not have write access to the program's installation folder.
You can fight the system with the ConfigurationManager
class. But the trivial workaround is to go into the Settings designer and change the setting's scope to User. If that causes hardships (say, the setting is relevant to every user), you should put your Options feature in a separate program so you can ask for the privilege elevation prompt. Or forego using a setting.
Under bash, you could simply:
IFS=\| read -ra headline <stores.dat
echo ${#headline[@]}
4
A lot quicker as without forks, and reusable as $headline
hold the full head line. You could, for sample:
printf " - %s\n" "${headline[@]}"
- sid
- storeNo
- latitude
- longitude
Nota This syntax will drive correctly spaces and others characters in column names.
What if some row do contain some extra columns?
This command will search for bigger line, counting separators:
tr -dc $'\n|' <stores.dat |wc -L
3
There are max 3 separators, then 4 fields.
A lookahead regex syntax can help you to achieve your goal. Thus a regex for your example is
.*?quick.*?(?=z)
And it's important to notice the .*?
lazy matching before the (?=z)
lookahead: the expression matches a substring until a first occurrence of the z
letter.
Here is C# code sample:
const string text = "The quick red fox jumped over the lazy brown dogz";
string lazy = new Regex(".*?quick.*?(?=z)").Match(text).Value;
Console.WriteLine(lazy); // The quick red fox jumped over the la
string greedy = new Regex(".*?quick.*(?=z)").Match(text).Value;
Console.WriteLine(greedy); // The quick red fox jumped over the lazy brown dog
As already noted you can't shrink ibdata1 (to do so you need to dump and rebuild), but there's also often no real need to.
Using autoextend (probably the most common size setting) ibdata1 preallocates storage, growing each time it is nearly full. That makes writes faster as space is already allocated.
When you delete data it doesn't shrink but the space inside the file is marked as unused. Now when you insert new data it'll reuse empty space in the file before growing the file any further.
So it'll only continue to grow if you're actually needing that data. Unless you actually need the space for another application there's probably no reason to shrink it.
The most useful shortcut in Vim, IMHO, is the * key.
Put the cursor on a word and hit the * key and you will jump to the next instance of that word.
The # key does the same, but it jumps to the previous instance of the word.
It is truly a time saver.
I'm using Mac OS X Yosemite and Netbeans 8.02, I got the same error and the simple solution I have found is like above, this is useful when you need to include native library in the project. So do the next for Netbeans:
1.- Right click on the Project
2.- Properties
3.- Click on RUN
4.- VM Options: java -Djava.library.path="your_path"
5.- for example in my case: java -Djava.library.path=</Users/Lexynux/NetBeansProjects/NAO/libs>
6.- Ok
I hope it could be useful for someone. The link where I found the solution is here: java.library.path – What is it and how to use
someClassWithinYourSourceDir.getClass().getResourceAsStream();
This is not the code, but the algorithm for very fast searching.
If your list and the value you are looking for are all numbers, this is pretty straightforward. If strings: look at the bottom:
If you also need the original position of your number, look for it in the second, index column.
If your list is not made of numbers, the method still works and will be fastest, but you may need to define a function which can compare/order strings.
Of course, this needs the investment of the sorted() method, but if you keep reusing the same list for checking, it may be worth it.
<style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:colorPrimary">#00397F</item>
<item name="android:textColorPrimary">#22397F</item>
<item name="android:colorAccent">#00397F</item>
<item name="colorPrimaryDark">#22397F</item>
</style>
The color of the buttons and other text can also be changed using appcompat :
I wanna clear something that no one mention before I think.
svg
image or icon<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M4 10.127L12 18.127L20 10.127H4Z" fill="#8E8E93"/> </svg>
try to find it.data:image/svg+xml;utf8,
fill="#8E8E93"
to this fill="%238E8E93"
If you want to add hexadecmal color you should change #
to %23
Here is the html code:
<fieldset>
<label for="editName">Country</label>
<select class="ra-select">
<option value="bangladesh" selected>Bangladesh</option>
<option value="saudi arabia">Saudi Arabia</option>
<option value="us">Uinited State Of America</option>
<option value="india">India</option>
</select>
</fieldset>
Here is the css code:
.ra-select {
width: 30%;
padding: 10px;
/* Replace Default styling (arrow) */
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
background-image: url('data:image/svg+xml;utf8,<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 10.127L12 18.127L20 10.127H4Z" fill="%238E8E93"/></svg>');
background-repeat: no-repeat;
background-position-y: 50%;
background-position-x: 98%;
}
.ra-select:focus,
.ra-select:hover {
outline: none;
border: 1px solid #bbb;
}
.ra-select option {
background-color: #fff;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container check">
<button class="btn">click</button>
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car<br>
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car<br>
</div>
<script>
$('.btn').click(function() {
$('input[type=checkbox]').each(function()
{
this.checked = false;
});
})
</script>
</body>
</html>
I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.
Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.
The module approach works well. If I absolutely need a singleton I prefer the Metaclass approach.
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls,*args,**kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
class MyClass(object):
__metaclass__ = Singleton
After 5.0.13, in stored procedures, you can use dynamic SQL:
delimiter //
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
SET @s = CONCAT('SELECT ',col,' FROM ',tbl );
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
//
delimiter ;
Dynamic SQL does not work in functions or triggers. See the MySQL documentation for more uses.
Just add the <mat-icon>
inside mat-button
or mat-raised-button
. See the example below. Note that I am using material icon instead of your svg for demo purpose:
<button mat-button>
<mat-icon>mic</mat-icon>
Start Recording
</button>
OR
<button mat-raised-button color="accent">
<mat-icon>mic</mat-icon>
Start Recording
</button>
Here is a link to stackblitz demo.
This worked for me. I have done like, when i click on the menu button, im adding or removing the class 'in' because by adding or removing that class the toggle is working by default. 'e.stopPropagation()' is to stop the default animation by bootstrap(i guess) you can also use the 'toggleClass' in place of add or remove class.
$('#ChangeToggle').on('click', function (e) {
if ($('.navbar-collapse').hasClass('in')) {
$('.navbar-collapse').removeClass('in');
e.stopPropagation();
} else {
$('.navbar-collapse').addClass('in');
$('.navbar-collapse').collapse();
}
});
yes, this is valid, and under some circumstances it is even useful. Generally, if you don't need it, don't do it.
What is the difference between
<init-param>
and<context-param>
!?
Single servlet versus multiple servlets.
Other Answers give details, but here is the summary:
A web app, that is, a “context”, is made up of one or more servlets.
<init-param>
defines a value available to a single specific servlet within a context.<context-param>
defines a value available to all the servlets within a context.This is my take on expanding @klimat answer to not losing filtering animation.
public void filter(String query){
int completeListIndex = 0;
int filteredListIndex = 0;
while (completeListIndex < completeList.size()){
Movie item = completeList.get(completeListIndex);
if(item.getName().toLowerCase().contains(query)){
if(filteredListIndex < filteredList.size()) {
Movie filter = filteredList.get(filteredListIndex);
if (!item.getName().equals(filter.getName())) {
filteredList.add(filteredListIndex, item);
notifyItemInserted(filteredListIndex);
}
}else{
filteredList.add(filteredListIndex, item);
notifyItemInserted(filteredListIndex);
}
filteredListIndex++;
}
else if(filteredListIndex < filteredList.size()){
Movie filter = filteredList.get(filteredListIndex);
if (item.getName().equals(filter.getName())) {
filteredList.remove(filteredListIndex);
notifyItemRemoved(filteredListIndex);
}
}
completeListIndex++;
}
}
Basically what it does is looking through a complete list and adding/removing items to a filtered list one by one.
try
cat ~/.mysql_history
this will show you all mysql commands ran on the system
Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).
If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.
For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.
For example:
Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table
Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.
Comment out these two lines in php.ini
;extension=imagick.so
;extension="ixed.5.6.lin"
it should fix the issue.
The reason behind this error is : Flask app is already running, hasn't shut down and in middle of that we try to start another instance by: with app.app_context(): #Code Before we use this with statement we need to make sure that scope of the previous running app is closed.
You can add a parameter in the query like @emailadd to be added in the aspx.cs file where the Stored Procedure is called with cmd.Parameter.AddWithValue.
The trick is that the @emailadd parameter doesn't exist in the table design of the select query, but being added and inserted in the table.
USE [DRDOULATINSTITUTE]
GO
/****** Object: StoredProcedure [dbo].[ReikiInsertRow] Script Date: 5/18/2016 11:12:33 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[ReikiInsertRow]
@Reiki varchar(100),
@emailadd varchar(50)
as
insert into dbo.ReikiPowerDisplay
select Reiki,ReikiDescription, @emailadd from ReikiPower
where Reiki=@Reiki;
Posted By: Aneel Goplani. CIS. 2002. USA
Most of the answers suggest the Array.prototype.indexOf
method, the only problem is that it will not work on any IE version before IE9.
As an alternative I leave you two more options that will work on all browsers:
if (/Foo|Bar|Baz/.test(str)) {
// ...
}
if (str.match("Foo|Bar|Baz")) {
// ...
}
Use Google Guava AbstractScheduledService
as given below:
public class ScheduledExecutor extends AbstractScheduledService {
@Override
protected void runOneIteration() throws Exception {
System.out.println("Executing....");
}
@Override
protected Scheduler scheduler() {
return Scheduler.newFixedRateSchedule(0, 3, TimeUnit.SECONDS);
}
@Override
protected void startUp() {
System.out.println("StartUp Activity....");
}
@Override
protected void shutDown() {
System.out.println("Shutdown Activity...");
}
public static void main(String[] args) throws InterruptedException {
ScheduledExecutor se = new ScheduledExecutor();
se.startAsync();
Thread.sleep(15000);
se.stopAsync();
}
}
If you have more services like this, then registering all services in ServiceManager will be good as all services can be started and stopped together. Read here for more on ServiceManager.
To capture div as PDF you can use https://grabz.it solution. It's got a JavaScript API which is easy and flexible and will allow you to capture the contents of a single HTML element such as a div or a span
In order to implement it you will need to first get an app key and secret and download the (free) SDK.
And now an example.
Let's say you have the HTML:
<div id="features">
<h4>Acme Camera</h4>
<label>Price</label>$399<br />
<label>Rating</label>4.5 out of 5
</div>
<p>Cras ut velit sed purus porttitor aliquam. Nulla tristique magna ac libero tempor, ac vestibulum felisvulput ate. Nam ut velit eget
risus porttitor tristique at ac diam. Sed nisi risus, rutrum a metus suscipit, euismod tristique nulla. Etiam venenatis rutrum risus at
blandit. In hac habitasse platea dictumst. Suspendisse potenti. Phasellus eget vehicula felis.</p>
To capture what is under the features id you will need to:
//add the sdk
<script type="text/javascript" src="grabzit.min.js"></script>
<script type="text/javascript">
//login with your key and secret.
GrabzIt("KEY", "SECRET").ConvertURL("http://www.example.com/my-page.html",
{"target": "#features", "format": "pdf"}).Create();
</script>
Please note the target: #feature
. #feature
is you CSS selector, like in the previous example. Now, when the page is loaded an image screenshot will now be created in the same location as the script tag, which will contain all of the contents of the features div and nothing else.
The are other configuration and customization you can do to the div-screenshot mechanism, please check them out here
Sharing working and relevant code from our project:
//documentsArray is the list of sampleCollection objects
sampleCollection.insertMany(documentsArray)
.then((res) => {
console.log("insert sampleCollection result ", res);
})
.catch(err => {
console.log("bulk insert sampleCollection error ", err);
});
If you setup your select like the following:
<select ng-model="myselect" ng-options="b for b in options track by b"></select>
you will get:
<option value="var1">var1</option>
<option value="var2">var2</option>
<option value="var3">var3</option>
working fiddle: http://jsfiddle.net/x8kCZ/15/
#define
can lead to unexpected results:
#include <iostream>
#define x 500
#define y x + 5
int z = y * 2;
int main()
{
std::cout << "y is " << y;
std::cout << "\nz is " << z;
}
Outputs an incorrect result:
y is 505
z is 510
However, if you replace this with constants:
#include <iostream>
const int x = 500;
const int y = x + 5;
int z = y * 2;
int main()
{
std::cout << "y is " << y;
std::cout << "\nz is " << z;
}
It outputs the correct result:
y is 505
z is 1010
This is because #define
simply replaces the text. Because doing this can seriously mess up order of operations, I would recommend using a constant variable instead.
I tried all the solutions here but none of them worked for me. Again, my site runs fine but I don't have intellisense and get red wavy lines under a lot of things in my views that Visual Studio does not recognize, one of them being Html.BeginForm()
, as well as anything having to do with ViewBag
.
I'm working with a new MVC 5 project. After hours of comparing web.config lines, I finally found what fixed it for me.
My web.config in my root had the following line:
<system.web>
<compilation debug="true" targetFramework="4.5" />
<!-- ... -->
</system.web>
I compared to a previous project not using MVC 5, and copied over a block I noticed was missing from the new one, which was the following:
<system.web>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<!-- ... -->
</system.web>
I copied the above block over to my new project's web.config in the root, changing the versions to match the numbers for each assembly found in my project references (right-clicking each reference mentioned and selecting "Properties", "Version" is given at the bottom of the properties window for the selected reference).
After implementing the above, I now have intellisense and don't get any unknown red lines under things like Html.BeginForm
, ViewBag.Title
, etc.
To write a newline use \n
not /n
the latter is just a slash and a n
Your database was shut down because of insufficient memory! You can edit the file my.cnf base below graph to resolve it
performance_schema_max_table_instances=200
table_definition_cache=200
table_open_cache=128
You can determin mousewhell direction.
$(window).on('mousewheel DOMMouseScroll', function (e) {
var delta = e.originalEvent.wheelDelta ?
e.originalEvent.wheelDelta : -e.originalEvent.detail;
if (delta >= 0) {
console.log('scroll up');
} else {
console.log('scroll down');
}
});
Thanks for your answers. I didn't understand what type of object "MyTable" was (in your answers) and the following code gave me the error shown below.
DataTable dt = ds.Tables[0];
var name = from r in dt
where r.ID == 0
select r.Name;
Could not find an implementation of the query pattern for source type 'System.Data.DataTable'. 'Where' not found
So I continued my googling and found something that does work:
var rowColl = ds.Tables[0].AsEnumerable();
string name = (from r in rowColl
where r.Field<int>("ID") == 0
select r.Field<string>("NAME")).First<string>();
What do you think?
In your Dockerfile use this command:
CMD ["sh", "-c", "tail -f /dev/null"]
Build your docker image.
kubectl run debug-container -it --image=<your-image>
I'm able to modify a script variable value by assignment in the Console. Seems simplest.
x = -x;
This is probably the most trivial question I have ever seen anywhere.
... and why you would call this trivial function 'reverse()' is another mystery.
Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf
between host and guest (there is known performance issues if there are large numbers of files/directories).
/vagrant
in guestVagrant is mounting the current working directory (where Vagrantfile
resides) as /vagrant
in the guest, this is the default behaviour.
See docs
NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.
You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true
in your Vagrantfile
.
Based on the output /tmp
on host was NOT mounted during up time.
Use VAGRANT_INFO=debug vagrant up
or VAGRANT_INFO=debug vagrant reload
to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp
on host should be drwxrwxrwt
).
I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)
config.vm.synced_folder "/tmp", "/tmp/src"
output
$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src
Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw)
.
You can use // instead of single /. That converts to int
directly.
I use the term program to include applications (apps), utilities and even operating systems like windows, linux and mac OS. We kinda need an overall term for all the different terms available. It might be wrong but works for me. :)
in my case .. setting parameterLimit:50000
fixed the problem
app.use( bodyParser.json({limit: '50mb'}) );
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true,
parameterLimit:50000
}));
Here's the jQuery way to do it:
$('#calendar').attr('src', loc);
I encountered the exact same problem today, Ryan.
In my src (or your root) directory, my log4j.properties file now has the following addition
# https://issues.apache.org/jira/browse/AXIS2-4363
log4j.category.org.apache.axiom=WARN
Thanks for the heads up as to how to do this, Benjamin.
As I was searching for Scala version, all I could find was McDowell's JNA code above. I include my Scala port here, as there currently isn't anywhere more appropriate.
import com.sun.jna.platform.win32._
object jna {
def getHome: java.io.File = {
if (!com.sun.jna.Platform.isWindows()) {
new java.io.File(System.getProperty("user.home"))
}
else {
val pszPath: Array[Char] = new Array[Char](WinDef.MAX_PATH)
new java.io.File(Shell32.INSTANCE.SHGetSpecialFolderPath(null, pszPath, ShlObj.CSIDL_MYDOCUMENTS, false) match {
case true => new String(pszPath.takeWhile(c => c != '\0'))
case _ => System.getProperty("user.home")
})
}
}
}
As with the Java version, you will need to add Java Native Access, including both jar files, to your referenced libraries.
It's nice to see that JNA now makes this much easier than when the original code was posted.
As per 'dtb' you need to use HttpStatusCode, but following 'zeldi' you need to be extra careful with code responses >= 400.
This has worked for me:
HttpWebResponse response = null;
HttpStatusCode statusCode;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
response = (HttpWebResponse)we.Response;
}
statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
sResponse = reader.ReadToEnd();
Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());
This button class with height autoresizing for text (for Xamarin but can be rewritten for other language)
[Register(nameof(ResizableButton))]
public class ResizableButton : UIButton
{
NSLayoutConstraint _heightConstraint;
public bool NeedsUpdateHeightConstraint { get; private set; } = true;
public ResizableButton(){}
public ResizableButton(UIButtonType type) : base(type){}
public ResizableButton(NSCoder coder) : base(coder){}
public ResizableButton(CGRect frame) : base(frame){}
protected ResizableButton(NSObjectFlag t) : base(t){}
protected internal ResizableButton(IntPtr handle) : base(handle){}
public override void LayoutSubviews()
{
base.LayoutSubviews();
UpdateHeightConstraint();
InvalidateIntrinsicContentSize();
}
public override void SetTitle(string title, UIControlState forState)
{
NeedsUpdateHeightConstraint = true;
base.SetTitle(title, forState);
}
private void UpdateHeightConstraint()
{
if (!NeedsUpdateHeightConstraint)
return;
NeedsUpdateHeightConstraint = false;
var labelSize = TitleLabel.SizeThatFits(new CGSize(Frame.Width - TitleEdgeInsets.Left - TitleEdgeInsets.Right, float.MaxValue));
var rect = new CGRect(Frame.X, Frame.Y, Frame.Width, labelSize.Height + TitleEdgeInsets.Top + TitleEdgeInsets.Bottom);
if (_heightConstraint != null)
RemoveConstraint(_heightConstraint);
_heightConstraint = NSLayoutConstraint.Create(this, NSLayoutAttribute.Height, NSLayoutRelation.Equal, 1, rect.Height);
AddConstraint(_heightConstraint);
}
public override CGSize IntrinsicContentSize
{
get
{
var labelSize = TitleLabel.SizeThatFits(new CGSize(Frame.Width - TitleEdgeInsets.Left - TitleEdgeInsets.Right, float.MaxValue));
return new CGSize(Frame.Width, labelSize.Height + TitleEdgeInsets.Top + TitleEdgeInsets.Bottom);
}
}
}
Just Try in button.
<button onclick="location.reload();location.href='url_name'"
id="myButton" class="btn request-callback" >Explore More</button>
Using href
<a href="#" class="know_how" onclick="location.reload();location.href='url_name'">Know More</a>
You can do it like this:
alert(parseFloat("1.1531531414")); // alerts the float
parseFloat = function(input) { return 1; };
alert(parseFloat("1.1531531414")); // alerts '1'
Check out a working example here: http://jsfiddle.net/LtjzW/1/
You have to define your exception elsewhere as a new class
public class YourCustomException extends Exception{
//Required inherited methods here
}
Then you can throw and catch YourCustomException as much as you'd like.
Your negative lookahead solution would e.g. be this:
\\(?:.(?!\\))+$
See it here on Regexr
Had the same issue with arrays, here is how to do it if you're manipulating arrays too :
array_name="ARRAY_NAME"
ARRAY_NAME=("Val0" "Val1" "Val2")
ARRAY=$array_name[@]
echo "ARRAY=${ARRAY}"
ARRAY=("${!ARRAY}")
echo "ARRAY=${ARRAY[@]}"
echo "ARRAY[0]=${ARRAY[0]}"
echo "ARRAY[1]=${ARRAY[1]}"
echo "ARRAY[2]=${ARRAY[2]}"
This will output :
ARRAY=ARRAY_NAME[@]
ARRAY=Val0 Val1 Val2
ARRAY[0]=Val0
ARRAY[1]=Val1
ARRAY[2]=Val2
As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.
This is some pseudocodish JavaScript:
Client:
var websocket = new WebSocket("server address");
websocket.onmessage = function(str) {
console.log("Someone sent: ", str);
};
// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
id: "client1"
}));
// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
to: "client2",
data: "foo"
}));
Server:
var clients = {};
server.on("data", function(client, str) {
var obj = JSON.parse(str);
if("id" in obj) {
// New client, add it to the id/client object
clients[obj.id] = client;
} else {
// Send data to the client requested
clients[obj.to].send(obj.data);
}
});
I had the exact same error but with slightly different format and root-cause, and since this is the first Q&A that pops up when you search for "time data does not match format", I thought I'd leave the mistake I made for future viewers:
My initial code:
start = datetime.strptime('05-SEP-19 00.00.00.000 AM', '%d-%b-%y %I.%M.%S.%f %p')
Where I used %I
to parse the hours and %p
to parse 'AM/PM'.
The error:
ValueError: time data '05-SEP-19 00.00.00.000000 AM' does not match format '%d-%b-%y %I.%M.%S.%f %p'
I was going through the datetime docs and finally realized in 12-hour format %I
, there is no 00... once I changed 00.00.00
to 12.00.00
, the problem was resolved.
So it's either 01-12 using %I
with %p
, or 00-23 using %H
.
They changed print
in Python 3. In 2 it was a statement, now it is a function and requires parenthesis.
Here's the docs from Python 3.0.
Inspired by Eric's answer, here is my solution to this problem for selenium 3.7.0. Compared with the solution at http://tarunlalwani.com/post/reusing-existing-browser-session-selenium/, the advantage is that there won't be a blank browser window each time I connect to the existing session.
import warnings
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.remote.errorhandler import ErrorHandler
from selenium.webdriver.remote.file_detector import LocalFileDetector
from selenium.webdriver.remote.mobile import Mobile
from selenium.webdriver.remote.remote_connection import RemoteConnection
from selenium.webdriver.remote.switch_to import SwitchTo
from selenium.webdriver.remote.webdriver import WebDriver
# This webdriver can directly attach to an existing session.
class AttachableWebDriver(WebDriver):
def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub',
desired_capabilities=None, browser_profile=None, proxy=None,
keep_alive=False, file_detector=None, session_id=None):
"""
Create a new driver that will issue commands using the wire protocol.
:Args:
- command_executor - Either a string representing URL of the remote server or a custom
remote_connection.RemoteConnection object. Defaults to 'http://127.0.0.1:4444/wd/hub'.
- desired_capabilities - A dictionary of capabilities to request when
starting the browser session. Required parameter.
- browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object.
Only used if Firefox is requested. Optional.
- proxy - A selenium.webdriver.common.proxy.Proxy object. The browser session will
be started with given proxy settings, if possible. Optional.
- keep_alive - Whether to configure remote_connection.RemoteConnection to use
HTTP keep-alive. Defaults to False.
- file_detector - Pass custom file detector object during instantiation. If None,
then default LocalFileDetector() will be used.
"""
if desired_capabilities is None:
raise WebDriverException("Desired Capabilities can't be None")
if not isinstance(desired_capabilities, dict):
raise WebDriverException("Desired Capabilities must be a dictionary")
if proxy is not None:
warnings.warn("Please use FirefoxOptions to set proxy",
DeprecationWarning)
proxy.add_to_capabilities(desired_capabilities)
self.command_executor = command_executor
if type(self.command_executor) is bytes or isinstance(self.command_executor, str):
self.command_executor = RemoteConnection(command_executor, keep_alive=keep_alive)
self.command_executor._commands['GET_SESSION'] = ('GET', '/session/$sessionId') # added
self._is_remote = True
self.session_id = session_id # added
self.capabilities = {}
self.error_handler = ErrorHandler()
self.start_client()
if browser_profile is not None:
warnings.warn("Please use FirefoxOptions to set browser profile",
DeprecationWarning)
if session_id:
self.connect_to_session(desired_capabilities) # added
else:
self.start_session(desired_capabilities, browser_profile)
self._switch_to = SwitchTo(self)
self._mobile = Mobile(self)
self.file_detector = file_detector or LocalFileDetector()
self.w3c = True # added hardcoded
def connect_to_session(self, desired_capabilities):
response = self.execute('GET_SESSION', {
'desiredCapabilities': desired_capabilities,
'sessionId': self.session_id,
})
# self.session_id = response['sessionId']
self.capabilities = response['value']
To use it:
if use_existing_session:
browser = AttachableWebDriver(command_executor=('http://%s:4444/wd/hub' % ip),
desired_capabilities=(DesiredCapabilities.INTERNETEXPLORER),
session_id=session_id)
self.logger.info("Using existing browser with session id {}".format(session_id))
else:
browser = AttachableWebDriver(command_executor=('http://%s:4444/wd/hub' % ip),
desired_capabilities=(DesiredCapabilities.INTERNETEXPLORER))
self.logger.info('New session_id : {}'.format(browser.session_id))
Some points.
Use $.data Instead of $.fn.data
// regular
$(elem).data(key,value);
// 10x faster
$.data(elem,key,value);
Then, You can get the previous value through the event object, without complicating your life:
$('#myInputElement').change(function(event){
var defaultValue = event.target.defaultValue;
var newValue = event.target.value;
});
Be warned that defaultValue is NOT the last set value. It's the value the field was initialized with. But you can use $.data to keep track of the "oldValue"
I recomend you always declare the "event" object in your event handler functions and inspect them with firebug (console.log(event)) or something. You will find a lot of useful things there that will save you from creating/accessing jquery objects (which are great, but if you can be faster...)
I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.
Code with Excepion
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
After Fixes:
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[102400];
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
Below is the relevant code example for Angular 2/4/5 projects:
let headers = new Headers({
'Content-Type': 'application/json'
});
let options = new RequestOptions({
headers: headers,
body: {
id: 123
}
});
return this.http.delete("http//delete.example.com/delete", options)
.map((response: Response) => {
return response.json()
})
.catch(err => {
return err;
});
Notice that
body
is passed throughRequestOptions
change does only work on input form elements.
you could just trigger a function after your XML / XSL transformation or make a listener:
var html = $('#laneconfigdisplay').html()
setInterval(function(){ if($('#laneconfigdisplay').html() != html){ alert('woo'); html = $('#laneconfigdisplay').html() } }, 10000) //checks your content box all 10 seconds and triggers alert when content has changed...
In my case there were uncommitted changes from the previous branch lingering around. I used following commands and then delete worked.
git checkout *
git checkout master
git branch -D
https://dev.mysql.com/doc/refman/8.0/en/alter-table.html
You can also set a default value for the column just add the DEFAULT keyword followed by the value.
ALTER TABLE [table_name] MODIFY [column_name] [NEW DATA TYPE] DEFAULT [VALUE];
This is also working for MariaDB (tested version 10.2)
You can save this in your shell.rc
or just put in console
function absolute_path { echo "$PWD/$1"; }
alias ap="absolute_path"
example:
ap somefile.txt
will output
/home/user/somefile.txt
How about this solution?
It doesn't use the Thread class, but it IS concurrent, and in a way it does exactly what you request
ExecutorService pool = Executors.newFixedThreadPool(2); // creates a pool of threads for the Future to draw from
Future<Integer> value = pool.submit(new Callable<Integer>() {
@Override
public Integer call() {return 2;}
});
Now all you do is say value.get()
whenever you need to grab your returned value, the thread is started the very second you give value
a value so you don't ever have to say threadName.start()
on it.
What a Future
is, is a promise to the program, you promise the program that you'll get it the value it needs sometime in the near future
If you call .get()
on it before it's done, the thread that's calling it will simply just wait until it's done
Use the following code to check if a folder exists. It works on both Windows & Linux platforms.
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char* argv[])
{
const char* folder;
//folder = "C:\\Users\\SaMaN\\Desktop\\Ppln";
folder = "/tmp";
struct stat sb;
if (stat(folder, &sb) == 0 && S_ISDIR(sb.st_mode)) {
printf("YES\n");
} else {
printf("NO\n");
}
}
Developers are often confused by what a callback is because of the name of the damned thing.
A callback function is a function which is:
A nice way of imagining how a callback function works is that it is a function that is "called at the back" of the function it is passed into.
Maybe a better name would be a "call after" function.
This construct is very useful for asynchronous behaviour where we want an activity to take place whenever a previous event completes.
Pseudocode:
// A function which accepts another function as an argument
// (and will automatically invoke that function when it completes - note that there is no explicit call to callbackFunction)
funct printANumber(int number, funct callbackFunction) {
printout("The number you provided is: " + number);
}
// a function which we will use in a driver function as a callback function
funct printFinishMessage() {
printout("I have finished printing numbers.");
}
// Driver method
funct event() {
printANumber(6, printFinishMessage);
}
Result if you called event():
The number you provided is: 6
I have finished printing numbers.
The order of the output here is important. Since callback functions are called afterwards, "I have finished printing numbers" is printed last, not first.
Callbacks are so-called due to their usage with pointer languages. If you don't use one of those, don't labour over the name 'callback'. Just understand that it is just a name to describe a method that's supplied as an argument to another method, such that when the parent method is called (whatever condition, such as a button click, a timer tick etc) and its method body completes, the callback function is then invoked.
Some languages support constructs where multiple callback function arguments are supported, and are called based on how the parent function completes (i.e. one callback is called in the event that the parent function completes successfully, another is called in the event that the parent function throws a specific error, etc).
Here is a two steps solution here is a hack to IE10 and 11
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
/* IE10+ specific styles go here */
}
because IE10 and IE11 Supports -ms-high-cotrast you can take the advantage of this to target this two browsers
and if you want to exclude the IE10 from this you must create a IE10 specific code as follow it's using the user agent trick you must add this Javascript
var doc = document.documentElement;
doc.setAttribute('data-useragent', navigator.userAgent);
and this HTML tag
<html data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)">
and now you can write your CSS code like this
html[data-useragent*='MSIE 10.0'] h1 {
color: blue;
}
for more information please refer to this websites,wil tutorail, Chris Tutorial
And if you want to target IE11 and later,here is what I've found:
_:-ms-fullscreen, :root .selector {}
Here is a great resource for getting more information: browserhacks.com
You need to put that code into the constructor of your class:
private Reminders reminder = new Reminders();
private dynamic defaultReminder;
public YourClass()
{
defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}
The reason is that you can't use one instance variable to initialize another one using a field initializer.
Linux Mint 19. Helped for me:
sudo apt install tk-dev
P.S. Recompile python interpreter after package install.
The git pull -X theirs
answers may create an ugly merge commit, or issue an
error: Your local changes to the following files would be overwritten by merge:
If you want to simply ignore any local modifications to files from the repo, for example on a client that should always be a mirror of an origin, run this (replace master
with the branch you want):
git fetch && git reset --hard origin/master
How does it work? git fetch
does git pull
but without merge. Then git reset --hard
makes your working tree match the last commit. All of your local changes to files in the repo will be discarded, but new local files will be left alone.
^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$
Regular expression to match valid UK postcodes. In the UK postal system not all letters are used in all positions (the same with vehicle registration plates) and there are various rules to govern this. This regex takes into account those rules. Details of the rules: First half of postcode Valid formats [A-Z][A-Z][0-9][A-Z] [A-Z][A-Z][0-9][0-9] [A-Z][0-9][0-9] [A-Z][A-Z][0-9] [A-Z][A-Z][A-Z] [A-Z][0-9][A-Z] [A-Z][0-9] Exceptions Position - First. Contraint - QVX not used Position - Second. Contraint - IJZ not used except in GIR 0AA Position - Third. Constraint - AEHMNPRTVXY only used Position - Forth. Contraint - ABEHMNPRVWXY Second half of postcode Valid formats [0-9][A-Z][A-Z] Exceptions Position - Second and Third. Contraint - CIKMOV not used
I use this simple function for JQuery based project
var pointerEventToXY = function(e){
var out = {x:0, y:0};
if(e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel'){
var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
out.x = touch.pageX;
out.y = touch.pageY;
} else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
out.x = e.pageX;
out.y = e.pageY;
}
return out;
};
example:
$('a').on('mousedown touchstart', function(e){
console.log(pointerEventToXY(e)); // will return obj ..kind of {x:20,y:40}
})
hope this will be usefull for you ;)
Adding to @adardesign
's answer, if you want to reset all files that have been added to assume-unchanged
list to no-assume-unchanged
in one go, you can do the following:
git ls-files -v | grep '^h' | sed 's/^..//' | sed 's/\ /\\ /g' | xargs -I FILE git update-index --no-assume-unchanged FILE || true
This will just strip out the two characters output from grep i.e. "h "
, then escape any spaces that may be present in file names, and finally || true
will prevent the command to terminate prematurely in case some files in the loop has errors.
You need scheme, host, path and queryString
@string.Format("{0}://{1}{2}{3}", Context.Request.Scheme, Context.Request.Host, Context.Request.Path, Context.Request.QueryString)
or using new C#6 feature "String interpolation"
@($"{Context.Request.Scheme}://{Context.Request.Host}{Context.Request.Path}{Context.Request.QueryString}")
If you have a array of objects you can do like this:
myArrayObjects = myArrayObjects.sort(function(a, b) {
return a.name.localeCompare(b.name, undefined, {
numeric: true,
sensitivity: 'base'
});
});
var myArrayObjects = [{_x000D_
"id": 1,_x000D_
"name": "1 example"_x000D_
},_x000D_
{_x000D_
"id": 2,_x000D_
"name": "100 example"_x000D_
},_x000D_
{_x000D_
"id": 3,_x000D_
"name": "12 example"_x000D_
},_x000D_
{_x000D_
"id": 4,_x000D_
"name": "5 example"_x000D_
},_x000D_
_x000D_
]_x000D_
_x000D_
myArrayObjects = myArrayObjects.sort(function(a, b) {_x000D_
return a.name.localeCompare(b.name, undefined, {_x000D_
numeric: true,_x000D_
sensitivity: 'base'_x000D_
});_x000D_
});_x000D_
console.log(myArrayObjects);
_x000D_
def extract_text_features(feature):
...
...
return pd.Series((feature1, feature2))
df[['NewFeature1', 'NewFeature1']] = df[['feature']].apply(extract_text_features, axis=1)
Here the a dataframe with a single feature is being converted to two new features. Give this a try too.
I put together a little category on UITableView based on Anna Karenina's excellent answer.
Like this you'll have a convenient delegate method like you're used to when dealing with regular table views. Check it out:
// UITableView+LongPress.h
#import <UIKit/UIKit.h>
@protocol UITableViewDelegateLongPress;
@interface UITableView (LongPress) <UIGestureRecognizerDelegate>
@property(nonatomic,assign) id <UITableViewDelegateLongPress> delegate;
- (void)addLongPressRecognizer;
@end
@protocol UITableViewDelegateLongPress <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didRecognizeLongPressOnRowAtIndexPath:(NSIndexPath *)indexPath;
@end
// UITableView+LongPress.m
#import "UITableView+LongPress.h"
@implementation UITableView (LongPress)
@dynamic delegate;
- (void)addLongPressRecognizer {
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 1.2; //seconds
lpgr.delegate = self;
[self addGestureRecognizer:lpgr];
}
- (void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
CGPoint p = [gestureRecognizer locationInView:self];
NSIndexPath *indexPath = [self indexPathForRowAtPoint:p];
if (indexPath == nil) {
NSLog(@"long press on table view but not on a row");
}
else {
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
// I am not sure why I need to cast here. But it seems to be alright.
[(id<UITableViewDelegateLongPress>)self.delegate tableView:self didRecognizeLongPressOnRowAtIndexPath:indexPath];
}
}
}
If you want to use this in a UITableViewController, you probably need to subclass and conform to the new protocol.
It works great for me, hope it helps others!
I would suggest to use Arrays.asList() for single line initialization. For different ways of declaring and initializing a List you can also refer Initialization of ArrayList in Java
I think it's a little simpler to use the dplyr
functions select
and left_join
; at least it's easier for me to understand. The join function from dplyr
are made to mimic sql arguments.
library(tidyverse)
DF2 <- DF2 %>%
select(client, LO)
joined_data <- left_join(DF1, DF2, by = "Client")
You don't actually need to use the "by" argument in this case because the columns have the same name.
For primitive types (e.g. numbers, booleans, strings, etc.), there is no difference between toBe
and toEqual
; either one will work for 5
, true
, or "the cake is a lie"
.
To understand the difference between toBe
and toEqual
, let's imagine three objects.
var a = { bar: 'baz' },
b = { foo: a },
c = { foo: a };
Using a strict comparison (===
), some things are "the same":
> b.foo.bar === c.foo.bar
true
> b.foo.bar === a.bar
true
> c.foo === b.foo
true
But some things, even though they are "equal", are not "the same", since they represent objects that live in different locations in memory.
> b === c
false
Jasmine's toBe
matcher is nothing more than a wrapper for a strict equality comparison
expect(c.foo).toBe(b.foo)
is the same thing as
expect(c.foo === b.foo).toBe(true)
Don't just take my word for it; see the source code for toBe.
But b
and c
represent functionally equivalent objects; they both look like
{ foo: { bar: 'baz' } }
Wouldn't it be great if we could say that b
and c
are "equal" even if they don't represent the same object?
Enter toEqual
, which checks "deep equality" (i.e. does a recursive search through the objects to determine whether the values for their keys are equivalent). Both of the following tests will pass:
expect(b).not.toBe(c);
expect(b).toEqual(c);
Hope that helps clarify some things.
Adding msecs was the better option, Thanks. Here is my amendment using this with Python 3.5.3 in Blender
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d %(levelname)s:\t%(message)s', datefmt='%Y-%m-%d %H:%M:%S')
log = logging.getLogger(__name__)
log.info("Logging Info")
log.debug("Logging Debug")
This is an improved version of @schuttek's answer. It is improved because it correctly return false for primitives (e.g. isSubclassOf(int.class, Object.class) => false) and also correctly handles interfaces (e.g. isSubclassOf(HashMap.class, Map.class) => true).
static public boolean isSubclassOf(final Class<?> clazz, final Class<?> possibleSuperClass)
{
if (clazz == null || possibleSuperClass == null)
{
return false;
}
else if (clazz.equals(possibleSuperClass))
{
return true;
}
else
{
final boolean isSubclass = isSubclassOf(clazz.getSuperclass(), possibleSuperClass);
if (!isSubclass && clazz.getInterfaces() != null)
{
for (final Class<?> inter : clazz.getInterfaces())
{
if (isSubclassOf(inter, possibleSuperClass))
{
return true;
}
}
}
return isSubclass;
}
}
Please note that, you should allow "system" key as well
$(element).keydown(function (e) {
var code = (e.keyCode ? e.keyCode : e.which), value;
if (isSysKey(code) || code === 8 || code === 46) {
return true;
}
if (e.shiftKey || e.altKey || e.ctrlKey) {
return ;
}
if (code >= 48 && code <= 57) {
return true;
}
if (code >= 96 && code <= 105) {
return true;
}
return false;
});
function isSysKey(code) {
if (code === 40 || code === 38 ||
code === 13 || code === 39 || code === 27 ||
code === 35 ||
code === 36 || code === 37 || code === 38 ||
code === 16 || code === 17 || code === 18 ||
code === 20 || code === 37 || code === 9 ||
(code >= 112 && code <= 123)) {
return true;
}
return false;
}
>>> points = {'a': (3, 4), 'c': (5, 5), 'b': (1, 2), 'd': (3, 3)}
>>> dict(filter(lambda x: (x[1][0], x[1][1]) < (5, 5), points.items()))
{'a': (3, 4), 'b': (1, 2), 'd': (3, 3)}
Executing the script below worked for me.
sudo chown $USER /home/$USER/.jupyter
Copying a string can be done two ways either copy the location a = "a" b = a or you can clone which means b wont get affected when a is changed which is done by a = 'a' b = a[:]
I see this being possible using either some regex, or a few substr calls (assuming the input is always of that format, and doesn't change length etc.)
something like
$in = "+11234567890"; $output = substr($in,2,3)."-".substr($in,6,3)."-".substr($in,10,4);
should do it.
It's a linker problem. Include the static library path into your project.
For Qt Creator open the project file .pro
and add the following line:
LIBS += -L<path for boost libraries in the system> -lboost_system
In my case Ubuntu x86_64:
LIBS += -L/usr/lib/x86_64-linux-gnu -lboost_system
For Codeblocks, open up Settings->Compiler...->Linker
settings tab and add:
boost_system
to the Link libraries text widget and press OK button.
ADB Build-Tools Will Not be downloaded automatically, by command android update sdk --no-ui
So for installing Buil-Tool type (in console):
android list sdk --all
Remember the number that is listed before the item and execute the following:
android update sdk -u --all --filter <number>
commands should be typed in /YourFolder/android-sdk-linux/tools
Also for remote folder (server opened by ssh for example) type:
**./android** list sdk --all
**./android** update sdk -u --all --filter <number>
For simple list of ADB packages type in terminal:
android list sdk
for install all packages:
android update sdk --no-ui
Or with filters (comma is separator):
android update sdk --no-ui --filter 3,5,8,14
(I have extracted this extension from the jQuery UI framework)
Works with: empty()
and html()
and remove()
$.cleanData = ( function( orig ) {
return function( elems ) {
var events, elem, i;
for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
try {
// Only trigger remove when necessary to save time
events = $._data( elem, "events" );
if ( events && events.remove ) {
$( elem ).triggerHandler( "remove" );
}
// Http://bugs.jquery.com/ticket/8235
} catch ( e ) {}
}
orig( elems );
};
} )( $.cleanData );
With this solution you can also unbind the event handler.
$("YourElemSelector").off("remove");
Try it! - Example
$.cleanData = (function(orig) {_x000D_
return function(elems) {_x000D_
var events, elem, i;_x000D_
for (i = 0;_x000D_
(elem = elems[i]) != null; i++) {_x000D_
try {_x000D_
_x000D_
// Only trigger remove when necessary to save time_x000D_
events = $._data(elem, "events");_x000D_
if (events && events.remove) {_x000D_
$(elem).triggerHandler("remove");_x000D_
}_x000D_
_x000D_
// Http://bugs.jquery.com/ticket/8235_x000D_
} catch (e) {}_x000D_
}_x000D_
orig(elems);_x000D_
};_x000D_
})($.cleanData);_x000D_
_x000D_
_x000D_
$("#DivToBeRemoved").on("remove", function() {_x000D_
console.log("div was removed event fired");_x000D_
});_x000D_
_x000D_
$("p").on("remove", function() {_x000D_
console.log("p was removed event fired");_x000D_
});_x000D_
_x000D_
$("span").on("remove", function() {_x000D_
console.log("span was removed event fired");_x000D_
});_x000D_
_x000D_
// $("span").off("remove");_x000D_
_x000D_
$("#DivToBeRemoved").on("click", function() {_x000D_
console.log("Div was clicked");_x000D_
});_x000D_
_x000D_
function RemoveDiv() {_x000D_
// $("#DivToBeRemoved").parent().html(""); _x000D_
$("#DivToBeRemoved").remove();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h3>OnRemove event handler attached to elements `div`, `p` and `span`.</h3>_x000D_
<div class="container">_x000D_
<br>_x000D_
<button onclick="RemoveDiv();">Click here to remove div below</button>_x000D_
<div id="DivToBeRemoved">_x000D_
DIV TO BE REMOVED _x000D_
contains 1 p element _x000D_
which in turn contains a span element_x000D_
<p>i am p (within div)_x000D_
<br><br><span>i am span (within div)</span></p>_x000D_
</div>_x000D_
</div>
_x000D_
Additional Demo - jsBin
You can make an AMI of an existing instance, and then launch other instances using that AMI.
If you want input comma separated string as input & apply in in query in that then you can make Function like:
create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1))
returns @temptable TABLE (items varchar(MAX))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end;
You can use it like :
Declare @Values VARCHAR(MAX);
set @Values ='1,2,5,7,10';
Select * from DBTable
Where id in (select items from [dbo].[Split] (@Values, ',') )
Alternatively if you don't have comma-separated string as input, You can try Table variable
OR TableType
Or Temp table
like: INSERT using LIST into Stored Procedure
I use it in form of a meta box. Here is a function that dumps values of all the meta data for post.
function dump_all_meta(){
echo "<h3>All Post Meta</h3>";
// Get all the data.
$getPostCustom=get_post_custom();
foreach( $getPostCustom as $name=>$value ) {
echo "<strong>".$name."</strong>"." => ";
foreach($getPostCustom as $name=>$value) {
echo "<strong>".$name."</strong>"." => ";
foreach($value as $nameAr=>$valueAr) {
echo "<br /> ";
echo $nameAr." => ";
echo var_dump($valueAr);
}
echo "<br /><br />";
}
} // Callback funtion ended.
Hope it helps. You can use it inside a meta box or at the front-end.
I have a similar issue running Linux systems. After the system was booted, a container with a restart policy of "unless-stopped" would not restart automatically unless I typed a command that used docker in some way such as "docker ps". I was surprised as I expected that command to just report some status information. Next I tried the command "systemctl status docker". On a system where no docker commands had been run, this command reported the following:
? docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)
Active: inactive (dead) TriggeredBy: ? docker.socket
Docs: https://docs.docker.com
On a system where "docker ps" had been run with no other Docker commands, I got the following:
? docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)
Active: active (running) since Sun 2020-11-22 08:33:23 PST; 1h 25min ago
TriggeredBy: ? docker.socket
Docs: https://docs.docker.com
Main PID: 3135 (dockerd)
Tasks: 13
Memory: 116.9M
CGroup: /system.slice/docker.service
+-3135 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
... [various messages not shown ]
The most likely explanation is that Docker waits for some docker command before fully initializing and starting containers. You could presumably run "docker ps" in a systemd unit file at a point after all the services your containers need have been initialized. I've tested this by putting a file named docker-onboot.service in the directory /lib/systemd/system with the following contents:
[Unit]
# This service is provided to force Docker containers
# that should automatically restart to restart when the system
# is booted. While the Docker daemon will start automatically,
# it will not be fully initialized until some Docker command
# is actually run. This unit merely runs "docker ps": any
# Docker command will result in the Docker daemon completing
# its initialization, at which point all containers that can be
# automatically restarted after booting will be restarted.
#
Description=Docker-Container Startup on Boot
Requires=docker.socket
After=docker.socket network-online.target containerd.service
[Service]
Type=oneshot
ExecStart=/usr/bin/docker ps
[Install]
WantedBy=multi-user.target
So far (one test, with this service enabled), the container started when the computer was booted. I did not try a dependency on docker.service because docker.service won't start until a docker command is run. The next test will be with the docker-onboot disabled (to see if the WantedBy dependency will automatically start it).