Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-
doNothing().when(InternalUtils.class); //This is the preferred way
//to mock static void methods.
InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.
mockStatic(Internalutils.class);
So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.
@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {
@Mock
private InternalService.Order order;
private InternalService internalService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
internalService = new InternalService();
}
@Test
public void processOrder() throws Exception {
Mockito.when(order.isSuccessful()).thenReturn(true);
PowerMockito.mockStatic(InternalService.InternalUtils.class);
internalService.processOrder(order);
PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
}
}
These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.
PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
This is code of my class, sendEmail api twice.
public class InternalService {
public void processOrder(Order order) {
if (order.isSuccessful()) {
InternalUtils.sendEmail("", new String[1], "", "");
InternalUtils.sendEmail("", new String[1], "", "");
}
}
public static class InternalUtils{
public static void sendEmail(String from, String[] to, String msg, String body){
}
}
public class Order{
public boolean isSuccessful(){
return true;
}
}
}
As it is calling twice you just need to change the verify(times(2))... that's all.
The following is a test class that mocks private static final Logger named log
in class LogUtil
.
In addition to mocking the getLogger
factory call, it is necessary to explicitly set the field using reflection, in @BeforeClass
public class LogUtilTest {
private static Logger logger;
private static MockedStatic<LoggerFactory> loggerFactoryMockedStatic;
/**
* Since {@link LogUtil#log} being a static final variable it is only initialized once at the class load time
* So assertions are also performed against the same mock {@link LogUtilTest#logger}
*/
@BeforeClass
public static void beforeClass() {
logger = mock(Logger.class);
loggerFactoryMockedStatic = mockStatic(LoggerFactory.class);
loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(anyString())).thenReturn(logger);
Whitebox.setInternalState(LogUtil.class, "log", logger);
}
@AfterClass
public static void after() {
loggerFactoryMockedStatic.close();
}
}
Try
git stash
This worked for me. It stashes anything you haven't committed and that got around the problem.
Just leaving the default navbar built in with bootstrap works fine.
You just need to add the custom css below, that way everything still works as it should.
HTML:
<nav class="navbar navbar-default">
CSS:
.navbar-default {
background-color: transparent;
}
If you want to convert b'\x61' to 97 or '0x61', you can try this:
[python3.5]
>>>from struct import *
>>>temp=unpack('B',b'\x61')[0] ## convert bytes to unsigned int
97
>>>hex(temp) ##convert int to string which is hexadecimal expression
'0x61'
You can try this one, it works just fine :
` ImageIcon icon = new ImageIcon(".//Ressources//User_50.png");
this.setIconImage(icon.getImage());`
An even more elegant solution is to limit the text by the number of words (and not by number of characters). This prevents ugly tear throughs (e.g. 'Stackov...').
Here's an example where I shorten only text blocks longer than 10 words:
{% set text = myentity.text |split(' ') %}
{% if text|length > 10 %}
{% for t in text|slice(0, 10) %}
{{ t }}
{% endfor %}
...
{% else %}
{{ text|join(' ') }}
{% endif %}
Since the return
statement terminates the execution of the current function, the two forms are equivalent (although the second one is arguably more readable than the first).
The efficiency of both forms is comparable, the underlying machine code has to perform a jump if the if
condition is false anyway.
Note that Python supports a syntax that allows you to use only one return
statement in your case:
return A+1 if A > B else A-1
By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).
BrowserStack.com
On this site, you can emulate a lot of iOS's devices online.
it does what it says - it will always return the integer 1. It's used to check whether a record matching your where clause exists.
The Console output is not appearing is because the backend code is not running in the context of the test.
You're probably better off using Trace.WriteLine
(In System.Diagnostics) and then adding a trace listener which writes to a file.
This topic from MSDN shows a way of doing this.
According to Marty Neal's and Dave Anderson's comments:
using System; using System.Diagnostics; ... Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); // or Trace.Listeners.Add(new ConsoleTraceListener()); Trace.WriteLine("Hello World");
You can add this in Post Model,
public function categories()
{
return $this->belongsToMany('App\Category','category_post','post_id','category_id');
}
category_post
indicate the table you want to use.
post_id
indicate the column where you want to store the posts id.
category_id
indicate the column where you want to store the categories id.
If for whatever reason you'd like to catch the output of Console.WriteLine
, you CAN do this:
protected void Application_Start(object sender, EventArgs e)
{
var writer = new LogWriter();
Console.SetOut(writer);
}
public class LogWriter : TextWriter
{
public override void WriteLine(string value)
{
//do whatever with value
}
public override Encoding Encoding
{
get { return Encoding.Default; }
}
}
If you're trying to just count how many of your cells in a range are not blank try this:
=COUNTA(range)
Example: (assume that it starts from A1 downwards):
---------
Something
---------
Something
---------
---------
Something
---------
---------
Something
---------
=COUNTA(A1:A6)
returns 4
since there are two blank cells in there.
Here is a different solution for anyone interested. It uses the new For range in c++11
string str("(555) 555-5555");
string str2="";
for (const auto c: str){
if(!ispunct(c)){
str2.push_back(c);
}
}
str = str2;
//output: 555 5555555
cout<<str<<endl;
For the following code you have to enable mssql in the php.ini as described at this link: http://www.php.net/manual/en/mssql.installation.php
$myServer = "10.85.80.229";
$myUser = "root";
$myPass = "pass";
$myDB = "testdb";
$conn = mssql_connect($myServer,$myUser,$myPass);
if (!$conn)
{
die('Not connected : ' . mssql_get_last_message());
}
$db_selected = mssql_select_db($myDB, $conn);
if (!$db_selected)
{
die ('Can\'t use db : ' . mssql_get_last_message());
}
JButton
has a model which answers these question:
isArmed()
, isPressed()
, isRollOVer()
etc. Hence you can ask the model for the answer you are seeking:
if(jButton1.getModel().isPressed())
System.out.println("the button is pressed");
package myguo;
import javax.swing.*;
public class MyGuo {
JFrame f;
JButton bt1 , bt2 ;
JTextField t1,t2;
JLabel l1,l2;
MyGuo(){
f=new JFrame("LOG IN FORM");
f.setLocation(500,300);
f.setSize(600,500);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l1=new JLabel("NAME");
l1.setBounds(50,70,80,30);
l2=new JLabel("PASSWORD");
l2.setBounds(50,100,80,30);
t1=new JTextField();
t1.setBounds(140, 70, 200,30);
t2=new JTextField();
t2.setBounds(140, 110, 200,30);
bt1 =new JButton("LOG IN");
bt1.setBounds(150,150,80,30);
bt2 =new JButton("CLEAR");
bt2.setBounds(235,150,80,30);
f.add(l1);
f.add(l2);
f.add(t1);
f.add(t2);
f.add(bt1);
f.add(bt2);
f.setVisible(true);
}
public static void main(String[] args) {
MyGuo myGuo = new MyGuo();
}
}
Try This:
var trident = !!navigator.userAgent.match(/Trident\/7.0/);
var net = !!navigator.userAgent.match(/.NET4.0E/);
var IE11 = trident && net
var IEold = ( navigator.userAgent.match(/MSIE/i) ? true : false );
if(IE11 || IEold){
alert("IE")
}else{
alert("Other")
}
The != operator most certainly does exist! It is an alias for the standard <>
operator.
Perhaps your fields are not actually empty strings, but instead NULL
?
To compare to NULL
you can use IS NULL
or IS NOT NULL
or the null safe equals operator <=>
.
The best solution is to use async Task
. You should avoid async void
for several reasons, one of which is composability.
If the method cannot be made to return Task
(e.g., it's an event handler), then you can use SemaphoreSlim
to have the method signal when it is about to exit. Consider doing this in a finally
block.
python 3.2
with open("d://test.txt") as f:
k=(((i.split("\n"))[0].rstrip()).split() for i in f.readlines())
d={}
for i,_,v in k:
d.setdefault(i,[]).append(v)
#read file lines and edit specific item
file=open("pythonmydemo.txt",'r')
a=file.readlines()
print(a[0][6:11])
a[0]=a[0][0:5]+' Ericsson\n'
print(a[0])
file=open("pythonmydemo.txt",'w')
file.writelines(a)
file.close()
print(a)
You're passing the result of somedict.keys()
to the function. In Python 3, dict.keys
doesn't return a list, but a set-like object that represents a view of the dictionary's keys and (being set-like) doesn't support indexing.
To fix the problem, use list(somedict.keys())
to collect the keys, and work with that.
Stack views use intrinsic content size, so use layout constraints to define the dimensions of the views.
There is an easy way to add constraints quickly (example):
[view1.heightAnchor constraintEqualToConstant:100].active = true;
Complete Code:
- (void) setup {
//View 1
UIView *view1 = [[UIView alloc] init];
view1.backgroundColor = [UIColor blueColor];
[view1.heightAnchor constraintEqualToConstant:100].active = true;
[view1.widthAnchor constraintEqualToConstant:120].active = true;
//View 2
UIView *view2 = [[UIView alloc] init];
view2.backgroundColor = [UIColor greenColor];
[view2.heightAnchor constraintEqualToConstant:100].active = true;
[view2.widthAnchor constraintEqualToConstant:70].active = true;
//View 3
UIView *view3 = [[UIView alloc] init];
view3.backgroundColor = [UIColor magentaColor];
[view3.heightAnchor constraintEqualToConstant:100].active = true;
[view3.widthAnchor constraintEqualToConstant:180].active = true;
//Stack View
UIStackView *stackView = [[UIStackView alloc] init];
stackView.axis = UILayoutConstraintAxisVertical;
stackView.distribution = UIStackViewDistributionEqualSpacing;
stackView.alignment = UIStackViewAlignmentCenter;
stackView.spacing = 30;
[stackView addArrangedSubview:view1];
[stackView addArrangedSubview:view2];
[stackView addArrangedSubview:view3];
stackView.translatesAutoresizingMaskIntoConstraints = false;
[self.view addSubview:stackView];
//Layout for Stack View
[stackView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = true;
[stackView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = true;
}
Note: This was tested on iOS 9
Click on the "show details" link under Date (dd/mm/YYY), then you can copy and paste that plugin code provided there
Update: I think you can just switch the order of the array, like so:
jQuery.fn.dataTableExt.oSort['us_date-asc'] = function(a,b) {
var usDatea = a.split('/');
var usDateb = b.split('/');
var x = (usDatea[2] + usDatea[0] + usDatea[1]) * 1;
var y = (usDateb[2] + usDateb[0] + usDateb[1]) * 1;
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
var usDatea = a.split('/');
var usDateb = b.split('/');
var x = (usDatea[2] + usDatea[0] + usDatea[1]) * 1;
var y = (usDateb[2] + usDateb[0] + usDateb[1]) * 1;
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
All I did was switch the __date_[1]
(day) and __date_[0]
(month), and replaced uk
with us
so you won't get confused. I think that should take care of it for you.
Update #2: You should be able to just use the date object for comparison. Try this:
jQuery.fn.dataTableExt.oSort['us_date-asc'] = function(a,b) {
var x = new Date(a),
y = new Date(b);
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
var x = new Date(a),
y = new Date(b);
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
Try the following script:
Exec sp_msforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER INDEX ALL ON ? REBUILD'
GO
Also
I prefer(After a long search) to use the following script, it contains @fillfactor
determines how much percentage of the space on each leaf-level page is filled with data.
DECLARE @TableName VARCHAR(255)
DECLARE @sql NVARCHAR(500)
DECLARE @fillfactor INT
SET @fillfactor = 80
DECLARE TableCursor CURSOR FOR
SELECT QUOTENAME(OBJECT_SCHEMA_NAME([object_id]))+'.' + QUOTENAME(name) AS TableName
FROM sys.tables
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER INDEX ALL ON ' + @TableName + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @TableName
END
CLOSE TableCursor
DEALLOCATE TableCursor
GO
for more info, check the following link:
and if you want to Check Index Fragmentation on Indexes in a Database, try the following script:
SELECT dbschemas.[name] as 'Schema',
dbtables.[name] as 'Table',
dbindexes.[name] as 'Index',
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
WHERE indexstats.database_id = DB_ID() AND dbtables.[name] like '%%'
ORDER BY indexstats.avg_fragmentation_in_percent desc
For more information, Check the following link:
Given this example url:
http://www.example.com/some-dir/yourpage.php?q=bogus&n=10
$_SERVER['REQUEST_URI']
will give you:
/some-dir/yourpage.php?q=bogus&n=10
Whereas $_GET['q']
will give you:
bogus
In other words, $_SERVER['REQUEST_URI']
will hold the full request path including the querystring. And $_GET['q']
will give you the value of parameter q
in the querystring.
node = { 'parent':0, 'left':0, 'right':0 }
import copy
root = copy.deepcopy(node)
root['parent'] = -1
left = copy
just to show another thought on implementation if you stick to the "OOP"
class Node:
def __init__(self,data):
self.data = data
self.child = {}
def append(self, title, child):
self.child[title] = child
CEO = Node( ('ceo', 1000) )
CTO = ('cto',100)
CFO = ('cfo', 10)
CEO.append('left child', CTO)
CEO.append('right child', CFO)
print CEO.data
print ' ', CEO.child['left child']
print ' ', CEO.child['right child']
let userImage:UIImage = UIImage(named: "Your-Image_name")!
let imageData:NSData = UIImagePNGRepresentation(userImage)! as NSData
let dataImage = imageData.base64EncodedString(options: .lineLength64Characters)
let imageData = dataImage
let dataDecode:NSData = NSData(base64Encoded: imageData!, options:.ignoreUnknownCharacters)!
let avatarImage:UIImage = UIImage(data: dataDecode as Data)!
yourImageView.image = avatarImage
Typically for local variables I initialize them as late as I can. It's rare that I need a "dummy" value. However, if you do, you can use any value you like - it won't make any difference, if you're sure you're going to assign a value before reading it.
If you want the char
equivalent of 0, it's just Unicode 0, which can be written as
char c = '\0';
That's also the default value for an instance (or static) variable of type char
.
Public: https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc6/11.2.0.4
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4</version>
</dependency>
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
My finally working approach is to try potential candidates of expected encodings by detecting invalid characters in the strings created from the byte array by the encodings. If I don't encounter invalid characters, I suppose the tested encoding works fine for the tested data.
For me, having only Latin and German special characters to consider, in order to determine the proper encoding for a byte array, I try to detect invalid characters in a string with this method:
/// <summary>
/// detect invalid characters in string, use to detect improper encoding
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static bool DetectInvalidChars(string s)
{
const string specialChars = "\r\n\t .,;:-_!\"'?()[]{}&%$§=*+~#@|<>äöüÄÖÜß/\\^€";
return s.Any(ch => !(
specialChars.Contains(ch) ||
(ch >= '0' && ch <= '9') ||
(ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z')));
}
(NB: if you have other Latin-based languages to consider, you might want to adapt the specialChars const string in the code)
Then I use it like this (I only expect UTF-8 or Default encoding):
// determine encoding by detecting invalid characters in string
var invoiceXmlText = Encoding.UTF8.GetString(invoiceXmlBytes); // try utf-8 first
if (StringFuncs.DetectInvalidChars(invoiceXmlText))
invoiceXmlText = Encoding.Default.GetString(invoiceXmlBytes); // fallback to default
I stole the logging code from virtualenv for a project of mine. Look in main()
of virtualenv.py
to see how it's initialized. The code is sprinkled with logger.notify()
, logger.info()
, logger.warn()
, and the like. Which methods actually emit output is determined by whether virtualenv was invoked with -v
, -vv
, -vvv
, or -q
.
This is a common way to do it:
long l = Long.parseLong(str);
There is also this method: Long.valueOf(str);
Difference is that parseLong
returns a primitive long
while valueOf
returns a new Long()
object.
If you are trying to return back the ID within the scope, using the SCOPE_IDENTITY()
would be a better approach. I would not advice to use @@IDENTITY
, as this can return any ID.
CREATE PROC [dbo].[sp_Test] (
@myID int output,
@myFirstName nvarchar(50),
@myLastName nvarchar(50),
@myAddress nvarchar(50),
@myPort int
) AS
BEGIN
INSERT INTO Dvds (myFirstName, myLastName, myAddress, myPort)
VALUES (@myFirstName, @myLastName, @myAddress, @myPort);
SET @myID = SCOPE_IDENTITY();
END
GO
The answers didn't work for me with postgresql 9.1+
This is what I had to do (you can check more in the manual here)
UPDATE schema.TableA as A
SET "columnA" = "B"."columnB"
FROM schema.TableB as B
WHERE A.id = B.id;
You can omit the schema, if you are using the default schema for both tables.
If you want it as a string (for example, a 10-digit phone number) you can use this:
n = 10
''.join(["{}".format(randint(0, 9)) for num in range(0, n)])
Found testing for window.Touch didn't work on android but this does:
function is_touch_device() {
return !!('ontouchstart' in window);
}
See article: What's the best way to detect a 'touch screen' device using JavaScript?
you can also "extend" the string class and choose the operator you prefer ( <<, &, |, etc ...)
Here is the code using operator<< to show there is no conflict with streams
note: if you uncomment s1.reserve(30), there is only 3 new() operator requests (1 for s1, 1 for s2, 1 for reserve ; you can't reserve at constructor time unfortunately); without reserve, s1 has to request more memory as it grows, so it depends on your compiler implementation grow factor (mine seems to be 1.5, 5 new() calls in this example)
namespace perso {
class string:public std::string {
public:
string(): std::string(){}
template<typename T>
string(const T v): std::string(v) {}
template<typename T>
string& operator<<(const T s){
*this+=s;
return *this;
}
};
}
using namespace std;
int main()
{
using string = perso::string;
string s1, s2="she";
//s1.reserve(30);
s1 << "no " << "sunshine when " << s2 << '\'' << 's' << " gone";
cout << "Aint't "<< s1 << " ..." << endl;
return 0;
}
Sliding from the right:
$('#example').animate({width:'toggle'},350);
Sliding to the left:
$('#example').toggle({ direction: "left" }, 1000);
Try this:
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(1347517119))
'2012-09-12 23:18:39'
Also in MySQL, you can FROM_UNIXTIME
like:
INSERT INTO tblname VALUES (FROM_UNIXTIME(1347517119))
For your 2nd question, it is probably because getbbb_class.end_time
is a string. You can convert it to numeric like: float(getbbb_class.end_time)
I'm using EF6, and I find something strange,
Suppose Customer has constructor with parameter ,
if I use new Customer(id, "name")
, and do
using (var db = new EfContext("name=EfSample"))
{
db.Customers.Add( new Customer(id, "name") );
db.SaveChanges();
}
It run through without error, but when I look into the DataBase, I find in fact that the data Is NOT be Inserted,
But if I add the curly brackets, use new Customer(id, "name"){}
and do
using (var db = new EfContext("name=EfSample"))
{
db.Customers.Add( new Customer(id, "name"){} );
db.SaveChanges();
}
the data will then actually BE Inserted,
seems the Curly Brackets make the difference, I guess that only when add Curly Brackets, entity framework will recognize this is a real concrete data.
A useful explanation to how braces are used (in addition to Filip Ekberg's useful answer, above) can be found in the short paper Parenthesis in Programming Languages.
You'll need to use multiple LIKE
terms, joined by OR
.
Do you mean counting the number of characters in a string? That's very simple
Dim strWord As String
Dim lngNumberOfCharacters as Long
strWord = "habit"
lngNumberOfCharacters = Len(strWord)
Debug.Print lngNumberOfCharacters
jquery provides val()
function and not value()
. You can check empty string using jquery
if($('#person_data[document_type]').val() != ''){}
You may want trigger action to execute once after the client executes a statement that modifies a million rows (statement-level trigger). Or, you may want to trigger the action once for every row that is modified (row-level trigger).
EXAMPLE: Let's say you have a trigger that will make sure all high school seniors graduate. That is, when a senior's grade is 12, and we increase it to 13, we want to set the grade to NULL
.
For a statement level trigger, you'd say, after the increase-grade statement runs, check the whole table once to update any nows with grade 13 to NULL
.
For a row-level trigger, you'd say, after every row that is updated, update the new row's grade to NULL
if it is 13.
A statement-level trigger would look like this:
create trigger stmt_level_trigger
after update on Highschooler
begin
update Highschooler
set grade = NULL
where grade = 13;
end;
and a row-level trigger would look like this:
create trigger row_level_trigger
after update on Highschooler
for each row
when New.grade = 13
begin
update Highschooler
set grade = NULL
where New.ID = Highschooler.ID;
end;
Note that SQLite doesn't support statement-level triggers, so in SQLite, the FOR EACH ROW
is optional.
You have to open as new StreamWriter(filename, true)
so that it appends to the file instead of overwriting.
This was just asked a couple of days ago (but I cannot find it):
>>> A = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A = set([6, 9, 12])
>>> [i for i in A if i not in subset_of_A]
[7, 8, 10, 11]
It might be better to use set
s from the beginning, depending on the context. Then you can use set operations like other answers show.
However, converting lists to sets and back only for these operations is slower than list comprehension.
right click on app-->select
New-->Select Folder-->then click on Assets Folder
Make sure that your connection string is in this format:
server=FOOSERVER;database=BLAH_DB;pooling=false;Connect Timeout=60;Integrated Security=SSPI;
If your string is missing the server
tag then the method would return back with this error.
I had the same problems on Ubuntu 16.04 when I followed the steps posted on the official document.
Then I remove the text "[ arch=amd64,arm64 ]" in step2 and it works for me.
echo "deb https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
apt-get install -y mongodb-org
root
is the old (pre-conda 4.4) name for the main environment; after conda 4.4, it was renamed to bebase
. source
In most cases what you want to do when you say that you want to update Anaconda is to execute the command:
conda update --all
(But this should be preceeded by conda update -n base conda
so you have the latest conda
version installed)
This will update all packages in the current environment to the latest version -- with the small print being that it may use an older version of some packages in order to satisfy dependency constraints (often this won't be necessary and when it is necessary the package plan solver will do its best to minimize the impact).
This needs to be executed from the command line, and the best way to get there is from Anaconda Navigator, then the "Environments" tab, then click on the triangle beside the base
environment, selecting "Open Terminal":
This operation will only update the one selected environment (in this case, the base
environment). If you have other environments you'd like to update you can repeat the process above, but first click on the environment. When it is selected there is a triangular marker on the right (see image above, step 3). Or from the command line you can provide the environment name (-n envname
) or path (-p /path/to/env
), for example to update your dspyr
environment from the screenshot above:
conda update -n dspyr --all
If you are only interested in updating an individual package then simply click on the blue arrow or blue version number in Navigator, e.g. for astroid
or astropy
in the screenshot above, and this will tag those packages for an upgrade. When you are done you need to click the "Apply" button:
Or from the command line:
conda update astroid astropy
If you don't care about package versions and just want "the latest set of all packages in the standard Anaconda Distribution, so long as they work together", then you should take a look at this gist.
In most cases updating the Anaconda package in the package list will have a surprising result: you may actually downgrade many packages (in fact, this is likely if it indicates the version as custom
). The gist above provides details.
Your base
environment is probably not a good place to try and manage an exact set of packages: it is going to be a dynamic working space with new packages installed and packages randomly updated. If you need an exact set of packages then create a conda environment to hold them. Thanks to the conda package cache and the way file linking is used doing this is typically i) fast and ii) consumes very little additional disk space. E.g.
conda create -n myspecialenv -c bioconda -c conda-forge python=3.5 pandas beautifulsoup seaborn nltk
The conda documentation has more details and examples.
None of this is going to help with updating packages that have been installed from PyPI via pip
or any packages installed using python setup.py install
. conda list
will give you some hints about the pip-based Python packages you have in an environment, but it won't do anything special to update them.
It is pretty much exactly the same story, with the exception that you may not be able to update the base
environment if it was installed by someone else (say to /opt/anaconda/latest
). If you're not able to update the environments you are using you should be able to clone and then update:
conda create -n myenv --clone base
conda update -n myenv --all
Options A, B and D seem to be in the same category since they only influence the initial start time, they do warmup of the website like compilation and loading of libraries in memory.
Using C, setting the idle timeout, should be enough so that subsequent requests to the server are served fast (restarting the app pool takes quite some time - in the order of seconds).
As far as I know, the timeout exists to save memory that other websites running in parallel on that machine might need. The price being that one time slow load time.
Besides the fact that the app pool gets shutdown in case of user inactivity, the app pool will also recycle by default every 1740 minutes (29 hours).
From technet:
Internet Information Services (IIS) application pools can be periodically recycled to avoid unstable states that can lead to application crashes, hangs, or memory leaks.
As long as app pool recycling is left on, it should be enough. But if you really want top notch performance for most components, you should also use something like the Application Initialization Module you mentioned.
You can easily convert the string data type to numerical data type.
Don't forget to change collectionName & FieldName.
for ex : CollectionNmae : Users & FieldName : Contactno.
Try this query..
db.collectionName.find().forEach( function (x) {
x.FieldName = parseInt(x.FieldName);
db.collectionName.save(x);
});
use copy() and unlink() function
$moveFile="path/filename";
if (copy($csvFile,$moveFile))
{
unlink($csvFile);
}
You can do that by applying your rotate CSS to an inner element and then adjusting the height of the element to match its width since the element was rotated to fit it into the <td>
.
Also make sure you change your id
#rotate
to a class since you have multiple.
$(document).ready(function() {_x000D_
$('.rotate').css('height', $('.rotate').width());_x000D_
});
_x000D_
td {_x000D_
border-collapse: collapse;_x000D_
border: 1px black solid;_x000D_
}_x000D_
tr:nth-of-type(5) td:nth-of-type(1) {_x000D_
visibility: hidden;_x000D_
}_x000D_
.rotate {_x000D_
/* FF3.5+ */_x000D_
-moz-transform: rotate(-90.0deg);_x000D_
/* Opera 10.5 */_x000D_
-o-transform: rotate(-90.0deg);_x000D_
/* Saf3.1+, Chrome */_x000D_
-webkit-transform: rotate(-90.0deg);_x000D_
/* IE6,IE7 */_x000D_
filter: progid: DXImageTransform.Microsoft.BasicImage(rotation=0.083);_x000D_
/* IE8 */_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)";_x000D_
/* Standard */_x000D_
transform: rotate(-90.0deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>10kg</div>_x000D_
</td>_x000D_
<td>B</td>_x000D_
<td>C</td>_x000D_
<td>D</td>_x000D_
<td>E</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>20kg</div>_x000D_
</td>_x000D_
<td>G</td>_x000D_
<td>H</td>_x000D_
<td>I</td>_x000D_
<td>J</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>30kg</div>_x000D_
</td>_x000D_
<td>L</td>_x000D_
<td>M</td>_x000D_
<td>N</td>_x000D_
<td>O</td>_x000D_
</tr>_x000D_
_x000D_
_x000D_
</table>
_x000D_
JavaScript
The equivalent to the above in pure JavaScript is as follows:
window.addEventListener('load', function () {
var rotates = document.getElementsByClassName('rotate');
for (var i = 0; i < rotates.length; i++) {
rotates[i].style.height = rotates[i].offsetWidth + 'px';
}
});
Try changing the following lines with new values
$cfg['Servers'][$i]['user'] = 'NEW_USERNAME';
$cfg['Servers'][$i]['password'] = 'NEW_PASSWORD';
Updated due to the absence of the above lines in the config file
Stop the MySQL server
sudo service mysql stop
Start mysqld
sudo mysqld --skip-grant-tables &
Login to MySQL as root
mysql -u root mysql
Change MYSECRET with your new root password
UPDATE user SET Password=PASSWORD('MYSECRET') WHERE User='root'; FLUSH PRIVILEGES; exit;
Kill mysqld
sudo pkill mysqld
Start mysql
sudo service mysql start
Login to phpmyadmin as root with your new password
It means that you can't use lambda expressions with a "statement body" (i.e. lambda expressions which use curly braces) in places where the lambda expression needs to be converted to an expression tree (which is for example the case when using linq2sql).
The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash
:
git stash
git checkout other-branch
git stash pop
The first stash
hides away your changes (basically making a temporary commit), and the subsequent stash pop
re-applies them. This lets Git use its merge capabilities.
If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.
On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:
# Unstage everything (warning: this leaves files with conflicts in your tree)
git reset
# Add the things you *do* want to commit here
git add -p # or maybe git add -i
git commit
# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop
# Add the changes meant for this branch
git add -p
git commit
# And throw away the rest
git reset --hard
Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:
git add -p
git commit
git stash
git checkout other-branch
git stash pop
And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1)
to your PS1 environment variable in your bashrc file. (See for example the Git in Bash documentation.)
use filter
var json = {
homes: [{
"home_id": "1",
"price": "925",
"sqft": "1100",
"num_of_beds": "2",
"num_of_baths": "2.0",
}, {
"home_id": "2",
"price": "1425",
"sqft": "1900",
"num_of_beds": "4",
"num_of_baths": "2.5",
},
]
}
let filter =
json.homes.filter(d =>
d.price >= 1000 &
d.sqft >= 500 &
d.num_of_beds >=2 &
d.num_of_baths >= 2.5
)
console.log(filter)
_x000D_
Youtube uses iframe. You can simply set it to:
iframe {
display: block;
margin: 0 auto;
}
To configure Docker to work with a proxy you need to add the HTTPS_PROXY / HTTP_PROXY environment variable to the Docker sysconfig file (/etc/sysconfig/docker
).
Depending on if you use init.d
or the services tool you need to add the "export" statement (due to Debian Bug report logs - #767441. Examples in /etc/default/docker are misleading regarding the supported syntax):
HTTPS_PROXY="https://<user>:<password>@<proxy-host>:<proxy-port>"
HTTP_PROXY="https://<user>:<password>@<proxy-host>:<proxy-port>"
export HTTP_PROXY="https://<user>:<password>@<proxy-host>:<proxy-port>"
export HTTPS_PROXY="https://<user>:<password>@<proxy-host>:<proxy-port>"
The Docker repository (Docker Hub) only supports HTTPS. To get Docker working with SSL intercepting proxies you have to add the proxy root certificate to the systems trust store.
For CentOS, copy the file to /etc/pki/ca-trust/source/anchors/
and update the CA trust store and restart the Docker service.
If your proxy uses NTLMv2 authentication - you need to use intermediate proxies like Cntlm to bridge the authentication. This blog post explains it in detail.
You can customize your Bootstrap Grid system and define your custom responsive grid.
change your default values for the following gutter width from @grid-gutter-width = 30px
to @grid-gutter-width = 0px
(Gutter width is padding between columns. It gets divided in half for the left and right.)
You can quickly control this by typing built-in magic commands in Spyder's IPython console, which I find faster than picking these from the preferences menu. Changes take immediate effect, without needing to restart Spyder or the kernel.
To switch to "automatic" (i.e. interactive) plots, type:
%matplotlib auto
then if you want to switch back to "inline", type this:
%matplotlib inline
(Note: these commands don't work in non-IPython consoles)
See more background on this topic: Purpose of "%matplotlib inline"
Using this command,
git log -r --oneline --no-merges --simplify-by-decoration --pretty=format:"%n %Cred CommitID %Creset: %h %n %Cred Remote Branch %Creset :%d %n %Cred Commit Message %Creset: %s %n"
CommitID : 27385d919
Remote Branch : (origin/ALPHA)
Commit Message : New branch created
It lists all remote branches including commit messages and commit IDs that are referred to by remote branches.
No idea if this still applies to 8, but historically IE doesn't apply several styles to elements that don't "have layout."
I can't leave this question in this state with that final code in the question hanging over me...
dan: here's a much neater and shorter version of your code. It would be a good idea to look at how this is done and code more this way in future. I realise you probably have no further need of this code, but learning how you should do it is a good idea. Some things to note:
There are only two comments - and even the second is not really necessary for someone familiar with Python, they'll realise NL is being stripped. Only write comments where it adds value.
The with
statement (recommended in another answer) removes the bother of closing the file through the context handler.
Use a dictionary instead of two lists.
A generator comprehension ((x for y in z)
) is used to do the translation in one line.
Wrap as little code as you can in a try
/except
block to reduce the probability of catching an exception you didn't mean to.
Use the input()
argument rather than print()
ing first - Use '\n'
to get the new line you want.
Don't write code across multiple lines or with intermediate variables like this just for the sake of it:
a = a.b()
a = a.c()
b = a.x()
c = b.y()
Instead, write these constructs like this, chaining the calls as is perfectly valid:
a = a.b().c()
c = a.x().y()
code = {}
with open('morseCode.txt', 'r') as morse_code_file:
# line format is <letter>:<morse code translation>
for line in morse_code_file:
line = line.rstrip() # Remove NL
code[line[0]] = line[2:]
user_input = input("Enter a string to convert to morse code or press <enter> to quit\n")
while user_input:
try:
print(''.join(code[x] for x in user_input.replace(' ', '').upper()))
except KeyError:
print("Error in input. Only alphanumeric characters, a comma, and period allowed")
user_input = input("Try again or press <enter> to quit\n")
Flask with SQLAlchemy has boolean.
I faced the same issue as the author of the question. For our case answers in this question weren't enough since each of the members of my team had a different local environment and we definitely needed to .gitignore
the file that had the different db connection string and credentials, so people don't commit the common file by mistake and break others' db connections.
On top of that when we followed the procedure below it was easy to deploy on different environments and as en extra bonus we didn't need to have any sensitive information in the version control at all.
Getting the idea from PHP Symfony 3 framework that has a parameters.yml
(.gitignored) and a parameters.yml.dist
(which is a sample that creates the first one through composer install
),
I did the following combining the knowledge from answers below: https://stackoverflow.com/a/35534970/986160 and https://stackoverflow.com/a/35535138/986160.
Essentially this gives the freedom to use inheritance of spring configurations and choose active profiles through configuration at the top one plus any extra sensitive credentials as follows:
spring:
profiles:
active: local/dev/prod
datasource:
username:
password:
url: jdbc:mysql://localhost:3306/db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring:
profiles:
active: dev
datasource:
username: root
password: verysecretpassword
url: jdbc:mysql://localhost:3306/real_db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring:
profiles:
active: dev
datasource:
username: root
password: rootroot
url: jdbc:mysql://localhost:3306/xampp_db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring:
datasource:
testWhileIdle: true
validationQuery: SELECT 1
jpa:
show-sql: true
format-sql: true
hibernate:
ddl-auto: create-droop
naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL57InnoDBDialect
Same can be done with .properties
This usually happens when the version of one of the DLLs of the testing environment does not match the development environment.
Clean and Build your solution and take all your DLLs to the environment where the error is happening that should fix it
When you establish a connection for a transaction, you acquire a lock before performing the transaction. If not able to acquire the lock, then you try for sometime. If lock is still not obtainable, then lock wait time exceeded error is thrown. Why you will not able to acquire a lock is that you are not closing the connection. So, when you are trying to get a lock second time, you will not be able to acquire the lock as your previous connection is still unclosed and holding the lock.
Solution: close the connection or setAutoCommit(true)
(according to your design) to release the lock.
The manual explains how to checkout code:
http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-checkout.html
{
int main(void);
should be
int main(void)
{
Then I let you fix the next compilation errors of your program...
Another way is to download JDK 1.7 and change the path from Android Studio in the error message..and choose Home folder who is contained in Jdk 1.7 folder
Use Method to Serialize and Deserialize Collection object from memory. This works on Collection Data Types. This Method will Serialize collection of any type to a byte stream. Create a Seperate Class SerilizeDeserialize
and add following two methods:
public class SerilizeDeserialize
{
// Serialize collection of any type to a byte stream
public static byte[] Serialize<T>(T obj)
{
using (MemoryStream memStream = new MemoryStream())
{
BinaryFormatter binSerializer = new BinaryFormatter();
binSerializer.Serialize(memStream, obj);
return memStream.ToArray();
}
}
// DSerialize collection of any type to a byte stream
public static T Deserialize<T>(byte[] serializedObj)
{
T obj = default(T);
using (MemoryStream memStream = new MemoryStream(serializedObj))
{
BinaryFormatter binSerializer = new BinaryFormatter();
obj = (T)binSerializer.Deserialize(memStream);
}
return obj;
}
}
How To use these method in your Class:
ArrayList arrayListMem = new ArrayList() { "One", "Two", "Three", "Four", "Five", "Six", "Seven" };
Console.WriteLine("Serializing to Memory : arrayListMem");
byte[] stream = SerilizeDeserialize.Serialize(arrayListMem);
ArrayList arrayListMemDes = new ArrayList();
arrayListMemDes = SerilizeDeserialize.Deserialize<ArrayList>(stream);
Console.WriteLine("DSerializing From Memory : arrayListMemDes");
foreach (var item in arrayListMemDes)
{
Console.WriteLine(item);
}
The Scanner should be closed. It is a good practice to close Readers, Streams...and this kind of objects to free up resources and aovid memory leaks; and doing so in a finally block to make sure that they are closed up even if an exception occurs while handling those objects.
this is pretty old, but if you are using Python 3.4 or above use PathLib.
# using OS
import os
path=os.path.dirname("C:/folder1/folder2/filename.xml")
print(path)
print(os.path.basename(path))
# using pathlib
import pathlib
path = pathlib.PurePath("C:/folder1/folder2/filename.xml")
print(path.parent)
print(path.parent.name)
echo str_pad("1234567", 8, '0', STR_PAD_LEFT);
I am using this example in my project:
html:
<hr class="my-3 dividerClass"/>
css:
.dividerClass{
border-top-color: #999
}
<ul>
<li ng-repeat=interface in interfaces>
<img src='green-checkmark.png' ng-show="interface=='UP'" />
<img src='big-black-X.png' ng-show="interface=='DOWN'" />
</li>
</ul>
Square brackets are lists while parentheses are tuples.
A list is mutable, meaning you can change its contents:
>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]
while tuples are not:
>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:
>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Note that, as many people have pointed out, you can add tuples together. For example:
>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)
However, this does not mean tuples are mutable. In the example above, a new tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:
>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)
Whereas, if you were to construct this same example with a list, y
would also be updated:
>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]
hyperjaxb (versions 2 and 3) actually generates hibernate mapping files and related entity objects and also does a round trip test for a given XSD and sample XML file. You can capture the log output and see the DDL statements for yourself. I had to tweak them a little bit, but it gives you a basic blue print to start with.
Technically, you can too put image data in an img tag, using data URIs.
<img src="data:image/jpeg;base64,<?php echo base64_encode( $image_data ); ?>" />
There are some special circumstances where this could even be useful, although in most cases you're better off serving the image through a separate script like daiscog suggests.
Why not just set the left two columns to a fixed with in your own css and then make a new grid layout of the full 12 columns for the rest of the content?
<div class="row">
<div class="fixed-1">Left 1</div>
<div class="fixed-2">Left 2</div>
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-11"></div>
</div>
</div>
This seems to work great :
if( response.getEntity() != null ) {
response.getEntity().consumeContent();
}//if
And don't forget to consume the entity even if you didn't open its content. For instance, you expect a HTTP_OK status from the response and don't get it, you still have to consume the entity !
I like Ken Cochrane's answer.
But I want to add additional point of view, not covered in detail here. In my opinion Docker differs also in whole process. In contrast to VMs, Docker is not (only) about optimal resource sharing of hardware, moreover it provides a "system" for packaging application (preferable, but not a must, as a set of microservices).
To me it fits in the gap between developer-oriented tools like rpm, Debian packages, Maven, npm + Git on one side and ops tools like Puppet, VMware, Xen, you name it...
Why is deploying software to a docker image (if that's the right term) easier than simply deploying to a consistent production environment?
Your question assumes some consistent production environment. But how to keep it consistent? Consider some amount (>10) of servers and applications, stages in the pipeline.
To keep this in sync you'll start to use something like Puppet, Chef or your own provisioning scripts, unpublished rules and/or lot of documentation... In theory servers can run indefinitely, and be kept completely consistent and up to date. Practice fails to manage a server's configuration completely, so there is considerable scope for configuration drift, and unexpected changes to running servers.
So there is a known pattern to avoid this, the so called immutable server. But the immutable server pattern was not loved. Mostly because of the limitations of VMs that were used before Docker. Dealing with several gigabytes big images, moving those big images around, just to change some fields in the application, was very very laborious. Understandable...
With a Docker ecosystem, you will never need to move around gigabytes on "small changes" (thanks aufs and Registry) and you don't need to worry about losing performance by packaging applications into a Docker container at runtime. You don't need to worry about versions of that image.
And finally you will even often be able to reproduce complex production environments even on your Linux laptop (don't call me if doesn't work in your case ;))
And of course you can start Docker containers in VMs (it's a good idea). Reduce your server provisioning on the VM level. All the above could be managed by Docker.
P.S. Meanwhile Docker uses its own implementation "libcontainer" instead of LXC. But LXC is still usable.
I am not sure if this is the best solution or not, but it is what I need.
Please tell me if you know what is need to be changed for better performance or quality. In my case, I have a button.
Custom item on my menu - main.xml
<item
android:id="@+id/badge"
android:actionLayout="@layout/feed_update_count"
android:icon="@drawable/shape_notification"
android:showAsAction="always">
</item>
Custom shape drawable (background square) - shape_notification.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke android:color="#22000000" android:width="2dp"/>
<corners android:radius="5dp" />
<solid android:color="#CC0001"/>
</shape>
Layout for my view - feed_update_count.xml
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/notif_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="32dp"
android:minHeight="32dp"
android:background="@drawable/shape_notification"
android:text="0"
android:textSize="16sp"
android:textColor="@android:color/white"
android:gravity="center"
android:padding="2dp"
android:singleLine="true">
</Button>
MainActivity - setting and updating my view
static Button notifCount;
static int mNotifCount = 0;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
View count = menu.findItem(R.id.badge).getActionView();
notifCount = (Button) count.findViewById(R.id.notif_count);
notifCount.setText(String.valueOf(mNotifCount));
return super.onCreateOptionsMenu(menu);
}
private void setNotifCount(int count){
mNotifCount = count;
invalidateOptionsMenu();
}
Sometimes, when a function name and a variable name to which the return of the function is stored are same, the error is shown. Just happened to me.
I received a similar error message once, in my case it was because my pandas dataframe contained NULLs. I will recommend to try & handle this in pandas before converting to spark (this resolved the issue in my case).
It means that the object you pass in the request (I guess it is pagedoc
) has a circular reference, something like:
var a = {};
a.b = a;
JSON.stringify
cannot convert structures like this.
N.B.: This would be the case with DOM nodes, which have circular references, even if they are not attached to the DOM tree. Each node has an ownerDocument
which refers to document
in most cases. document
has a reference to the DOM tree at least through document.body
and document.body.ownerDocument
refers back to document
again, which is only one of multiple circular references in the DOM tree.
A total different approach to convert hex color code to RGB without regex
It handles both #FFF
and #FFFFFF
format on the base of length of string. It removes #
from beginning of string and divides each character of string and converts it to base10 and add it to respective index on the base of it's position.
//Algorithm of hex to rgb conversion in ES5_x000D_
function hex2rgbSimple(str){_x000D_
str = str.replace('#', '');_x000D_
return str.split('').reduce(function(result, char, index, array){_x000D_
var j = parseInt(index * 3/array.length);_x000D_
var number = parseInt(char, 16);_x000D_
result[j] = (array.length == 3? number : result[j]) * 16 + number;_x000D_
return result;_x000D_
},[0,0,0]);_x000D_
}_x000D_
_x000D_
//Same code in ES6_x000D_
hex2rgb = str => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]);_x000D_
_x000D_
//hex to RGBA conversion_x000D_
hex2rgba = (str, a) => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0,a||1]);_x000D_
_x000D_
//hex to standard RGB conversion_x000D_
hex2rgbStandard = str => `RGB(${str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]).join(',')})`;_x000D_
_x000D_
_x000D_
console.log(hex2rgb('#aebece'));_x000D_
console.log(hex2rgbSimple('#aebece'));_x000D_
_x000D_
console.log(hex2rgb('#aabbcc'));_x000D_
_x000D_
console.log(hex2rgb('#abc'));_x000D_
_x000D_
console.log(hex2rgba('#abc', 0.7));_x000D_
_x000D_
console.log(hex2rgbStandard('#abc'));
_x000D_
This one was your solution.
$x = 0;
while($row = mysqli_fetch_array($result)) {
$posts[$x]['post_id'] = $row['post_id'];
$posts[$x]['post_title'] = $row['post_title'];
$posts[$x]['type'] = $row['type'];
$posts[$x]['author'] = $row['author'];
$x++;
}
As the author of the linked webpage in the popular answer, I would like to add my last version of this simple helper function. It is much more solid.
I use json_encode()
to make a check for if the variable type is not necessary and also add a buffer to solve problems with frameworks. There not have a solid return or excessive usage of header()
.
/**
* Simple helper to debug to the console
*
* @param $data object, array, string $data
* @param $context string Optional a description.
*
* @return string
*/
function debug_to_console($data, $context = 'Debug in Console') {
// Buffering to solve problems frameworks, like header() in this and not a solid return.
ob_start();
$output = 'console.info(\'' . $context . ':\');';
$output .= 'console.log(' . json_encode($data) . ');';
$output = sprintf('<script>%s</script>', $output);
echo $output;
}
// $data is the example variable, object; here an array.
$data = [ 'foo' => 'bar' ];
debug_to_console($data);`
Also a simple example as an image to understand it much easier:
Since Java 8 there is an easier way to transform:
import java.util.List;
import static java.util.stream.Collectors.toList;
public static <T> List<T> fromArray(T[] array) {
return Arrays.stream(array).collect(toList());
}
You can select every column from that sub-query by aliasing it and adding the alias before the *
:
SELECT t.*, a+b AS total_sum
FROM
(
SELECT SUM(column1) AS a, SUM(column2) AS b
FROM table
) t
Alert dialog with edit text
AlertDialog.Builder builder = new AlertDialog.Builder(context);//Context is activity context
final EditText input = new EditText(context);
builder.setTitle(getString(R.string.remove_item_dialog_title));
builder.setMessage(getString(R.string.dialog_message_remove_item));
builder.setTitle(getString(R.string.update_qty));
builder.setMessage("");
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
input.setHint(getString(R.string.enter_qty));
input.setTextColor(ContextCompat.getColor(context, R.color.textColor));
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setText("String in edit text you want");
builder.setView(input);
builder.setPositiveButton(getString(android.R.string.ok),
(dialog, which) -> {
//Positive button click event
});
builder.setNegativeButton(getString(android.R.string.cancel),
(dialog, which) -> {
//Negative button click event
});
AlertDialog dialog = builder.create();
dialog.show();
Ubuntu has the option to install a headless Java -- this means without graphics libraries. This wasn't always the case, but I encountered this while trying to run a Java text editor on 10.10 the other day. Run the following command to install a JDK that has these libraries:
sudo apt-get install openjdk-6-jdk
EDIT: Actually, looking at my config, you might need the JRE. If that's the case, run:
sudo apt-get install openjdk-6-jre
In javascript, navigation type 2
means browser's back or forward button clicked and the browser is actually taking content from cache.
if(performance.navigation.type == 2)
{
//Do your code here
}
Here is what I did:
The .suo file is a hidden file in the same folder as the .svn solution file and contains the Visual Studio User Options.
In vim column visual mode is Ctrl + v. If that is what you meant?
The following definition might be more efficient than the first solution proposed
def new_list_from_intervals(original_list, *intervals):
n = sum(j - i for i, j in intervals)
new_list = [None] * n
index = 0
for i, j in intervals :
for k in range(i, j) :
new_list[index] = original_list[k]
index += 1
return new_list
then you can use it like below
new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))
It is not possible because they are executed in different environments (JSP at server side, JavaScript at client side). So they are not executed in the sequence you see in your code.
var val1 = document.getElementById('userName').value;
<c:set var="user" value=""/> // how do i set val1 here?
Here JSTL code is executed at server side and the server sees the JavaScript/Html codes as simple texts. The generated contents from JSTL code (if any) will be rendered in the resulting HTML along with your other JavaScript/HTML codes. Now the browser renders HTML along with executing the Javascript codes. Now remember there is no JSTL code available for the browser.
Now for example,
<script type="text/javascript">
<c:set var="message" value="Hello"/>
var message = '<c:out value="${message}"/>';
</script>
Now for the browser, this content is rendered,
<script type="text/javascript">
var message = 'Hello';
</script>
Hope this helps.
in exemple if you want to compile sources but have objects in an different directory :
You need to do :
gcc -c -o <obj/1.o> <srcs/1.c> <obj/2.o> <srcs/2.c> ...
but with most of macros the result will be all objects followed by all sources, like :
gcc -c -o <all OBJ path> <all SRC path>
so this will not compile anything ^^ and you will not be able to put your objects files in a different dir :(
the solution is to use these special macros
$@ $<
this will generate a .o file (obj/file.o) for each .c file in SRC (src/file.c)
$(OBJ):$(SRC)
gcc -c -o $@ $< $(HEADERS) $(FLAGS)
it means :
$@ = $(OBJ)
$< = $(SRC)
but lines by lines INSTEAD of all lines of OBJ followed by all lines of SRC
This depends on the alphabet but for the english one, try this:
String input = "abc".toLowerCase(); //note the to lower case in order to treat a and A the same way
for( int i = 0; i < input.length(); ++i) {
int position = input.charAt(i) - 'a' + 1;
}
Please read the example in rfc6749 sec 7.1 first.
The bearer token is a type of access token, which does NOT require PoP(proof-of-possession) mechanism.
PoP means kind of multi-factor authentication to make access token more secure. ref
Proof-of-Possession refers to Cryptographic methods that mitigate the risk of Security Tokens being stolen and used by an attacker. In contrast to 'Bearer Tokens', where mere possession of the Security Token allows the attacker to use it, a PoP Security Token cannot be so easily used - the attacker MUST have both the token itself and access to some key associated with the token (which is why they are sometimes referred to 'Holder-of-Key' (HoK) tokens).
Maybe it's not the case, but I would say,
BTW, there's a draft of "OAuth 2.0 Proof-of-Possession (PoP) Security Architecture" now.
NOTE: I wrote this answer in Jun 2013, so it's bit dated nowadays. Many things changed in Android platform since version 6 (Marshmallow, released late 2015), making the whole problem more/less obsolete. However I believe this post can still be worth reading as general problem analysis approach example.
Exception you are getting (SecurityException: Permission denied (missing INTERNET permission?)
), clearly indicates that you are not allowed to do networking. That's pretty indisputable fact. But how can this happen? Usually it's either due to missing <uses-permission android:name="android.permission.INTERNET" />
entry in your AndroidManifest.xml
file or, as internet permission is granted at installation not at run time, by long standing, missed bug in Android framework that causes your app to be successfully installed, but without expected permission grant.
My Manifest is correct, so how can this happen?
Theoretically, presence of uses-permission
in Manifest perfectly fulfills the requirement and from developer standpoint is all that's needed to be done to be able to do networking. Moreover, since permissions are shown to the user during installation, the fact your app ended installed on user's device means s/he granted what you asked for (otherwise installation is cancelled), so assumption that if your code is executed then all requested permissions are granted is valid. And once granted, user cannot revoke the permission other way than uninstalling the app completely as standard Android framework (from AOSP) offers no such feature at the moment.
But things are getting more tricky if you also do not mind your app running on rooted devices too. There're tools available in Google Play your users can install to control permission granted to installed apps at run-time - for example: Permissions Denied and others. This can also be done with CyanogenMod, vendor brand (i.e. LG's) or other custom ROM, featuring various type of "privacy managers" or similar tools.
So if app is blocked either way, it's basically blocked intentionally by the user and if so, it is really more user problem in this case (or s/he do not understand what certain options/tools really do and what would be the consequences) than yours, because standard SDK (and most apps are written with that SDK in mind) simply does not behave that way. So I strongly doubt this problem occurs on "standard", non-rooted device with stock (or vendor like Samsung, HTC, Sony etc) ROM.
I do not want to crash...
Properly implemented permission management and/org blocking must deal with the fact that most apps may not be ready for the situation where access to certain features is both granted and not accessible at the same time, as this is kind of contradiction where app uses manifest to request access at install time. Access control done right should must make all things work as before, and still limit usability using techniques in scope of expected behavior of the feature. For example, when certain permission is granted (i.e. GPS, Internet access) such feature can be made available from the app/user perspective (i.e. you can turn GPS on. or try to connect), the altered implementation can provide no real data - i.e. GPS can always return no coordinates, like when you are indoor or have no satellite "fix". Internet access can granted as before, but you can make no successful connection as there's no data coverage or routing. Such scenarios should be expected in normal usage as well, therefore it should be handled by the apps already. As this simply can happen during normal every day usage, any crash in such situation should be most likely be related to application bugs.
We lack too much information about the environment on which this problem occurs to diagnose problem w/o guessing, but as kind of solution, you may consider using setDefaultUncaughtExceptionHandler() to catch such unexpected exceptions in future and i.e. simply show user detailed information what permission your app needs instead of just crashing. Please note that using this will most likely conflict with tools like Crittercism, ACRA and others, so be careful if you use any of these.
Notes
Please be aware that android.permission.INTERNET
is not the only networking related permission you may need to declare in manifest in attempt to successfully do networking. Having INTERNET
permission granted simply allows applications to open network sockets (which is basically fundamental requirement to do any network data transfer). But in case your network stack/library would like to get information about networks as well, then you will also need android.permission.ACCESS_NETWORK_STATE
in your Manifest (which is i.e. required by HttpUrlConnection client (see tutorial).
Addendum (2015-07-16)
Please note that Android 6 (aka Marshmallow) introduced completely new permission management mechanism called Runtime Permissions. It gives user more control on what permission are granted (also allows selective grant) or lets one revoke already granted permissions w/o need to app removal:
This [...] introduces a new permissions model, where users can now directly manage app permissions at runtime. This model gives users improved visibility and control over permissions, while streamlining the installation and auto-update processes for app developers. Users can grant or revoke permissions individually for installed apps.
However, the changes do not affect INTERNET
or ACCESS_NETWORK_STATE
permissions, which are considered "Normal" permissions. The user does not need to explicitly grant these permission.
See behavior changes description page for details and make sure your app will behave correctly on newer systems too. It's is especially important when your project set targetSdk
to at least 23
as then you must support new permissions model (detailed documentation). If you are not ready, ensure you keep targetSdk
to at most 22
as this ensures even new Android will use old permission system when your app is installed.
There are different ways to do this some of them has given.
implode(), join(), var_export(), print_r(), serialize(), json_encode()
exc... You can also write your own function without these:
A For()
loop is very useful. You can add your array's value to another variable like this:
<?php
$dizi=array('mother','father','child'); //This is array
$sayi=count($dizi);
for ($i=0; $i<$sayi; $i++) {
$dizin.=("'$dizi[$i]',"); //Now it is string...
}
echo substr($dizin,0,-1); //Write it like string :D
?>
In this code we added $dizi's values and comma to $dizin:
$dizin.=("'$dizi[$i]',");
Now
$dizin = 'mother', 'father', 'child',
It's a string, but it has an extra comma :)
And then we deleted the last comma, substr($dizin, 0, -1);
Output:
'mother','father','child'
Use a list/dictionary or define your own class to encapsulate the stuff you're defining, but if you need all those variables you can do:
a = b = c = d = e = g = h = i = j = True
f = False
If you want to call your activity, just use this . You use the getActivity method when you are inside a fragment.
Use fileReader.readAsDataURL( fileObject )
, this will encode it to base64, which you can safely upload to your server.
In Intellij, I simple changed the name of the docker files to *.Dockerfile, and associated the file type *.Dockerfile to docker syntax.
For VS 2019, this should work without installing anything:
//#region MyRegion1
foo() {
}
//#endregion
//#region MyRegion2
bar() {
}
//#endregion
I think the best and cleanest way would be to get a custom download of bootstrap.
http://getbootstrap.com/customize/
You can then change the font-defaults in the Typography (in that link). This then gives you a .Less file that you can make further changes to defaults with later.
In case of multi monitor and If you prefer to center on correct monitor/screen then you might like to try these lines:
// Save values for future(for example, to center a form on next launch)
int screen_x = Screen.FromControl(Form).WorkingArea.X;
int screen_y = Screen.FromControl(Form).WorkingArea.Y;
// Move it and center using correct screen/monitor
Form.Left = screen_x;
Form.Top = screen_y;
Form.Left += (Screen.FromControl(Form).WorkingArea.Width - Form.Width) / 2;
Form.Top += (Screen.FromControl(Form).WorkingArea.Height - Form.Height) / 2;
If you want to check your URL. I suppose you are using Chrome. You can go to chrome console and URL will be displayed under "XHR finished loading:"
You do not need to install or update any software for the JUnit. it is the part of Java Development tools and comes with almost most of the latest versions in Eclipse.
Go to your project. Right click onto that->Select buildpath->add library->select JUnit from the list ->select the version you want to work with-> done
build you project again to see the errors gone:)
In my case the only way I could keep using GetGroups() without any expcetion was adding the user (USER_WITH_PERMISSION) to the group which has permission to read the AD (Active Directory). It's extremely essential to construct the PrincipalContext passing this user and password.
var pc = new PrincipalContext(ContextType.Domain, domain, "USER_WITH_PERMISSION", "PASS");
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
var groups = user.GetGroups();
Steps you may follow inside Active Directory to get it working:
- Into Active Directory create a group (or take one) and under secutiry tab add "Windows Authorization Access Group"
- Click on "Advanced" button
- Select "Windows Authorization Access Group" and click on "View"
- Check "Read tokenGroupsGlobalAndUniversal"
- Locate the desired user and add to the group you created (taken) from the first step
You want huge?
Here's a small table: create table foo (id int not null primary key auto_increment, crap char(2000));
insert into foo(crap) values ('');
-- each time you run the next line, the number of rows in foo doubles. insert into foo( crap ) select * from foo;
run it twenty more times, you have over a million rows to play with.
Yes, if he's looking for looks of relations to navigate, this is not the answer. But if by huge he means to test performance and his ability to optimize, this will do it. I did exactly this (and then updated with random values) to test an potential answer I had for another question. (And didn't answer it, because I couldn't come up with better performance than what that asker had.)
Had he asked for "complex", I'd have gien a differnt answer. To me,"huge" implies "lots of rows".
Because you don't need huge to play with tables and relations. Consider a table, by itself, with no nullable columns. How many different kinds of rows can there be? Only one, as all columns must have some value as none can be null.
Every nullable column multiples by two the number of different kinds of rows possible: a row where that column is null, an row where it isn't null.
Now consider the table, not in isolation. Consider a table that is a child table: for every child that has an FK to the parent, that, is a many-to-one, there can be 0, 1 or many children. So we multiply by three times the count we got in the previous step (no rows for zero, one for exactly one, two rows for many). For any grandparent to which the parent is a many, another three.
For many-to-many relations, we can have have no relation, a one-to-one, a one-to-many, many-to-one, or a many-to-many. So for each many-to-many we can reach in a graph from the table, we multiply the rows by nine -- or just like two one-to manys. If the many-to-many also has data, we multiply by the nullability number.
Tables that we can't reach in our graph -- those that we have no direct or indirect FK to, don't multiply the rows in our table.
By recursively multiplying the each table we can reach, we can come up with the number of rows needed to provide one of each "kind", and we need no more than those to test every possible relation in our schema. And we're nowhere near huge.
In my case, I was getting this error because my table had
varchar(50)
but I was injecting 67 character long string, which resulted in thi error. Changing it to
varchar(255)
fixed the problem.
I accidentally deleted a whole bunch of data in the wrong environment and this post was one of the first ones I found.
Because I was simultaneously panicking and searching for a solution, I went for the first thing I saw - ApexSQL Logs, which was $2000 which was an acceptable cost.
However, I've since found out that Toad for Sql Server can generate undo scripts from transaction logs and it is only $655.
Lastly, found an even cheaper option SysToolsGroup Log Analyzer and it is only $300.
If you are needing to use CSS with the jQuery .animate()
function, you can use set the duration.
$("#my_image").css({
'left':'1000px',
6000, ''
});
We have the duration property set to 6000.
This will set the time in thousandth of seconds: 6 seconds.
After the duration our next property "easing" changes how our CSS happens.
We have our positioning set to absolute.
There are two default ones to the absolute function: 'linear' and 'swing'.
In this example I am using linear.
It allows for it to use a even pace.
The other 'swing' allows for a exponential speed increase.
There are a bunch of really cool properties to use with animate like bounce, etc.
$(document).ready(function(){
$("#my_image").css({
'height': '100px',
'width':'100px',
'background-color':'#0000EE',
'position':'absolute'
});// property than value
$("#my_image").animate({
'left':'1000px'
},6000, 'linear', function(){
alert("Done Animating");
});
});
.reduce((o,v,i)=>(o[i]=v,o), {})
[docs]
or more verbose
var trAr2Obj = function (arr) {return arr.reduce((o,v,i)=>(o[i]=v,o), {});}
or
var transposeAr2Obj = arr=>arr.reduce((o,v,i)=>(o[i]=v,o), {})
shortest one with vanilla JS
JSON.stringify([["a", "X"], ["b", "Y"]].reduce((o,v,i)=>{return o[i]=v,o}, {}))
=> "{"0":["a","X"],"1":["b","Y"]}"
some more complex example
[["a", "X"], ["b", "Y"]].reduce((o,v,i)=>{return o[v[0]]=v.slice(1)[0],o}, {})
=> Object {a: "X", b: "Y"}
even shorter (by using function(e) {console.log(e); return e;}
=== (e)=>(console.log(e),e)
)
? nodejs
> [[1, 2, 3], [3,4,5]].reduce((o,v,i)=>(o[v[0]]=v.slice(1),o), {})
{ '1': [ 2, 3 ], '3': [ 4, 5 ] }
[/docs]
JSON stands for JavaScript Object Notation. A JSON object is really a string that has yet to be turned into the object it represents.
To add a property to an existing object in JS you could do the following.
object["property"] = value;
or
object.property = value;
If you provide some extra info like exactly what you need to do in context you might get a more tailored answer.
Try this, it helped me: wrap the div in tags, the problem is that it will center the content of the div also (if not coded otherwise). Hope that helps :)
I think this is slightly more readable. It uses Array.from
and logic is identical to using nested loops:
var arr = [_x000D_
[1, 2, 3, 4],_x000D_
[1, 2, 3, 4],_x000D_
[1, 2, 3, 4]_x000D_
];_x000D_
_x000D_
/*_x000D_
* arr[0].length = 4 = number of result rows_x000D_
* arr.length = 3 = number of result cols_x000D_
*/_x000D_
_x000D_
var result = Array.from({ length: arr[0].length }, function(x, row) {_x000D_
return Array.from({ length: arr.length }, function(x, col) {_x000D_
return arr[col][row];_x000D_
});_x000D_
});_x000D_
_x000D_
console.log(result);
_x000D_
If you are dealing with arrays of unequal length you need to replace arr[0].length
with something else:
var arr = [_x000D_
[1, 2],_x000D_
[1, 2, 3],_x000D_
[1, 2, 3, 4]_x000D_
];_x000D_
_x000D_
/*_x000D_
* arr[0].length = 4 = number of result rows_x000D_
* arr.length = 3 = number of result cols_x000D_
*/_x000D_
_x000D_
var result = Array.from({ length: arr.reduce(function(max, item) { return item.length > max ? item.length : max; }, 0) }, function(x, row) {_x000D_
return Array.from({ length: arr.length }, function(x, col) {_x000D_
return arr[col][row];_x000D_
});_x000D_
});_x000D_
_x000D_
console.log(result);
_x000D_
To update all possible packages I used conda update --update-all
It works!
For the checked out branch, in the case the commit you want to point to is ahead of the current branch (which should be the case unless you want to undo the last commits of the current branch), you can simply do:
git merge --ff-only <commit>
This makes a softer alternative to git reset --hard
, and will fail if you are not in the case described above.
To do the same thing for a non checked out branch, the equivalent would be:
git push . <commit>:<branch>
Jotting down some steps which help:
Writing answer from eclipse perspective as base logic will remain the same whether done by Intellij or command line
> <maven.compiler.source>1.8</maven.compiler.source> > <maven.compiler.target>1.8</maven.compiler.target>
for /r %i in (*.lastUpdated) do del %i**
The best way to add different objects into same container is to use make_shared, vector, and range based loop and you will have a nice, clean and "readable" code!
typedef std::shared_ptr<gate> Ptr
vector<Ptr> myConatiner;
auto andGate = std::make_shared<ANDgate>();
myConatiner.push_back(andGate );
auto orGate= std::make_shared<ORgate>();
myConatiner.push_back(orGate);
for (auto& element : myConatiner)
element->run();
You can use this jsFiddle
And HTML:
<div id="previewBox">
<button id="closeButton">Close</button>
<a class="fragment" href="google.com">
<div>
<img src ="http://placehold.it/116x116" alt="some description"/>
<h3>the title will go here</h3>
<h4> www.myurlwill.com </h4>
<p class="text">
this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etcthis is a short description yada yada peanuts etc
</p>
</div>
</a>
</div>
With JS (jquery required):
$(document).ready(function() {
$('#closeButton').on('click', function(e) {
$('#previewBox').remove();
});
});
I don't think it is very important to find the location of Svcutil.exe. You can use Visual Studio Command prompt to execute directly without its absolute path,
Syntax:
svcutil.exe /language:[vb|cs] /out:[YourClassName].[cs|vb] /config:[YourAppConfigFile.config] [YourServiceAddress]
example:
svcutil.exe /language:cs /out:MyClientClass.cs /config:app.config http://localhost:8370/MyService/
You need to create a handler for the onkeypress
action.
HTML
<input name="keywords" type="text" id="keywords" size="50" onkeypress="handleEnter(this, event)" />
JS
function handleEnter(inField, e)
{
var charCode;
//Get key code (support for all browsers)
if(e && e.which)
{
charCode = e.which;
}
else if(window.event)
{
e = window.event;
charCode = e.keyCode;
}
if(charCode == 13)
{
//Call your submit function
}
}
Subject is the certificate's common name and is a critical property for the certificate in a lot of cases if it's a server certificate and clients are looking for a positive identification.
As an example on an SSL certificate for a web site the subject would be the domain name of the web site.
You can try it by adding
See also a lot of general hints and useful links at the regex tag details page.
Online tutorials
Quantifiers
*
:greedy, *?
:reluctant, *+
:possessive+
:greedy, +?
:reluctant, ++
:possessive?
:optional (zero-or-one){n,m}
:between n & m, {n,}
:n-or-more, {n}
:exactly n{n}
and {n}?
Character Classes
[...]
: any one character, [^...]
: negated/any character but[^]
matches any one character including newlines javascript[\w-[\d]]
/ [a-z-[qz]]
: set subtraction .net, xml-schema, xpath, JGSoft[\w&&[^\d]]
: set intersection java, ruby 1.9+[[:alpha:]]
:POSIX character classes[^\\D2]
, [^[^0-9]2]
, [^2[^0-9]]
get different results in Java? java\d
:digit, \D
:non-digit\w
:word character, \W
:non-word character\s
:whitespace, \S
:non-whitespace\p{L}, \P{L}
, etc.)Escape Sequences
\h
:space-or-tab, \t
:tab\H
:Non horizontal whitespace character, \V
:Non vertical whitespace character, \N
:Non line feed character pcre php5 java-8\v
:vertical tab, \e
:the escape characterAnchors
^
:start of line/input, \b
:word boundary, and \B
:non-word boundary, $
:end of line/input\A
:start of input, \Z
:end of input php, perl, ruby\z
:the very end of input (\Z
in Python) .net, php, pcre, java, ruby, icu, swift, objective-c\G
:start of match php, perl, ruby(Also see "Flavor-Specific Information ? Java ? The functions in Matcher
")
Groups
(...)
:capture group, (?:)
:non-capture group
\1
:backreference and capture-group reference, $1
:capture group reference
(?i:regex)
mean?(?P<group_name>regexp)
mean?(?>)
:atomic group or independent group, (?|)
:branch reset
regular-expressions.info
(?<groupname>regex)
: Overview and naming rules (Non-Stack Overflow links)(?P<groupname>regex)
python, (?<groupname>regex)
.net, (?<groupname>regex)
perl, (?P<groupname>regex)
and (?<groupname>regex)
phpLookarounds
(?=...)
:positive, (?!...)
:negative(?<=...)
:positive, (?<!...)
:negative (not supported by javascript)Modifiers
flag | modifier | flavors |
---|---|---|
c |
current position | perl |
e |
expression | php perl |
g |
global | most |
i |
case-insensitive | most |
m |
multiline | php perl python javascript .net java |
m |
(non)multiline | ruby |
o |
once | perl ruby |
S |
study | php |
s |
single line | unsupported: javascript (workaround) | ruby |
U |
ungreedy | php r |
u |
unicode | most |
x |
whitespace-extended | most |
y |
sticky ? | javascript |
Other:
|
:alternation (OR) operator, .
:any character, [.]
:literal dot character(*PRUNE)
, (*SKIP)
, (*FAIL)
and (*F)
(*BSR_ANYCRLF)
(?R)
, (?0)
and (?1)
, (?-1)
, (?&groupname)
Common Tasks
{...}
Advanced Regex-Fu
(?!a)a
this
except in contexts A, B and CFlavor-Specific Information
(Except for those marked with *
, this section contains non-Stack Overflow links.)
java.util.regex.Matcher
:
matches()
): The match must be anchored to both input-start and -endfind()
): A match may be anywhere in the input string (substrings)lookingAt()
: The match must be anchored to input-start onlyjava.lang.String
functions that accept regular expressions: matches(s)
, replaceAll(s,s)
, replaceFirst(s,s)
, split(s)
, split(s,i)
java.util.regex
preg_match
search
vs match
, how-toregex
, struct regex::Regex
regexp
commandGeneral information
(Links marked with *
are non-Stack Overflow links.)
Examples of regex that can cause regex engine to fail
Tools: Testers and Explainers
(This section contains non-Stack Overflow links.)
To find the fastest way to read a file line by line you will have to do some benchmarking. I have done some small tests on my computer but you cannot expect that my results apply to your environment.
Using StreamReader.ReadLine
This is basically your method. For some reason you set the buffer size to the smallest possible value (128). Increasing this will in general increase performance. The default size is 1,024 and other good choices are 512 (the sector size in Windows) or 4,096 (the cluster size in NTFS). You will have to run a benchmark to determine an optimal buffer size. A bigger buffer is - if not faster - at least not slower than a smaller buffer.
const Int32 BufferSize = 128;
using (var fileStream = File.OpenRead(fileName))
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize)) {
String line;
while ((line = streamReader.ReadLine()) != null)
// Process line
}
The FileStream
constructor allows you to specify FileOptions. For example, if you are reading a large file sequentially from beginning to end, you may benefit from FileOptions.SequentialScan
. Again, benchmarking is the best thing you can do.
Using File.ReadLines
This is very much like your own solution except that it is implemented using a StreamReader
with a fixed buffer size of 1,024. On my computer this results in slightly better performance compared to your code with the buffer size of 128. However, you can get the same performance increase by using a larger buffer size. This method is implemented using an iterator block and does not consume memory for all lines.
var lines = File.ReadLines(fileName);
foreach (var line in lines)
// Process line
Using File.ReadAllLines
This is very much like the previous method except that this method grows a list of strings used to create the returned array of lines so the memory requirements are higher. However, it returns String[]
and not an IEnumerable<String>
allowing you to randomly access the lines.
var lines = File.ReadAllLines(fileName);
for (var i = 0; i < lines.Length; i += 1) {
var line = lines[i];
// Process line
}
Using String.Split
This method is considerably slower, at least on big files (tested on a 511 KB file), probably due to how String.Split
is implemented. It also allocates an array for all the lines increasing the memory required compared to your solution.
using (var streamReader = File.OpenText(fileName)) {
var lines = streamReader.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
// Process line
}
My suggestion is to use File.ReadLines
because it is clean and efficient. If you require special sharing options (for example you use FileShare.ReadWrite
), you can use your own code but you should increase the buffer size.
Daniel's answer seems to work fine for now, but please note that generating absolute urls using twig's asset
function is now deprecated:
DEPRECATED - Generating absolute URLs with the Twig asset() function was deprecated in 2.7 and will be removed in 3.0. Please use absolute_url() instead.
Here's the official announcement: http://symfony.com/blog/new-in-symfony-2-7-the-new-asset-component#template-function-changes
You have to use the absolute_url
twig function:
{# Symfony 2.6 #}
{{ asset('logo.png', absolute = true) }}
{# Symfony 2.7 #}
{{ absolute_url(asset('logo.png')) }}
It is interesting to note that it also works with path
function:
{{ absolute_url(path('index')) }}
You could also use strdup
:
The strdup() function returns a pointer to a new string which is a duplicate of the string s.
Memory for the new string is obtained with malloc(3), and can be freed with free(3).
For you example:
char *a = strdup("stack overflow");
I urge you to read this blog post that directly addresses your problem.
Using custom model binders isn't really wise as Phil Haack pointed out (his blog post is linked in the upper blog post as well).
Basically you have three options:
Write a JsonValueProviderFactory
and use a client side library like json2.js
to communicate wit JSON directly.
Write a JQueryValueProviderFactory
that understands the jQuery JSON object transformation that happens in $.ajax
or
Use the very simple and quick jQuery plugin outlined in the blog post, that prepares any JSON object (even arrays that will be bound to IList<T>
and dates that will correctly parse on the server side as DateTime
instances) that will be understood by Asp.net MVC default model binder.
Of all three, the last one is the simplest and doesn't interfere with Asp.net MVC inner workings thus lowering possible bug surface. Using this technique outlined in the blog post will correctly data bind your strong type action parameters and validate them as well. So it is basically a win win situation.
Probably svn import
would be the best option around. Check out Getting Data into Your Repository (in Version Control with Subversion, For Subversion).
The svn import command is a quick way to copy an unversioned tree of files into a repository, creating intermediate directories as necessary. svn import doesn't require a working copy, and your files are immediately committed to the repository. You typically use this when you have an existing tree of files that you want to begin tracking in your Subversion repository. For example:
$ svn import /path/to/mytree \ http://svn.example.com/svn/repo/some/project \ -m "Initial import" Adding mytree/foo.c Adding mytree/bar.c Adding mytree/subdir Adding mytree/subdir/quux.h Committed revision 1. $
The previous example copied the contents of the local directory mytree into the directory some/project in the repository. Note that you didn't have to create that new directory first—svn import does that for you. Immediately after the commit, you can see your data in the repository:
$ svn list http://svn.example.com/svn/repo/some/project bar.c foo.c subdir/ $
Note that after the import is finished, the original local directory is not converted into a working copy. To begin working on that data in a versioned fashion, you still need to create a fresh working copy of that tree.
Note: if you are on the same machine as the Subversion repository you can use the file://
specifier with a path rather than the https://
with a URL specifier.
You can use any one of bellow as both works same way:
getSupportActionBar().setDisplayShowTitleEnabled(false);
and
getSupportActionBar().setTitle(null);
Where to use:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
Or :
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
You can try using get_the_category()
:
$categories = get_the_category();
$category_id = $categories[0]->cat_ID;
If you want to do some serious work with arrays then you should use the numpy library. This will allow you for example to do vector addition and matrix multiplication, and for large arrays it is much faster than Python lists.
However, numpy requires that the size is predefined. Of course you can also store numpy arrays in a list, like:
import numpy as np
vec_list = [np.zeros((3,)) for _ in range(10)]
vec_list.append(np.array([1,2,3]))
vec_sum = vec_list[0] + vec_list[1] # possible because we use numpy
print vec_list[10][2] # prints 3
But since your numpy arrays are pretty small I guess there is some overhead compared to using a tuple. It all depends on your priorities.
See also this other question, which is pretty similar (apart from the variable size).
Thats because DataGridView looks for properties of containing objects. For string there is just one property - length. So, you need a wrapper for a string like this
public class StringValue
{
public StringValue(string s)
{
_value = s;
}
public string Value { get { return _value; } set { _value = value; } }
string _value;
}
Then bind List<StringValue>
object to your grid. It works
If you want to process your String one character at a time. you have various options.
uhello = u'Hello\u0020World'
Using List comprehension:
print([x for x in uhello])
Output:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
Using map:
print(list(map(lambda c2: c2, uhello)))
Output:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
Calling Built in list function:
print(list(uhello))
Output:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
Using for loop:
for c in uhello:
print(c)
Output:
H
e
l
l
o
W
o
r
l
d
As the others mentioned, it's "exec" ..
but, in case your code contains variables, you can use "global" to access it, also to prevent the compiler to raise the following error:
NameError: name 'p_variable' is not defined
exec('p_variable = [1,2,3,4]')
global p_variable
print(p_variable)
Anyone who is just starting with Haskell and trying to print an Int, use:
module Lib
( someFunc
) where
someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)
In a POST request, the parameters are sent in the body of the request, that's why you don't see them in the URL.
If you want to see them, change
type: 'POST',
to
type: 'GET',
Note that browsers have development tools which lets you see the complete requests that your code issues. In Chrome, it's in the "Network" panel.
If you really just want a random value from the available key range, use random.choice
on the dictionary's values (converted to list form, if Python 3).
>>> from random import choice
>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>>> choice(list(d.values()))
As of the C++11
standard, string-to-number conversion and vice-versa are built in into the standard library. All the following functions are present in <string>
(as per paragraph 21.5).
float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);
int stoi(const string& str, size_t *idx = 0, int base = 10);
long stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);
long long stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);
Each of these take a string as input and will try to convert it to a number. If no valid number could be constructed, for example because there is no numeric data or the number is out-of-range for the type, an exception is thrown (std::invalid_argument
or std::out_of_range
).
If conversion succeeded and idx
is not 0
, idx
will contain the index of the first character that was not used for decoding. This could be an index behind the last character.
Finally, the integral types allow to specify a base, for digits larger than 9, the alphabet is assumed (a=10
until z=35
). You can find more information about the exact formatting that can parsed here for floating-point numbers, signed integers and unsigned integers.
Finally, for each function there is also an overload that accepts a std::wstring
as it's first parameter.
string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);
These are more straightforward, you pass the appropriate numeric type and you get a string back. For formatting options you should go back to the C++03 stringsream option and use stream manipulators, as explained in an other answer here.
As noted in the comments these functions fall back to a default mantissa precision that is likely not the maximum precision. If more precision is required for your application it's also best to go back to other string formatting procedures.
There are also similar functions defined that are named to_wstring
, these will return a std::wstring
.
i Change the format of file to *.XLSX this change compress my file and reduce file size of 15%
In my case the error was pointing to the AndroidManifest.xml file. I had this line:
<meta-data
android:name="com.google.android.actions"
android:resource="@xml/popup_info.xml" />
Which, I'm not sure why Android Studio put that there. I didn't change my manifest file, and this never happened until I upgraded to version 3.5.3 - so AS must have done it for me. Anyway, the line should have looked like this:
<meta-data
android:name="com.google.android.actions"
android:resource="@layout/popup" />
Once I changed that, it was all good.
Depending on how you're using the list, it may be worth it to use a TreeSet and then use the toArray() method at the end. I had a case where I needed a sorted list, and I found that the TreeSet + toArray() was much faster than adding to an array and merge sorting at the end.
yum uses RPM, so the following command will list the contents of the installed package:
$ rpm -ql package-name
console.log()
and console.dir()
:Here is the difference in a nutshell:
console.log(input)
: The browser logs in a nicely formatted mannerconsole.dir(input)
: The browser logs just the object with all its propertiesThe following code:
let obj = {a: 1, b: 2};
let DOMel = document.getElementById('foo');
let arr = [1,2,3];
console.log(DOMel);
console.dir(DOMel);
console.log(obj);
console.dir(obj);
console.log(arr);
console.dir(arr);
Logs the following in google dev tools:
Are you using HTML5? If so, check whether you have any <input type="hidden">
in your form with the property required
. Remove that required
property. Internet Explorer won't take this property, so it works but Chrome will.
Access it like any other pointer value:
std::vector<int>* v = new std::vector<int>();
v->push_back(0);
v->push_back(12);
v->push_back(1);
int twelve = v->at(1);
int one = (*v)[2];
// iterate it
for(std::vector<int>::const_iterator cit = v->begin(), e = v->end;
cit != e; ++cit)
{
int value = *cit;
}
// or, more perversely
for(int x = 0; x < v->size(); ++x)
{
int value = (*v)[x];
}
// Or -- with C++ 11 support
for(auto i : *v)
{
int value = i;
}
You can use the redirect URL to controller:
Class Ctrlr1 extends CI_Controller{
public void my_fct1(){
redirect('Ctrlr2 /my_fct2', 'refresh');
}
}
Class Ctrlr2 extends CI_Controller{
public void my_fct2(){
$this->load->view('view1');
}
}
Edit: copyitright has pointed out that this is unreliable. Approving read access with UAC will allow dir to succeed. I have a bit more script to offer another possibility, but it's not read-only.
reg query "HKLM\SOFTWARE\Foo" >NUL 2>NUL && goto :error_key_exists
reg add "HKLM\SOFTWARE\Foo" /f >NUL 2>NUL || goto :error_not_admin
reg delete "HKLM\SOFTWARE\Foo" /f >NUL 2>NUL || goto :error_failed_delete
goto :success
:error_failed_delete
echo Error unable to delete test key
exit /b 3
:error_key_exists
echo Error test key exists
exit /b 2
:error_not_admin
echo Not admin
exit /b 1
:success
echo Am admin
Old answer below
Warning: unreliable
Based on a number of other good answers here and points brought up by and31415 I found that I am a fan of the following:
dir "%SystemRoot%\System32\config\DRIVERS" 2>nul >nul || echo Not Admin
Few dependencies and fast.
The limitations of a 32-bit JVM on a 64-bit OS will be exactly the same as the limitations of a 32-bit JVM on a 32-bit OS. After all, the 32-bit JVM will be running In a 32-bit virtual machine (in the virtualization sense) so it won't know that it's running on a 64-bit OS/machine.
The one advantage to running a 32-bit JVM on a 64-bit OS versus a 32-bit OS is that you can have more physical memory, and therefore will encounter swapping/paging less frequently. This advantage is only really fully realized when you have multiple processes, however.
To include the direction along with the orderBy function:
ng-repeat="card in cards | orderBy:myOrderbyFunction():defaultSortDirection"
where
defaultSortDirection = 0; // 0 = Ascending, 1 = Descending
Docker now recommends migrating towards using --mount
.
Multiple volume mounts are also explained in detail in the current Docker documentation.
From: https://docs.docker.com/storage/bind-mounts/
$ docker run -d \
-it \
--name devtest \
--mount type=bind,source="$(pwd)"/target,target=/app \
--mount type=bind,source="$(pwd)"/target,target=/app2,readonly,bind-propagation=rslave \
nginx:latest
Original older answer should still work; just trying to keep the answer aligned to current best known method.
I think you should use this code in Laravel version 5+.
Also this will work not only with parameter page
but also with any other parameter(s):
$users->appends(request()->input())->links();
Personally, I try to avoid using Facades
as much as I can. Using global helper functions is less code and much elegant.
UPDATE:
Do not use Input
Facade as it is deprecated in Laravel v6+
Test castEnum = static_cast<Test>(a-1);
will cast a
to A
. If you don't want to substruct 1, you can redefine the enum
:
enum Test
{
A:1, B
};
In this case Test castEnum = static_cast<Test>(a);
could be used to cast a
to A
.
Could it work declaring the filter the following way?
app.filter('dateUTC', function ($filter) {
return function (input, format) {
if (!angular.isDefined(format)) {
format = 'dd/MM/yyyy';
}
var date = new Date(input);
return $filter('date')(date.toISOString().slice(0, 23), format);
};
});
If you have not pushed the changes already:
git rm -r --cached .
git add .
git commit -m 'clear git cache'
git push
It is not necessary to stop timer, see nice solution from this post:
"You could let the timer continue firing the callback method but wrap your non-reentrant code in a Monitor.TryEnter/Exit. No need to stop/restart the timer in that case; overlapping calls will not acquire the lock and return immediately."
private void CreatorLoop(object state)
{
if (Monitor.TryEnter(lockObject))
{
try
{
// Work here
}
finally
{
Monitor.Exit(lockObject);
}
}
}
The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:
$('form').on('submit',doFormStuff);
createNewForm();
// re-attach to all forms
$('form').off('submit').on('submit',doFormStuff);
Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:
function bindItems(){
$('form').off('submit').on('submit',doFormStuff);
$('button').off('click').on('click',doButtonStuff);
}
So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.
createNewButton();
bindItems();
I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.
Create build.gradle file in facebook sdk project:
apply plugin: 'android-library'
dependencies {
compile 'com.android.support:support-v4:18.0.+'
}
android {
compileSdkVersion 8
buildToolsVersion "19.0.0"
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
// Move the build types to build-types/<type>
// For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
// This moves them out of them default location under src/<type>/... which would
// conflict with src/ being used by the main source set.
// Adding new build types or product flavors should be accompanied
// by a similar customization.
debug.setRoot('build-types/debug')
release.setRoot('build-types/release')
}
}
Then add include ':libs:facebook'
equals <project_directory>/libs/facebook
(path to library) in settings.gradle
.
json characters are nothing special when it comes down to storage, chars such as
{
,}
,[
,]
,'
,a-z
,0-9
.... are really nothing special and can be stored as text.
the first problem your going to have is this
{ profile_id: 22, username: 'Robert', password: 'skhgeeht893htgn34ythg9er' }
that stored in a database is not that simple to update unless you had your own proceedure and developed a jsondecode for mysql
UPDATE users SET JSON(user_data,'username') = 'New User';
So as you cant do that you would Have to first SELECT the json, Decode it, change it, update it, so in theory you might as well spend more time constructing a suitable database structure!
I do use json to store data but only Meta Data, data that dont get updated often, not related to the user specific.. example if a user adds a post, and in that post he adds images ill parse the images and create thumbs and then use the thumb urls in a json format.
You can use the following approach:
[lower + x*(upper-lower)/length for x in range(length)]
lower and/or upper must be assigned as floats for this approach to work.
To avoid the fact that destroy_all
instantiates all the records and destroys them one at a time, you can use it directly from the model class.
So instead of :
u = User.find_by_name('JohnBoy')
u.usage_indexes.destroy_all
You can do :
u = User.find_by_name('JohnBoy')
UsageIndex.destroy_all "user_id = #{u.id}"
The result is one query to destroy all the associated records
If you are sending this through your own mail server you might need to add a "Sender" header which will contain an email address of from your own domain. Gmail will probably be spamming the email because the FROM address is a gmail address but has not been sent from their own server.
No, you can't. Just declare the variable outside the function. You don't have to declare it at the same time as you assign the value:
var trailimage;
function makeObj(address) {
trailimage = [address, 50, 50];
I know this is an old question but I did it like:
<asp:RadioButtonList runat="server" ID="myrbl" RepeatDirection="Horizontal" CssClass="rbl">
Use this as your class:
.rbl input[type="radio"]
{
margin-left: 10px;
margin-right: 1px;
}
I see some of the other answers calling the modulo twice.
My preference is not to ask php to do the same thing more than once. For this reason, I cache the remainder.
Other devs may prefer to not generate the extra global variable or have other justifications for using modulo operator twice.
Code: (Demo)
$factor = 6;
for($x = 0; $x < 10; ++$x){ // battery of 10 tests
$number = rand( 0 , 100 );
echo "Number: $number Becomes: ";
if( $remainder = $number % $factor ) { // if not zero
$number += $factor - $remainder; // use cached $remainder instead of calculating again
}
echo "$number\n";
}
Possible Output:
Number: 80 Becomes: 84
Number: 57 Becomes: 60
Number: 94 Becomes: 96
Number: 48 Becomes: 48
Number: 80 Becomes: 84
Number: 36 Becomes: 36
Number: 17 Becomes: 18
Number: 41 Becomes: 42
Number: 3 Becomes: 6
Number: 64 Becomes: 66
.set_title('') can be used to add title to Seaborn Plot
import seaborn as sb
sb.boxplot().set_title('Title')
Specific use case for emplace_back
: If you need to create a temporary object which will then be pushed into a container, use emplace_back
instead of push_back
. It will create the object in-place within the container.
Notes:
push_back
in the above case will create a temporary object and move it
into the container. However, in-place construction used for emplace_back
would be more
performant than constructing and then moving the object (which generally involves some copying).emplace_back
instead of push_back
in all the cases without much issue. (See exceptions)Failure [INSTALL_FAILED_OLDER_SDK] basically means that the installation has failed due to the target location (AVD/Device) having an older SDK version than the targetSdkVersion specified in your app.
N/B Froyo 2.2 API 8
To fix this simply change
targetSdkVersion="17" to targetSdkVersion="8"
cheers.
If you want to find dependencies recursively (including dependencies of dependencies, dependencies of dependencies of dependencies and so on)…
You may use ldd
command.
ldd - print shared library dependencies
Using Script Console.
In case the jobs are grouped it's possible to either give it a full name with forward slashes:
getItemByFullName("folder_name/job_name")
job.getBuilds().each { it.delete() }
job.nextBuildNumber = 1
job.save()
or traverse the hierarchy like this:
def folder = Jenkins.instance.getItem("folder_name")
def job = folder.getItem("job_name")
job.getBuilds().each { it.delete() }
job.nextBuildNumber = 1
job.save()
A scrolling comes from a box with class pre-scrollable
<div class="pre-scrollable"></div>
There's more examples: http://getbootstrap.com/css/#code-block
Wish it helps.
iPhone & iPod touch:
<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="../iphone.css" type="text/css" />
iPhone 4 & iPod touch 4G:
<link rel="stylesheet" media="only screen and (-webkit-min-device-pixel-ratio: 2)" type="text/css" href="../iphone4.css" />
iPad:
<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="../ipad.css" type="text/css" />
To archive the necessary result with double constructor you need to round the BigDecimal before convert it to String e.g.
new java.math.BigDecimal(10.0001).round(new java.math.MathContext(6, java.math.RoundingMode.HALF_UP)).toString()
will print the "10.0001"
It depends.
When you commit to sending output to stdout
, you're basically leaving it up to the user to decide where that output should go.
If you use printf(...)
(or the equivalent fprintf(stdout, ...)
), you're sending the output to stdout
, but where that actually ends up can depend on how I invoke your program.
If I launch your program from my console like this, I'll see output on my console:
$ prog
Hello, World! # <-- output is here on my console
However, I might launch the program like this, producing no output on the console:
$ prog > hello.txt
but I would now have a file "hello.txt" with the text "Hello, World!" inside, thanks to the shell's redirection feature.
Who knows – I might even hook up some other device and the output could go there. The point is that when you decide to print to stdout
(e.g. by using printf()
), then you won't exactly know where it will go until you see how the process is launched or used.
To tell eclipse to use JDK, you have to follow the below steps.
After completing the above steps, you are done now and eclipse will start using the selected JDK for compilation.
.clearfix
is defined in less/mixins.less
. Right above its definition is a comment with a link to this article:
The article explains how it all works.
UPDATE: Yes, link-only answers are bad. I knew this even at the time that I posted this answer, but I didn't feel like copying and pasting was OK due to copyright, plagiarism, and what have you. However, I now feel like it's OK since I have linked to the original article. I should also mention the author's name, though, for credit: Nicolas Gallagher. Here is the meat of the article (note that "Thierry’s method" is referring to Thierry Koblentz’s “clearfix reloaded”):
This “micro clearfix” generates pseudo-elements and sets their
display
totable
. This creates an anonymous table-cell and a new block formatting context that means the:before
pseudo-element prevents top-margin collapse. The:after
pseudo-element is used to clear the floats. As a result, there is no need to hide any generated content and the total amount of code needed is reduced.Including the
:before
selector is not necessary to clear the floats, but it prevents top-margins from collapsing in modern browsers. This has two benefits:
It ensures visual consistency with other float containment techniques that create a new block formatting context, e.g.,
overflow:hidden
It ensures visual consistency with IE 6/7 when
zoom:1
is applied.N.B.: There are circumstances in which IE 6/7 will not contain the bottom margins of floats within a new block formatting context. Further details can be found here: Better float containment in IE using CSS expressions.
The use of
content:" "
(note the space in the content string) avoids an Opera bug that creates space around clearfixed elements if thecontenteditable
attribute is also present somewhere in the HTML. Thanks to Sergio Cerrutti for spotting this fix. An alternative fix is to usefont:0/0 a
.Legacy Firefox
Firefox < 3.5 will benefit from using Thierry’s method with the addition of
visibility:hidden
to hide the inserted character. This is because legacy versions of Firefox needcontent:"."
to avoid extra space appearing between thebody
and its first child element, in certain circumstances (e.g., jsfiddle.net/necolas/K538S/.)Alternative float-containment methods that create a new block formatting context, such as applying
overflow:hidden
ordisplay:inline-block
to the container element, will also avoid this behaviour in legacy versions of Firefox.
Write a function lensort to sort a list of strings based on length.
def lensort(a):
n = len(a)
for i in range(n):
for j in range(i+1,n):
if len(a[i]) > len(a[j]):
temp = a[i]
a[i] = a[j]
a[j] = temp
return a
print lensort(["hello","bye","good"])
you should try this
~/Views/Shared/parts/UMFview.ascx
place the ~/Views/
before your code
I found also this list of property flags: How to use the UserAccountControl flags
SCRIPT 0x0001 1
ACCOUNTDISABLE 0x0002 2
HOMEDIR_REQUIRED 0x0008 8
LOCKOUT 0x0010 16
PASSWD_NOTREQD 0x0020 32
PASSWD_CANT_CHANGE 0x0040 64
ENCRYPTED_TEXT_PWD_ALLOWED 0x0080 128
TEMP_DUPLICATE_ACCOUNT 0x0100 256
NORMAL_ACCOUNT 0x0200 512
INTERDOMAIN_TRUST_ACCOUNT 0x0800 2048
WORKSTATION_TRUST_ACCOUNT 0x1000 4096
SERVER_TRUST_ACCOUNT 0x2000 8192
DONT_EXPIRE_PASSWORD 0x10000 65536
MNS_LOGON_ACCOUNT 0x20000 131072
SMARTCARD_REQUIRED 0x40000 262144
TRUSTED_FOR_DELEGATION 0x80000 524288
NOT_DELEGATED 0x100000 1048576
USE_DES_KEY_ONLY 0x200000 2097152
DONT_REQ_PREAUTH 0x400000 4194304
PASSWORD_EXPIRED 0x800000 8388608
TRUSTED_TO_AUTH_FOR_DELEGATION 0x1000000 16777216
PARTIAL_SECRETS_ACCOUNT 0x04000000 67108864
You must make a binary-AND of property userAccountControl
with 0x002
. In order to get all locked (i.e. disabled) accounts you can filter on this:
(&(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=2))
For operator 1.2.840.113556.1.4.803
see LDAP Matching Rules
There is a built-in library called pickle
. Using pickle
you can dump objects to a file and load them later.
import pickle
f = open('store.pckl', 'wb')
pickle.dump(obj, f)
f.close()
f = open('store.pckl', 'rb')
obj = pickle.load(f)
f.close()
One option is just to use the regex |
character to try to match each of the substrings in the words in your Series s
(still using str.contains
).
You can construct the regex by joining the words in searchfor
with |
:
>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0 cat
1 hat
2 dog
3 fog
dtype: object
As @AndyHayden noted in the comments below, take care if your substrings have special characters such as $
and ^
which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.
You can make your list of substrings safer by escaping non-alphanumeric characters with re.escape
:
>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']
The strings with in this new list will match each character literally when used with str.contains
.
If you're using Windows 10, if you use
py -m pip install pyqt5
in the command prompt it should download fine. Depending on either the version of Python or Windows sometimes python -m pip install pyqt5
isn't accepted, so you have to use py instead. pip is a good way to download a lot of stuff, so I'd recommend that.
We can append or prepend two lists or list&array
Append:
var l = List(1,2,3)
l = l :+ 4
Result : 1 2 3 4
var ar = Array(4, 5, 6)
for(x <- ar)
{ l = l :+ x }
l.foreach(println)
Result:1 2 3 4 5 6
Prepending:
var l = List[Int]()
for(x <- ar)
{ l= x :: l } //prepending
l.foreach(println)
Result:6 5 4 1 2 3
This Perl code removes commas at the end of the line:
perl -pe 's/,$//' file > file.nocomma
This variation still works if there is whitespace after the comma:
perl -lpe 's/,\s*$//' file > file.nocomma
This variation edits the file in-place:
perl -i -lpe 's/,\s*$//' file
This variation edits the file in-place, and makes a backup file.bak
:
perl -i.bak -lpe 's/,\s*$//' file