Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
I had the same problem when tom?at could not find the class. Try to view other log files. Sometimes No class def found error appears in different log files:
Old question, but where others use JOIN to combine unrelated queries to rows in one table, this is my solution to combine unrelated queries to one row, e.g:
select
(select count(*) c from v$session where program = 'w3wp.exe') w3wp,
(select count(*) c from v$session) total,
sysdate
from dual;
which gives the following one-row output:
W3WP TOTAL SYSDATE
----- ----- -------------------
14 290 2020/02/18 10:45:07
(which tells me that our web server currently uses 14 Oracle sessions out of the total of 290 sessions; I log this output without headers in an sqlplus script that runs every so many minutes)
The following code could be used to not use the string type:
int decimalResult = 789.500
while (decimalResult>0 && decimalResult % 10 == 0)
{
decimalResult = decimalResult / 10;
}
return decimalResult;
Returns 789.5
The other answers don't work. The only way to see the captured output is using the following flag:
pytest --show-capture all
A Float
represents double
in SQL server. You can find a proof from the coding in C# in visual studio. Here I have declared Overtime
as a Float
in SQL server and in C#. Thus I am able to convert
int diff=4;
attendance.OverTime = Convert.ToDouble(diff);
Here OverTime
is declared float type
Not very simple but:
a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,3].count(k)}.values.flatten
=> [1, 1, 2, 2]
Also handles the case for multiples in the 'subtrahend':
a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,1,3].count(k)}.values.flatten
=> [1, 2, 2]
EDIT: this is more an enhancement combining Norm212 and my answer to make a "functional" solution.
b = [1,1,3].each.with_object( a ) { |del| a.delete_at( a.index( del ) ) }
Put it in a lambda if needed:
subtract = lambda do |minuend, subtrahend|
subtrahend.each.with_object( minuend ) { |del| minuend.delete_at( minuend.index( del ) ) }
end
then:
subtract.call a, [1,1,3]
In SQL Server 2008 you can use the MERGE statement
Run away from store procedures as much as possible. They are pretty hard to maintain and are VERY OLD STUFF ;)
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.
Here's how to do it for Internet Explorer:
function copy (str)
{
//for IE ONLY!
window.clipboardData.setData('Text',str);
}
HTML is intended for structuring data, not controlling layout. CSS is intended to control layout. You'll also find that many designers frown on using <table>
for layouts for this very same reason.
If you're using GNU find,
find . -mtime 1 -exec cp -t ~/test/ {} +
This works as well as piping the output into xargs
while avoiding the pitfalls of doing so (it handles embedded spaces and newlines without having to use find ... -print0 | xargs -0 ...
).
Possibly mine isn't a great answer but here goes.
Since working more with truly RESTful web services over HTTP, I've tried to steer people away from using the term endpoint since it has no clear definition, and instead use the language of REST which is resources and resource locations.
To my mind, endpoint is a TCP term. It's conflated with HTTP because part of the URL identifies a listening server.
So resource isn't a newer term, I don't think, I think endpoint was always misappropriated and we're realising that as we're getting our heads around REST as a style of API.
Edit
I blogged about this.
https://medium.com/@lukepuplett/stop-saying-endpoints-92c19e33e819
In C++ you can access fields or methods, using different operators, depending on it's type:
Note that :: should be used with a class name rather than a class instance, since static fields or methods are common to all instances of a class.
class AClass{
public:
static int static_field;
int instance_field;
static void static_method();
void method();
};
then you access this way:
AClass instance;
AClass *pointer = new AClass();
instance.instance_field; //access instance_field through a reference to AClass
instance.method();
pointer->instance_field; //access instance_field through a pointer to AClass
pointer->method();
AClass::static_field;
AClass::static_method();
INNER JOIN = JOIN
INNER JOIN is the default if you don't specify the type when you use the word JOIN.
You can also use LEFT OUTER JOIN or RIGHT OUTER JOIN, in which case the word OUTER is optional, or you can specify CROSS JOIN.
OR
For an inner join, the syntax is:
SELECT ...
FROM TableA
[INNER] JOIN TableB(in other words, the "INNER" keyword is optional - results are the same with or without it)
Yes it's possible (but not recommended).
CREATE TABLE contact (contactid int, name varchar(100), dob datetime)
INSERT INTO contact SELECT 1, 'Joe', '1974-01-01'
DECLARE @columns varchar(8000)
SELECT @columns = ISNULL(@columns + ', ','') + QUOTENAME(column_name)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'contact' AND COLUMN_NAME <> 'dob'
ORDER BY ORDINAL_POSITION
EXEC ('SELECT ' + @columns + ' FROM contact')
Explanation of the code:
SELECT @variable = @variable + ... FROM
to concatenate the
column names. This type of SELECT
does not not return a result set. This is perhaps undocumented behaviour but works in every version of SQL Server. As an alternative you could use SET @variable = (SELECT ... FOR XML PATH(''))
to concatenate strings.ISNULL
function to prepend a comma only if this is not the
first column name.
Use the QUOTENAME
function to support spaces and punctuation in column names.WHERE
clause to hide columns we don't want to see.EXEC (@variable)
, also known as dynamic SQL, to resolve the
column names at runtime. This is needed because we don't know the column names at compile time.I was having the same problem when I received a html to put inside my project and rename it to .jsp. To solve the problem, I needed to what people above already said, that is, to change text encoding in Eclipse Preferences. However, before renaming the files to .jsp, it was necessary to include the following line in the beginning of each .html file:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
I believe this forced Eclipse to understand that it was necessary to change file encoding when I tried to rename .html to .jsp.
I know you've found a solution to your question, I just wanted to recommend that maybe you look at the following more extensive jQuery plugin for International Number Formats:
Can be pretty easily done assuming you're using jQuery and css3:
HTML:
<div id="clicker">Click Here</div>
<div id="rotating"></div>
CSS:
#clicker {
width: 100px;
height: 100px;
background-color: Green;
}
#rotating {
width: 100px;
height: 100px;
background-color: Red;
margin-top: 50px;
-webkit-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-in-out;
-o-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
.rotated {
transform:rotate(25deg);
-webkit-transform:rotate(25deg);
-moz-transform:rotate(25deg);
-o-transform:rotate(25deg);
}
JS:
$(document).ready(function() {
$('#clicker').click(function() {
$('#rotating').toggleClass('rotated');
});
});
A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.
Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).
Depending on how many options you have, you could put your values in an array and auto-populate your options like this
<select ng-model="somethingHere.values" ng-options="values for values in [5,4,3,2,1]">
<option value="">Pick a Number</option>
</select>
16x16 pixels, *.ico format.
If the difference between endTime and startTime is greater than or equal to 60 Minutes , the statement:endTime.Subtract(startTime).Minutes;
will always return (minutesDifference % 60)
. Obviously which is not desired when we are only talking about minutes (not hours here).
Here are some of the ways if you want to get total number of minutes
(in different typecasts):
// Default value that is returned is of type *double*
double double_minutes = endTime.Subtract(startTime).TotalMinutes;
int integer_minutes = (int)endTime.Subtract(startTime).TotalMinutes;
long long_minutes = (long)endTime.Subtract(startTime).TotalMinutes;
string string_minutes = (string)endTime.Subtract(startTime).TotalMinutes;
There are probably embedded tabs (CHAR(9)
) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:
DECLARE @var NVARCHAR(255), @i INT;
SET @i = 1;
SELECT @var = AccountType FROM dbo.Account
WHERE AccountNumber = 200
AND AccountType LIKE '%Daily%';
CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));
WHILE @i <= LEN(@var)
BEGIN
INSERT #x
SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));
SET @i = @i + 1;
END
SELECT i,c,a FROM #x ORDER BY i;
You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.
It's in an additional download. Use this menu item:
Xcode > Open Developer Tool > More Developer Tools...
and get "Hardware IO Tools for Xcode".
For Xcode 8+, get "Additional Tools for Xcode [version]".
Double-click on a .prefPane
file to install. If you already have an older .prefPane
installed, you'll need to remove it from /Library/PreferencePanes
.
As already mentioned, this is simply not allowed and I think it makes a very good sense. However, to add some more details, here is a quote from the C# 4.0 Specification, section 21.1:
Formal parameters of constructors, methods, indexers and delegate types can be declared optional:
fixed-parameter:
attributesopt parameter-modifieropt type identifier default-argumentopt
default-argument:
= expression
- A fixed-parameter with a default-argument is an optional parameter, whereas a fixed-parameter without a default-argument is a required parameter.
- A required parameter cannot appear after an optional parameter in a formal-parameter-list.
- A
ref
orout
parameter cannot have a default-argument.
import numpy
X = numpy.array(the_big_nested_list_you_had)
It's still not going to do what you want; you have more bugs, like trying to unpack a 3-dimensional shape into two target variables in test
.
This is an old question, I know but for 2019 peeps:
Like above if you just want to change the URL you can do this:
<select onChange="window.location.href=this.value">
<option value="www.google.com">A</option>
<option value="www.aol.com">B</option>
</select>
But if you want it to act like an a tag and so you can do "./page"
, "#bottom"
or "?a=567"
use window.location.replace()
<select onChange="window.location.redirect(this.value)">
<option value="..">back</option>
<option value="./list">list</option>
<option value="#bottom">bottom</option>
</select>
Check that the server name you're logging into with SQL Management Studio matches your connection string.
I was getting this error today. It turned out that I hadn't realised the machine with SQL Server installed had multiples servers running. I had in fact put my database in a totally different server to the one I thought I was using. (So my connection string was pointing to a server with no database)
Hence, When .net tried to access the database it couldn't find anything and gave only a misleading error message about pipes.
I opened the correct server in SQL Management Studio, added my database to and then all worked fine. (If the correct server isn't available in the dropdown, try browsing for it.)
This should be enough to force an IE
user to drop compatibility mode in any IE
version:
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
However, there are a couple of caveats one should be aware of:
<head>
. Only the <title>
tag may be placed above it.If you don't do that, you'll get an error on IE9
Dev Tools: X-UA-Compatible META tag ignored because document mode is already finalized.
If you want this markup to validate, make sure you remember to close the meta
tag with a />
instead of just >
.
Starting with IE11
, edge mode is the preferred document mode. To support/enable that, use the HTML5 document type declaration <!doctype html>
.
If you need to support webfonts on IE7
, make sure you use <!DOCTYPE html>
. I've tested it and found that rendering webfonts on IE7
got pretty unreliable when using <!doctype html>
.
The use of Google Chrome Frame is popular, but unfortunately it's going to be dropped sometime this month, Jan. 2014.
<meta http-equiv="X-UA-Compatible" content="IE=EDGE,chrome=1">
Extensive related info here. The tip on using it as the first meta tag is on a previously mentioned source here, which has been updated.
I am using IntelliJ 2020.3.1 and the File > Other Settings... menu option has disappeared. I went to Settings in the usual way and searched for "jdk". Under Build, Execution, Deployment > Build Tools > Maven > Importing I found the the setting that will solve my specific issue:
JDK for importer.
The Best way is do not use any pairing code.
Instead of onClick
go to other function or other class where You create the socket using UUID.
Android automatically pops up for pairing if already not paired.
or see this link for better understanding
Below is code for the same:
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
// **add this 2 line code**
Intent myIntent = new Intent(view.getContext(), Connect.class);
startActivityForResult(myIntent, 0);
finish();
}
};
Connect.java file is :
public class Connect extends Activity {
private static final String TAG = "zeoconnect";
private ByteBuffer localByteBuffer;
private InputStream in;
byte[] arrayOfByte = new byte[4096];
int bytes;
public BluetoothDevice mDevice;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connect);
try {
setup();
} catch (ZeoMessageException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ZeoMessageParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setup() throws ZeoMessageException, ZeoMessageParseException {
// TODO Auto-generated method stub
getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
getRemoteDevice("**:**:**:**:**:**");// add device mac adress
try {
sock = zee.createRfcommSocketToServiceRecord(
UUID.fromString("*******************")); // use unique UUID
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Connecting");
try {
sock.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Connected");
try {
in = sock.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Listening...");
while (true) {
try {
bytes = in.read(arrayOfByte);
Log.d(TAG, "++++ Read "+ bytes +" bytes");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Done: test()");
}}
private static final LogBroadcastReceiver receiver = new LogBroadcastReceiver();
public static class LogBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) {
Log.d("ZeoReceiver", paramAnonymousIntent.toString());
Bundle extras = paramAnonymousIntent.getExtras();
for (String k : extras.keySet()) {
Log.d("ZeoReceiver", " Extra: "+ extras.get(k).toString());
}
}
};
private BluetoothSocket sock;
@Override
public void onDestroy() {
getApplicationContext().unregisterReceiver(receiver);
if (sock != null) {
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onDestroy();
}
}
__func__
is an implicitly declared identifier that expands to a character array variable containing the function name when it is used inside of a function. It was added to C in C99. From C99 §6.4.2.2/1:
The identifier
__func__
is implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declarationstatic const char __func__[] = "function-name";
appeared, where function-name is the name of the lexically-enclosing function. This name is the unadorned name of the function.
Note that it is not a macro and it has no special meaning during preprocessing.
__func__
was added to C++ in C++11, where it is specified as containing "an implementation-de?ned string" (C++11 §8.4.1[dcl.fct.def.general]/8), which is not quite as useful as the specification in C. (The original proposal to add __func__
to C++ was N1642).
__FUNCTION__
is a pre-standard extension that some C compilers support (including gcc and Visual C++); in general, you should use __func__
where it is supported and only use __FUNCTION__
if you are using a compiler that does not support it (for example, Visual C++, which does not support C99 and does not yet support all of C++0x, does not provide __func__
).
__PRETTY_FUNCTION__
is a gcc extension that is mostly the same as __FUNCTION__
, except that for C++ functions it contains the "pretty" name of the function including the signature of the function. Visual C++ has a similar (but not quite identical) extension, __FUNCSIG__
.
For the nonstandard macros, you will want to consult your compiler's documentation. The Visual C++ extensions are included in the MSDN documentation of the C++ compiler's "Predefined Macros". The gcc documentation extensions are described in the gcc documentation page "Function Names as Strings."
Removes any trailing commas:
while (strgroupids.EndsWith(","))
strgroupids = strgroupids.Substring(0, strgroupids.Length - 1);
This is backwards though, you wrote the code that adds the comma in the first place. You should use string.Join(",",g)
instead, assuming g
is a string[]
. Give it a better name than g
too !
Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.
Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.
As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:
Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.
Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:
meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)
Formula is from Chris Broadfoot's comment.
Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
What you're looking for are the scales for each zoom level. Use these:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000
import urllib, urllib2, cookielib
username = 'myuser'
password = 'mypassword'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()
resp.read()
is the straight html of the page you want to open, and you can use opener
to view any page using your session cookie.
$("#btnAddProfile").text("Save");
Template argument deduction for class templates
[*this]{ std::cout << could << " be " << useful << '\n'; }
[[fallthrough]]
, [[nodiscard]]
, [[maybe_unused]]
attributes
using
in attributes to avoid having to repeat an attribute namespace.
Compilers are now required to ignore non-standard attributes they don't recognize.
Simple static_assert(expression);
with no string
no throw
unless throw()
, and throw()
is noexcept(true)
.
std::tie
with auto
const auto [it, inserted] = map.insert( {"foo", bar} );
it
and inserted
with deduced type from the pair
that map::insert
returns.std::array
s and relatively flat structsif (init; condition)
and switch (init; condition)
if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
if(decl)
to cases where decl
isn't convertible-to-bool sensibly.Generalizing range-based for loops
Fixed order-of-evaluation for (some) expressions with some modifications
.then
on future work.Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
std::string
like reference-to-character-array or substringstring const&
again. Also can make parsing a bajillion times faster."hello world"sv
char_traits
std::byte
off more than they could chew.
std::invoke
std::apply
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
result_of
is_invocable<Foo(Args...), R>
is "can you call Foo
with Args...
and get something compatible with R
", where R=void
is default.invoke_result<Foo, Args...>
is std::result_of_t<Foo(Args...)>
but apparently less confusing?[class.directory_iterator]
and [class.recursive_directory_iterator]
fstream
s can be opened with path
s, as well as with const path::value_type*
strings.
for_each_n
reduce
transform_reduce
exclusive_scan
inclusive_scan
transform_exclusive_scan
transform_inclusive_scan
Added for threading purposes, exposed even if you aren't using them threaded
atomic<T>
::is_always_lockfree
std::lock
pain when locking more than one mutex at a time.std
algorithms, and related machinery[func.searchers]
and [alg.search]
std::function
for allocatorsstd::sample
, sampling from a range?
try_emplace
and insert_or_assign
Splicing for map<>
, unordered_map<>
, set<>
, and unordered_set<>
non-const .data()
for string.
non-member std::size
, std::empty
, std::data
std::begin
/end
The emplace
family of functions now returns a reference to the created object.
unique_ptr<T[]>
fixes and other unique_ptr
tweaks.weak_from_this
and some fixed to shared from thisstd
datatype improvements:{}
construction of std::tuple
and other improvementsC++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
std
implementations exposedstd::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughlygcd
and lcm
std::uncaught_exceptions
std::as_const
std::bool_constant
_v
template variablesstd::void_t<T>
std::owner_less<void>
std::less<void>
, but for smart pointers to sort based on contentsstd::chrono
polishstd::conjunction
, std::disjunction
, std::negation
exposedstd::not_fn
std
std::less
.<codecvt>
memory_order_consume
result_of
, replaced with invoke_result
shared_ptr::unique
, it isn't very threadsafeIsocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
register
, keyword reserved for future usebool b; ++b;
<functional>
stuff, random_shuffle
std::function
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
https://isocpp.org/files/papers/p0636r0.html
In my case, it happenned for the master branch. Later found that my access to the project was accidentally revoked by the project manager. To cross-check, I visited the review site and couldn't see any commits of the said branch and others for that project.
CASE
isn't used for flow control... for this, you would need to use IF
...
But, there's a set-based solution to this problem instead of the procedural approach:
UPDATE tblEmployee
SET
InOffice = CASE WHEN @NewStatus = 'InOffice' THEN -1 ELSE InOffice END,
OutOffice = CASE WHEN @NewStatus = 'OutOffice' THEN -1 ELSE OutOffice END,
Home = CASE WHEN @NewStatus = 'Home' THEN -1 ELSE Home END
WHERE EmpID = @EmpID
Note that the ELSE
will preserves the original value if the @NewStatus
condition isn't met.
Window -> Preferences -> JavaScript -> Validator (also per project settings possible)
or
Window -> Preferences -> Validation (disable validations and configure their settings)
This occurs typically when the stmt is reused butexpecting a different ResultSet, try creting a new stmt and executeQuery. It fixed it for me!
From Alex B The C++ standard does not specify the size of integral types in bytes, but it specifies minimum ranges they must be able to hold. You can infer minimum size in bits from the required range. You can infer minimum size in bytes from that and the value of the CHAR_BIT macro that defines the number of bits in a byte (in all but the most obscure platforms it's 8, and it can't be less than 8).
One additional constraint for char is that its size is always 1 byte, or CHAR_BIT bits (hence the name).
Minimum ranges required by the standard (page 22) are:
and Data Type Ranges on MSDN:
signed char: -127 to 127 (note, not -128 to 127; this accommodates 1's-complement platforms) unsigned char: 0 to 255 "plain" char: -127 to 127 or 0 to 255 (depends on default char signedness) signed short: -32767 to 32767 unsigned short: 0 to 65535 signed int: -32767 to 32767 unsigned int: 0 to 65535 signed long: -2147483647 to 2147483647 unsigned long: 0 to 4294967295 signed long long: -9223372036854775807 to 9223372036854775807 unsigned long long: 0 to 18446744073709551615 A C++ (or C) implementation can define the size of a type in bytes sizeof(type) to any value, as long as
the expression sizeof(type) * CHAR_BIT evaluates to the number of bits enough to contain required ranges, and the ordering of type is still valid (e.g. sizeof(int) <= sizeof(long)). The actual implementation-specific ranges can be found in header in C, or in C++ (or even better, templated std::numeric_limits in header).
For example, this is how you will find maximum range for int:
C:
#include <limits.h>
const int min_int = INT_MIN;
const int max_int = INT_MAX;
C++:
#include <limits>
const int min_int = std::numeric_limits<int>::min();
const int max_int = std::numeric_limits<int>::max();
This is correct, however, you were also right in saying that: char : 1 byte short : 2 bytes int : 4 bytes long : 4 bytes float : 4 bytes double : 8 bytes
Because 32 bit architectures are still the default and most used, and they have kept these standard sizes since the pre-32 bit days when memory was less available, and for backwards compatibility and standardization it remained the same. Even 64 bit systems tend to use these and have extentions/modifications. Please reference this for more information:
I found this query which helped me find my locked table and query causing the issue.
SELECT L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE resource_database_id = db_id()
ORDER BY L.request_session_id
Previous answers cover about ASCII character
at a certain index.
It is a little bit troublesome to get a Unicode character
at a certain index in Python 2.
E.g., with s = '????????'
which is <type 'str'>
,
__getitem__
, e.g., s[i]
, does not lead you to where you desire. It will spit out semething like ?
. (Many Unicode characters are more than 1 byte but __getitem__
in Python 2 is incremented by 1 byte.)
In this Python 2 case, you can solve the problem by decoding:
s = '????????'
s = s.decode('utf-8')
for i in range(len(s)):
print s[i]
UPDATE user_account student
SET (student.student_education_facility_id) = (
SELECT teacher.education_facility_id
FROM user_account teacher
WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'
)
WHERE student.user_type = 'ROLE_STUDENT';
Simple example of escaping quotes in shell:
$ echo 'abc'\''abc'
abc'abc
$ echo "abc"\""abc"
abc"abc
It's done by finishing already opened one ('
), placing escaped one (\'
), then opening another one ('
). This syntax works for all commands. It's very similar approach to the 1st answer.
Apparently I don't have enough reputation points to comment on Dansalmo's answer, but it is a good one, though mis-named. His answer is actually a K-combinator.
int K( int a, int b ) {
return a;
}
The JLS is specific about argument evaluation when passing to methods/ctors/etc. (Was this not so in older specs?)
Granted, this is a functional idiom, but it is clear enough to those who recognize it. (If you don't understand code you find, don't mess with it!)
y = K(x, x=y); // swap x and y
The K-combinator is specifically designed for this kind of thing. AFAIK there's no reason it shouldn't pass a code review.
My $0.02.
The best way to hide the button is to filter it with it's data-icon attribute:
$('#dialog-id [data-icon="delete"]').hide();
Add this in your .htaccess file:
Options -Indexes
If it is not work for any reason, try this within your .htaccess file:
IndexIgnore *
Here is a sed solution:
sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt
followings programs will execute,"one number is multiple of another" in
#include<stdio.h>
int main
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0)
printf("this is multiple number");
else if (b%a==0);
printf("this is multiple number");
else
printf("this is not multiple number");
return 0;
}
Horizontal scrollbars in a HTML Select are not natively supported. However, here's a way to create the appearance of a horizontal scrollbar:
1. First create a css class
<style type="text/css">
.scrollable{
overflow: auto;
width: 70px; /* adjust this width depending to amount of text to display */
height: 80px; /* adjust height depending on number of options to display */
border: 1px silver solid;
}
.scrollable select{
border: none;
}
</style>
2. Wrap the SELECT inside a DIV - also, explicitly set the size to the number of options.
<div class="scrollable">
<select size="6" multiple="multiple">
<option value="1" selected>option 1 The Long Option</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5 Another Longer than the Long Option ;)</option>
<option value="6">option 6</option>
</select>
</div>
%02x
means print at least 2 digits, prepend it with 0
's if there's less. In your case it's 7 digits, so you get no extra 0
in front.
Also, %x
is for int, but you have a long. Try %08lx
instead.
Based on Ivan Laharnar with less code and simplier:
declare
lastSeq number;
begin
SELECT MAX(ID) + 1 INTO lastSeq FROM <TABLE_NAME>;
if lastSeq IS NULL then lastSeq := 1; end if;
execute immediate 'CREATE SEQUENCE <SEQUENCE_NAME> INCREMENT BY 1 START WITH ' || lastSeq || ' MAXVALUE 999999999 MINVALUE 1 NOCACHE';
end;
labelname.ForeColor = Color.Colorname;
Converting millis to datetime (UTC):
import datetime
time_in_millis = 1596542285000
dt = datetime.datetime.fromtimestamp(time_in_millis / 1000.0, tz=datetime.timezone.utc)
Converting datetime to string following the RFC3339 standard (used by Open API specification):
from rfc3339 import rfc3339
converted_to_str = rfc3339(dt, utc=True, use_system_timezone=False)
# 2020-08-04T11:58:05Z
you can use
<a href="\\computername\folder">Open folder</a>
in Internet Explorer
Just use android:focusableInTouchMode="false"
on your webView.
var elem = document.getElementById("myvideo");
function openFullscreen() {
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) { /* Firefox */
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) { /* IE/Edge */
elem.msRequestFullscreen();
}
}
//Internet Explorer 10 and earlier does not support the msRequestFullscreen() method.
16kb is about right; if you're using gigabit ethernet, each packet could be 9kb in size.
You can't directly instantiate an abstract class, but you can create an anonymous class when there is no concrete class:
public class AbstractTest {
public static void main(final String... args) {
final Printer p = new Printer() {
void printSomethingOther() {
System.out.println("other");
}
@Override
public void print() {
super.print();
System.out.println("world");
printSomethingOther(); // works fine
}
};
p.print();
//p.printSomethingOther(); // does not work
}
}
abstract class Printer {
public void print() {
System.out.println("hello");
}
}
This works with interfaces, too.
You can do like this :
webelement time=driver.findElement(By.id("input_name")).getAttribute("value");
this will give you the time displaying on the webpage.
df.shape
, where df
is your DataFrame.
Memory management in Linux is a bit tricky to understand, and I can't say I fully understand it yet, but I'll try to share a little bit of my experience and knowledge.
Short answer to your question: Yes there are other stuff included than whats in the list.
What's being shown in your list is applications run in userspace. The kernel uses memory for itself and modules, on top of that it also has a lower limit of free memory that you can't go under. When you've reached that level it will try to free up resources, and when it can't do that anymore, you end up with an OOM problem.
From the last line of your list you can read that the kernel reports a total-vm usage of: 1498536kB (1,5GB), where the total-vm includes both your physical RAM and swap space. You stated you don't have any swap but the kernel seems to think otherwise since your swap space is reported to be full (Total swap = 524284kB, Free swap = 0kB) and it reports a total vmem size of 1,5GB.
Another thing that can complicate things further is memory fragmentation. You can hit the OOM killer when the kernel tries to allocate lets say 4096kB of continous memory, but there are no free ones availible.
Now that alone probably won't help you solve the actual problem. I don't know if it's normal for your program to require that amount of memory, but I would recommend to try a static code analyzer like cppcheck to check for memory leaks or file descriptor leaks. You could also try to run it through Valgrind to get a bit more information out about memory usage.
Use AppContext. Make sure you create a bean in your context file.
private final static Foo foo = AppContext.getApplicationContext().getBean(Foo.class);
public static void randomMethod() {
foo.doStuff();
}
It's creating a size 0
bitfield if the condition is false, but a size -1
(-!!1
) bitfield if the condition is true/non-zero. In the former case, there is no error and the struct is initialized with an int member. In the latter case, there is a compile error (and no such thing as a size -1
bitfield is created, of course).
JavaScript is a client-side language and your MySQL database is going to be running on a server.
So you have to rename your file to index.php
for example (.php is important) so you can use php code for that. It is not very difficult, but not directly possible with html.
(Somehow you can tell your server to let the html files behave like php files, but this is not the best solution.)
So after you renamed your file, go to the very top, before <html>
or <!DOCTYPE html>
and type:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
/*Creating variables*/
$name = $_POST["name"];
$address = $_POST["address"];
$age = $_POST["age"];
$dbhost = "localhost"; /*most of the time it's localhost*/
$username = "yourusername";
$password = "yourpassword";
$dbname = "mydatabase";
$mysql = mysqli_connect($dbhost, $username, $password, $dbname); //It connects
$query = "INSERT INTO yourtable (name,address,age) VALUES $name, $address, $age";
mysqli_query($mysql, $query);
}
?>
<!DOCTYPE html>
<html>
<head>.......
....
<form method="post">
<input name="name" type="text"/>
<input name="address" type="text"/>
<input name="age" type="text"/>
</form>
....
You just need to make sure you have the rights to push to the remote repository and do
git push origin master
or simply
git push
When you are in the Command, click Create to create a new parameter; call it project_name
. Once you've created it, double click its name to add it to the command's text. You query should resemble:
SELECT Projecttname, ReleaseDate, TaskName
FROM DB_Table
WHERE Project_Name LIKE {?project_name} + '*'
AND ReleaseDate >= getdate() --assumes sql server
If desired, link the main report to the subreport on this ({?project_name}
) field. If you don't establish a link between the main and subreport, CR will prompt you for the subreport's parameter.
In versions prior to 2008, a command's parameter was only allowed to be a scalar value.
Quick example using company1
from your question, with python3.
import pickle
# Save the file
pickle.dump(company1, file = open("company1.pickle", "wb"))
# Reload the file
company1_reloaded = pickle.load(open("company1.pickle", "rb"))
However, as this answer noted, pickle often fails. So you should really use dill
.
import dill
# Save the file
dill.dump(company1, file = open("company1.pickle", "wb"))
# Reload the file
company1_reloaded = dill.load(open("company1.pickle", "rb"))
Use:
System.out.println("Current date in Date Format: " + sdf.format(date));
As Wrikken suggested, it's a valid request. It's also quite common when the client is requesting media or resuming a download.
A client will often test to see if the server handles ranged requests other than just looking for an Accept-Ranges
response. Chrome always sends a Range: bytes=0-
with its first GET request for a video, so it's something you can't dismiss.
Whenever a client includes Range:
in its request, even if it's malformed, it's expecting a partial content (206) response. When you seek forward during HTML5 video playback, the browser only requests the starting point. For example:
Range: bytes=3744-
So, in order for the client to play video properly, your server must be able to handle these incomplete range requests.
You can handle the type of 'range' you specified in your question in two ways:
First, You could reply with the requested starting point given in the response, then the total length of the file minus one (the requested byte range is zero-indexed). For example:
Request:
GET /BigBuckBunny_320x180.mp4
Range: bytes=100-
Response:
206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/64656927
Second, you could reply with the starting point given in the request and an open-ended file length (size). This is for webcasts or other media where the total length is unknown. For example:
Request:
GET /BigBuckBunny_320x180.mp4
Range: bytes=100-
Response:
206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/*
Tips:
You must always respond with the content length included with the range. If the range is complete, with start to end, then the content length is simply the difference:
Request: Range: bytes=500-1000
Response: Content-Range: bytes 500-1000/123456
Remember that the range is zero-indexed, so Range: bytes=0-999
is actually requesting 1000 bytes, not 999, so respond with something like:
Content-Length: 1000
Content-Range: bytes 0-999/123456
Or:
Content-Length: 1000
Content-Range: bytes 0-999/*
But, avoid the latter method if possible because some media players try to figure out the duration from the file size. If your request is for media content, which is my hunch, then you should include its duration in the response. This is done with the following format:
X-Content-Duration: 63.23
This must be a floating point. Unlike Content-Length
, this value doesn't have to be accurate. It's used to help the player seek around the video. If you are streaming a webcast and only have a general idea of how long it will be, it's better to include your estimated duration rather than ignore it altogether. So, for a two-hour webcast, you could include something like:
X-Content-Duration: 7200.00
With some media types, such as webm, you must also include the content-type, such as:
Content-Type: video/webm
All of these are necessary for the media to play properly, especially in HTML5. If you don't give a duration, the player may try to figure out the duration (to allow for seeking) from its file size, but this won't be accurate. This is fine, and necessary for webcasts or live streaming, but not ideal for playback of video files. You can extract the duration using software like FFMPEG and save it in a database or even the filename.
X-Content-Duration
is being phased out in favor of Content-Duration
, so I'd include that too. A basic, response to a "0-" request would include at least the following:
HTTP/1.1 206 Partial Content
Date: Sun, 08 May 2013 06:37:54 GMT
Server: Apache/2.0.52 (Red Hat)
Accept-Ranges: bytes
Content-Length: 3980
Content-Range: bytes 0-3979/3980
Content-Type: video/webm
X-Content-Duration: 2054.53
Content-Duration: 2054.53
One more point: Chrome always starts its first video request with the following:
Range: bytes=0-
Some servers will send a regular 200 response as a reply, which it accepts (but with limited playback options), but try to send a 206 instead to show than your server handles ranges. RFC 2616 says it's acceptable to ignore range headers.
The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.
To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson
function and add contentType: 'application/json;charset=UTF-8'
to the jQuery ajax call parameters.
$.ajax({
url: 'test.php',
type: "POST",
dataType: 'json',
data: formToJson($("form")),
contentType: 'application/json;charset=UTF-8',
...
})
Like many others here, I had the same error. In my case it was because the execute permission was denied on a stored procedure it used. It was resolved when the user associated with the data source was given that permission.
First, create a folder named “menu” in the “res” folder.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/search"
android:icon="@android:drawable/ic_menu_search"
android:title="Search"/>
<item
android:id="@+id/add"
android:icon="@android:drawable/ic_menu_add"
android:title="Add"/>
<item
android:id="@+id/edit"
android:icon="@android:drawable/ic_menu_edit"
android:title="Edit">
<menu>
<item
android:id="@+id/share"
android:icon="@android:drawable/ic_menu_share"
android:title="Share"/>
</menu>
</item>
</menu>
Then, create your Activity Class:
public class PopupMenu1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_menu_1);
}
public void onPopupButtonClick(View button) {
PopupMenu popup = new PopupMenu(this, button);
popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(PopupMenu1.this,
"Clicked popup menu item " + item.getTitle(),
Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
}
Define the class before you use it:
class Something:
def out(self):
print("it works")
s = Something()
s.out()
You need to pass self
as the first argument to all instance methods.
Java doesn't natively allow building of an exe, that would defeat its purpose of being cross-platform.
AFAIK, these are your options:
Make a runnable JAR. If the system supports it and is configured appropriately, in a GUI, double clicking the JAR will launch the app. Another option would be to write a launcher shell script/batch file which will start your JAR with the appropriate parameters
There also executable wrappers - see How can I convert my Java program to an .exe file?
There is no real need to create a war to run it from Tomcat. You can follow these steps
Create a folder in webapps folder e.g. MyApp
Put your html and css in that folder and name the html file, which you want to be the starting page for your application, index.html
Start tomcat and point your browser to url "http://localhost:8080/MyApp". Your index.html page will pop up in the browser
TRY THIS
IF EXISTS
(
SELECT name FROM master.dbo.sysdatabases
WHERE name = N'New_Database'
)
BEGIN
SELECT 'Database Name already Exist' AS Message
END
ELSE
BEGIN
CREATE DATABASE [New_Database]
SELECT 'New Database is Created'
END
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
Another Simple way i found in Netbeans right click on your project>libraris click add jar/folder add your comm.jar and you done.
if you dont have comm.jar download it from >>> http://llk.media.mit.edu/projects/picdev/software/javaxcomm.zip
There are two related error messages that may tell you something is wrong with declarations and/or imports.
The first is the one you are referring to, which can be generated by NOT putting an #import in your .m (or .pch file) while declaring an @class in your .h.
The second you might see, if you had a method in your States class like:
- (void)logout:(NSTimer *)timer
after adding the #import is this:
No visible @interface for "States" declares the selector 'logout:'
If you see this, you need to check and see if you declared your "logout" method (in this instance) in the .h file of the class you're importing or forwarding.
So in your case, you would need a:
- (void)logout:(NSTimer *)timer;
in your States class's .h to make one or both of these related errors disappear.
This is another method I use because changing DropDownSyle
to DropDownList
makes it look 3D and sometimes its just plain ugly.
You can prevent user input by handling the KeyPress
event of the ComboBox like this.
private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
v-flex does not have a display flex! Inspect v-flex in your browser and you will find out it is just a simple block div.
So, you should override it with display: flex
in your HTML or CSS to make it work with justify-content.
You can loop through a hash map like this
<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);
%>
<c:forEach items="${itemList}" var="itemrow">
<input type="text" value="<c:out value='${itemrow.test}'/>"/>
</c:forEach>
For more JSTL functionality look here
you can use like this
SELECT Convert(varchar(10), GETDATE(),120)
<div class="parent" style="height:500px;">
<div class="child-left floatLeft" style="height:100%">
</div>
<div class="child-right floatLeft" style="height:100%">
</div>
</div>
I used inline style just to give idea.
If you use docker there is a chance you get error because of OpenSSL default security level.
You need lower seclevel in /etc/ssl/openssl.cnf
from DEFAULT@SECLEVEL=2
to DEFAULT@SECLEVEL=1
Or just add into Dockerfile
RUN sed -i "s|DEFAULT@SECLEVEL=2|DEFAULT@SECLEVEL=1|g" /etc/ssl/openssl.cnf
Source: https://github.com/dotnet/runtime/issues/30667#issuecomment-566482876
After that change I can run SoapClient without any additional options
You can verify it by run on container
curl -A 'cURL User Agent' -4 https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl
var d1=new Date(2011,0,1); // jan,1 2011
var d2=new Date(); // now
var diff=d2-d1,sign=diff<0?-1:1,milliseconds,seconds,minutes,hours,days;
diff/=sign; // or diff=Math.abs(diff);
diff=(diff-(milliseconds=diff%1000))/1000;
diff=(diff-(seconds=diff%60))/60;
diff=(diff-(minutes=diff%60))/60;
days=(diff-(hours=diff%24))/24;
console.info(sign===1?"Elapsed: ":"Remains: ",
days+" days, ",
hours+" hours, ",
minutes+" minutes, ",
seconds+" seconds, ",
milliseconds+" milliseconds.");
$('.select_continent').click(function () {
alert($(this).attr('value'));
});
to work on a two section of a one long file simply use shortcut ( Ctrl + \ ) or click on split editor window while you are on selected Tab. the icon is on top-right of the VS Code.
Here are some easy way to get you up and running with the XlsxWriter module.The first step is to install the XlsxWriter module.The pip installer is the preferred method for installing Python modules from PyPI, the Python Package Index:
sudo pip install xlsxwriter
Note
Windows users can omit sudo at the start of the command.
The method you want is BigInteger#valueOf(long val).
E.g.,
BigInteger bi = BigInteger.valueOf(myInteger.intValue());
Making a String first is unnecessary and undesired.
Here is a better way to loop over files as it handles spaces and newlines in file names:
#!/bin/bash
find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
echo "$line"
ls -l "$line"
done
I am using Visual Studio 2017 15.4.0 version. Especially when i started use lightweight solution option, this offline thing happened to me. I tried to above solutions which are:
Then from File -> Source Control -> Advanced -> Change Source Control. I saw my files. I select them and then chose bind option. That worked for me.
sounds like you want something like:
select PropertyID, SUM(Amount)
from MyTable
Where EndDate is null
Group by PropertyID
You can use string.Compare
lst.Where(x => string.Compare(x,"valueToCompare",StringComparison.InvariantCultureIgnoreCase)==0);
if you just want to check contains then use "Any"
lst.Any(x => string.Compare(x,"valueToCompare",StringComparison.InvariantCultureIgnoreCase)==0)
I would recommend 422. It's not part of the main HTTP spec, but it is defined by a public standard (WebDAV) and it should be treated by browsers the same as any other 4xx status code.
From RFC 4918:
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Or, you can use a control
class instead of their types:
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int RowIndex = row.RowIndex;
I smell homework, so probably an ArrayList won't be allowed (?)
Instead of looking for a way to "shift indexes", maybe just build a new array:
int[] b = new int[a.length +1];
Then
//edit: copy values of course, not indexes
Try this script.
http://www.biterscripting.com/SS_URLs.html
When I use it with this url,
script SS_URLs.txt URL("http://stackoverflow.com/questions/56107/what-is-the-best-way-to-parse-html-in-c")
It shows me all the links on the page for this thread.
http://sstatic.net/so/all.css
http://sstatic.net/so/favicon.ico
http://sstatic.net/so/apple-touch-icon.png
.
.
.
You can modify that script to check for images, variables, whatever.
I installed HandyCache, in them install link on my general proxy.
In IE set proxy 127.0.0.1.
In Eclipse, Window > Preferences > General > Network Connections, set Active Provider = Native.
This can be done in in 3 lines of code:
// grab the window frame and adjust it for orientation
UIView *rootView = [[[UIApplication sharedApplication] keyWindow]
rootViewController].view;
CGRect originalFrame = [[UIScreen mainScreen] bounds];
CGRect adjustedFrame = [rootView convertRect:originalFrame fromView:nil];
simply multiplying by -1 works in both ways ...
>>> -10 * -1
10
>>> 10 * -1
-10
Just for the reference it should be noted that getBoundingClientRect()
can work in certain cases.
For example, a simple check that the element is hidden using display: none
could look somewhat like this:
var box = element.getBoundingClientRect();
var visible = box.width && box.height;
This is also handy because it also covers zero-width, zero-height and position: fixed
cases. However, it shall not report elements hidden with opacity: 0
or visibility: hidden
(but neither would offsetParent
).
Checkbox
You can create your own CheckBox control extending UIButton with Swift:
import UIKit
class CheckBox: UIButton {
// Images
let checkedImage = UIImage(named: "ic_check_box")! as UIImage
let uncheckedImage = UIImage(named: "ic_check_box_outline_blank")! as UIImage
// Bool property
var isChecked: Bool = false {
didSet {
if isChecked == true {
self.setImage(checkedImage, for: UIControl.State.normal)
} else {
self.setImage(uncheckedImage, for: UIControl.State.normal)
}
}
}
override func awakeFromNib() {
self.addTarget(self, action:#selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
self.isChecked = false
}
@objc func buttonClicked(sender: UIButton) {
if sender == self {
isChecked = !isChecked
}
}
}
And then add it to your views with Interface Builder:
Radio Buttons
Radio Buttons can be solved in a similar way.
For example, the classic gender selection Woman - Man:
import UIKit
class RadioButton: UIButton {
var alternateButton:Array<RadioButton>?
override func awakeFromNib() {
self.layer.cornerRadius = 5
self.layer.borderWidth = 2.0
self.layer.masksToBounds = true
}
func unselectAlternateButtons() {
if alternateButton != nil {
self.isSelected = true
for aButton:RadioButton in alternateButton! {
aButton.isSelected = false
}
} else {
toggleButton()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
unselectAlternateButtons()
super.touchesBegan(touches, with: event)
}
func toggleButton() {
self.isSelected = !isSelected
}
override var isSelected: Bool {
didSet {
if isSelected {
self.layer.borderColor = Color.turquoise.cgColor
} else {
self.layer.borderColor = Color.grey_99.cgColor
}
}
}
}
You can init your radio buttons like this:
override func awakeFromNib() {
self.view.layoutIfNeeded()
womanRadioButton.selected = true
manRadioButton.selected = false
}
override func viewDidLoad() {
womanRadioButton?.alternateButton = [manRadioButton!]
manRadioButton?.alternateButton = [womanRadioButton!]
}
Hope it helps.
The web site likely uses cookies to store your session information. When you run
curl --user user:pass https://xyz.com/a #works ok
curl https://xyz.com/b #doesn't work
curl
is run twice, in two separate sessions. Thus when the second command runs, the cookies set by the 1st command are not available; it's just as if you logged in to page a
in one browser session, and tried to access page b
in a different one.
What you need to do is save the cookies created by the first command:
curl --user user:pass --cookie-jar ./somefile https://xyz.com/a
and then read them back in when running the second:
curl --cookie ./somefile https://xyz.com/b
Alternatively you can try downloading both files in the same command, which I think will use the same cookies.
I had a similar issue with Datagrip and none of these solutions worked.
Once I restarted the Datagrip Client it was no longer an issue and I could drop tables again.
While Parallels is technically a VM it is capable of running games in high resolution at a high frame rate. If you run Parallels in Coherence mode it completely integrates Windows 7 into OS X and .Net framework is fully supported. So yes you can install Visual Studio on your Mac however the Apps you created would only run of windows computers unless they were web based.
I found the OpenSSL answer given above didn't work for me, but the following did, working with a CRT file sourced from windows.
openssl x509 -inform DER -in yourdownloaded.crt -out outcert.pem -text
It is very simple: Use the command:
docker-compose restart worker
You can set the time to wait for stop before killing the container (in seconds)
docker-compose restart -t 30 worker
Note that this will restart the container but without rebuilding it. If you want to apply your changes and then restart, take a look at the other answers.
private void SaveFileStream(String path, Stream stream)
{
var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
stream.CopyTo(fileStream);
fileStream.Dispose();
}
as a beginner, I just coded this:
L = [15, 18, 2, 36, 12, 78, 5, 6, 9]
total = 0
def average(numbers):
total = sum(numbers)
total = float(total)
return total / len(numbers)
print average(L)
I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.
Code with Excepion
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
After Fixes:
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[102400];
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
In the html form, you need to supply additional viewstate variable and disable ViewState in a server page. This requires some control on both sides , though.
Form HTML:
<html><body> <form id='postForm' action='WebForm.aspx' method='POST'>
<input type='text' name='postData' value='base-64-encoded-value' />
<input type='hidden' name='__VIEWSTATE' value='' /> <!-- still need __VIEWSTATE, even empty one -->
</form>
</body></html>
Note empty __VIEWSTATE.
WebForm.aspx:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="WebForm.aspx.cs" Inherits="WebForm"
EnableEventValidation="False" EnableViewState="false" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="postForm" runat="server">
<asp:TextBox ID="postData" runat="server"></asp:TextBox>
<div>
</div>
</form>
</body>
</html>
Note EnableEventValidation="False", EnableViewState="false"
to prevent validation error for empty view state.
Code Behind/Inherits values are not precise.
WebForm.cs:
public partial class WebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string value = Encoding.Unicode.GetString(Convert.FromBase64String(this.postData.Text));
}
}
Based on the same basic idea as in @Will Hartung's answer, here is my magic one-tag extensible template engine. It even includes documentation and an example :-)
WEB-INF/tags/block.tag:
<%--
The block tag implements a basic but useful extensible template system.
A base template consists of a block tag without a 'template' attribute.
The template body is specified in a standard jsp:body tag, which can
contain EL, JSTL tags, nested block tags and other custom tags, but
cannot contain scriptlets (scriptlets are allowed in the template file,
but only outside of the body and attribute tags). Templates can be
full-page templates, or smaller blocks of markup included within a page.
The template is customizable by referencing named attributes within
the body (via EL). Attribute values can then be set either as attributes
of the block tag element itself (convenient for short values), or by
using nested jsp:attribute elements (better for entire blocks of markup).
Rendering a template block or extending it in a child template is then
just a matter of invoking the block tag with the 'template' attribute set
to the desired template name, and overriding template-specific attributes
as necessary to customize it.
Attribute values set when rendering a tag override those set in the template
definition, which override those set in its parent template definition, etc.
The attributes that are set in the base template are thus effectively used
as defaults. Attributes that are not set anywhere are treated as empty.
Internally, attributes are passed from child to parent via request-scope
attributes, which are removed when rendering is complete.
Here's a contrived example:
====== WEB-INF/tags/block.tag (the template engine tag)
<the file you're looking at right now>
====== WEB-INF/templates/base.jsp (base template)
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:block>
<jsp:attribute name="title">Template Page</jsp:attribute>
<jsp:attribute name="style">
.footer { font-size: smaller; color: #aaa; }
.content { margin: 2em; color: #009; }
${moreStyle}
</jsp:attribute>
<jsp:attribute name="footer">
<div class="footer">
Powered by the block tag
</div>
</jsp:attribute>
<jsp:body>
<html>
<head>
<title>${title}</title>
<style>
${style}
</style>
</head>
<body>
<h1>${title}</h1>
<div class="content">
${content}
</div>
${footer}
</body>
</html>
</jsp:body>
</t:block>
====== WEB-INF/templates/history.jsp (child template)
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:block template="base" title="History Lesson">
<jsp:attribute name="content" trim="false">
<p>${shooter} shot first!</p>
</jsp:attribute>
</t:block>
====== history-1977.jsp (a page using child template)
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:block template="history" shooter="Han" />
====== history-1997.jsp (a page using child template)
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:block template="history" title="Revised History Lesson">
<jsp:attribute name="moreStyle">.revised { font-style: italic; }</jsp:attribute>
<jsp:attribute name="shooter"><span class="revised">Greedo</span></jsp:attribute>
</t:block>
--%>
<%@ tag trimDirectiveWhitespaces="true" %>
<%@ tag import="java.util.HashSet, java.util.Map, java.util.Map.Entry" %>
<%@ tag dynamic-attributes="dynattributes" %>
<%@ attribute name="template" %>
<%
// get template name (adding default .jsp extension if it does not contain
// any '.', and /WEB-INF/templates/ prefix if it does not start with a '/')
String template = (String)jspContext.getAttribute("template");
if (template != null) {
if (!template.contains("."))
template += ".jsp";
if (!template.startsWith("/"))
template = "/WEB-INF/templates/" + template;
}
// copy dynamic attributes into request scope so they can be accessed from included template page
// (child is processed before parent template, so only set previously undefined attributes)
Map<String, String> dynattributes = (Map<String, String>)jspContext.getAttribute("dynattributes");
HashSet<String> addedAttributes = new HashSet<String>();
for (Map.Entry<String, String> e : dynattributes.entrySet()) {
if (jspContext.getAttribute(e.getKey(), PageContext.REQUEST_SCOPE) == null) {
jspContext.setAttribute(e.getKey(), e.getValue(), PageContext.REQUEST_SCOPE);
addedAttributes.add(e.getKey());
}
}
%>
<% if (template == null) { // this is the base template itself, so render it %>
<jsp:doBody/>
<% } else { // this is a page using the template, so include the template instead %>
<jsp:include page="<%= template %>" />
<% } %>
<%
// clean up the added attributes to prevent side effect outside the current tag
for (String key : addedAttributes) {
jspContext.removeAttribute(key, PageContext.REQUEST_SCOPE);
}
%>
From the Gnuplot documentation. To draw a vertical line from the bottom to the top of the graph at x=3, use:
set arrow from 3, graph 0 to 3, graph 1 nohead
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
End if
The error indicates that the compiler thinks you want to do a bitwise OR
on a Boolean and a string. Which of course won't work.
# Spawn a child process:
(dosmth) & pid=$!
# in the background, sleep for 10 secs then kill that process
(sleep 10 && kill -9 $pid) &
or to get the exit codes as well:
# Spawn a child process:
(dosmth) & pid=$!
# in the background, sleep for 10 secs then kill that process
(sleep 10 && kill -9 $pid) & waiter=$!
# wait on our worker process and return the exitcode
exitcode=$(wait $pid && echo $?)
# kill the waiter subshell, if it still runs
kill -9 $waiter 2>/dev/null
# 0 if we killed the waiter, cause that means the process finished before the waiter
finished_gracefully=$?
str_replace(PHP_EOL, null, $str);
Example in Swift, picturing the foundry's explanation above and the Apple's documentation:
ViewController.swift
import UIKit
protocol ViewControllerProtocol {
func dismissViewController1AndPresentViewController2()
}
class ViewController: UIViewController, ViewControllerProtocol {
@IBAction func goToViewController1BtnPressed(sender: UIButton) {
let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
vc1.delegate = self
vc1.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
self.presentViewController(vc1, animated: true, completion: nil)
}
func dismissViewController1AndPresentViewController2() {
self.dismissViewControllerAnimated(false, completion: { () -> Void in
let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
self.presentViewController(vc2, animated: true, completion: nil)
})
}
}
ViewController1.swift
import UIKit
class ViewController1: UIViewController {
var delegate: protocol<ViewControllerProtocol>!
@IBAction func goToViewController2(sender: UIButton) {
self.delegate.dismissViewController1AndPresentViewController2()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
}
ViewController.swift
import UIKit
protocol ViewControllerProtocol {
func popViewController1AndPushViewController2()
}
class ViewController: UIViewController, ViewControllerProtocol {
@IBAction func goToViewController1BtnPressed(sender: UIButton) {
let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
vc1.delegate = self
self.navigationController?.pushViewController(vc1, animated: true)
}
func popViewController1AndPushViewController2() {
self.navigationController?.popViewControllerAnimated(false)
let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
self.navigationController?.pushViewController(vc2, animated: true)
}
}
ViewController1.swift
import UIKit
class ViewController1: UIViewController {
var delegate: protocol<ViewControllerProtocol>!
@IBAction func goToViewController2(sender: UIButton) {
self.delegate.popViewController1AndPushViewController2()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
}
UPDATE for v1.1:
Rather than giving q="search_string"
give it q="hashtag"
in URL encoded form to return results with HASHTAG ONLY. So your query would become:
GET https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames
%23
is URL encoded form of #
. Try the link out in your browser and it should work.
You can optimize the query by adding since_id
and max_id
parameters detailed here. Hope this helps !
Note: Search API is now a OAUTH authenticated call, so please include your access_tokens to the above call
Updated
Twitter Search doc link: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html
Another approach is to use the first_value
window function: http://sqlfiddle.com/#!12/7a145/14
SELECT DISTINCT
first_value("id") OVER (PARTITION BY "category" ORDER BY "date" DESC)
FROM Table1
ORDER BY 1;
... though I suspect hims056's suggestion will typically perform better where appropriate indexes are present.
A third solution is:
SELECT
id
FROM (
SELECT
id,
row_number() OVER (PARTITION BY "category" ORDER BY "date" DESC) AS rownum
FROM Table1
) x
WHERE rownum = 1;
Looking into the actual implementation of UrlBasedViewResolver and RedirectView the redirect will always be contextRelative if your redirect target starts with /. So also sending a //yahoo.com/path/to/resource wouldn't help to get a protocol relative redirect.
So to achieve what you are trying you could do something like:
@RequestMapping(method = RequestMethod.POST)
public String processForm(HttpServletRequest request, LoginForm loginForm,
BindingResult result, ModelMap model)
{
String redirectUrl = request.getScheme() + "://www.yahoo.com";
return "redirect:" + redirectUrl;
}
I might be late to the party but here is my simple solution and it works like a charm with every application I have:
try
{
//run the program again and close this one
Process.Start(Application.StartupPath + "\\blabla.exe");
//or you can use Application.ExecutablePath
//close this one
Process.GetCurrentProcess().Kill();
}
catch
{ }
This is a simple WORKAROUND (no solution):
You can install a mediation such as InMobi: https://developers.google.com/admob/android/mediation/inmobi
In this way, if for whatever reason admob is not showing you ads, you can still show them from other ad networks.
max-width is the width of the target display area, e.g. the browser; max-device-width is the width of the device's entire rendering area, i.e. the actual device screen.
• If you are using the max-device-width, when you change the size of the browser window on your desktop, the CSS style won't change to different media query setting;
• If you are using the max-width, when you change the size of the browser on your desktop, the CSS will change to different media query setting and you might be shown with the styling for mobiles, such as touch-friendly menus.
If you want to grow the array dynamically, you should use malloc() to dynamically allocate some fixed amount of memory, and then use realloc() whenever you run out. A common technique is to use an exponential growth function such that you allocate some small fixed amount and then make the array grow by duplicating the allocated amount.
Some example code would be:
size = 64; i = 0;
x = malloc(sizeof(words)*size); /* enough space for 64 words */
while (read_words()) {
if (++i > size) {
size *= 2;
x = realloc(sizeof(words) * size);
}
}
/* done with x */
free(x);
You use it like this:
SELECT age, name
FROM users
UNION
SELECT 25 AS age, 'Betty' AS name
Use UNION ALL
to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION
.
iOS includes built in support for base64 encoding and decoding. If you look at resolv.h
you should see the two functions b64_ntop
and b64_pton
. The Square SocketRocket library provides a reasonable example of how to use these functions from objective-c.
These functions are pretty well tested and reliable - unlike many of the implementations you may find in random internet postings.
Don't forget to link against libresolv.dylib
.
I implemented access using the following
class D(Enum):
x = 1
y = 2
def __str__(self):
return '%s' % self.value
now I can just do
print(D.x)
to get 1
as result.
You can also use self.name
in case you wanted to print x
instead of 1
.
import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions)
with open('data.csv', 'r') as f:
for rec in csv.DictReader(f):
for l, col in zip(data, cols):
l.append(float(rec[col]))
print data
# [[3.0, 3.0], [0.01, 0.01]]
This is one of the best way to do so:
<script>
$(window).on('beforeunload', function() {
$('body').hide();
$(window).scrollTop(0);
});
</script>
_x000D_
This is thrown when
... the peer was not able to identify itself (for example; no certificate, the particular cipher suite being used does not support authentication, or no peer authentication was established during SSL handshaking) this exception is thrown.
Probably the cause of this exception (where is the stacktrace) will show you why this exception is thrown. Most likely the default keystore shipped with Java does not contain (and trust) the root certificate of the TTP that is being used.
The answer is to retrieve the root certificate (e.g. from your browsers SSL connection), import it into the cacerts
file and trust it using keytool
which is shipped by the Java JDK. Otherwise you will have to assign another trust store programmatically.
For me works using &autoplay=1&mute=1
Use the RAISERROR
function:
RAISERROR( 'This message will show up right away...',0,1) WITH NOWAIT
You shouldn't completely replace all your prints with raiserror. If you have a loop or large cursor somewhere just do it once or twice per iteration or even just every several iterations.
Also: I first learned about RAISERROR at this link, which I now consider the definitive source on SQL Server Error handling and definitely worth a read:
http://www.sommarskog.se/error-handling-I.html
Always use new in C++. If you need a block of untyped memory, you can use operator new directly:
void *p = operator new(size);
...
operator delete(p);
In response to question edits here is how it works for Anonymous classes
final X parameter = ...; // the final is important
Thread t = new Thread(new Runnable() {
p = parameter;
public void run() {
...
};
t.start();
You have a class that extends Thread (or implements Runnable) and a constructor with the parameters you'd like to pass. Then, when you create the new thread, you have to pass in the arguments, and then start the thread, something like this:
Thread t = new MyThread(args...);
t.start();
Runnable is a much better solution than Thread BTW. So I'd prefer:
public class MyRunnable implements Runnable {
private X parameter;
public MyRunnable(X parameter) {
this.parameter = parameter;
}
public void run() {
}
}
Thread t = new Thread(new MyRunnable(parameter));
t.start();
This answer is basically the same as this similar question: How to pass parameters to a Thread object
You should work with padding on the inner container rather than with margin. Try this!
HTML
<div class="row info-panel">
<div class="col-md-4" id="server_1">
<div class="server-action-menu">
Server 1
</div>
</div>
</div>
CSS
.server-action-menu {
background-color: transparent;
background-image: linear-gradient(to bottom, rgba(30, 87, 153, 0.2) 0%, rgba(125, 185, 232, 0) 100%);
background-repeat: repeat;
border-radius:10px;
padding: 5px;
}
executeQuery()
returns a ResultSet
. I'm not as familiar with Java/MySQL, but to create indexes you probably want a executeUpdate()
.
The whole point of using Maps is direct access. If you know for sure that the value in a map will never be Groovy-false
, then you can do this:
def mymap = [name:"Gromit", likes:"cheese", id:1234]
def key = "likes"
if(mymap[key]) {
println mymap[key]
}
However, if the value could potentially be Groovy-false
, you should use:
if(mymap.containsKey(key)) {
println mymap[key]
}
The easiest solution, though, if you know the value isn't going to be Groovy-false
(or you can ignore that), and want a default value, is like this:
def value = mymap[key] ?: "default"
All three of these solutions are significantly faster than your examples, because they don't scan the entire map for keys. They take advantage of the HashMap
(or LinkedHashMap
) design that makes direct key access nearly instantaneous.
In my case LD_LIBRARY_PATH had /usr/lib64 first before /usr/local/lib64. (I was builing llvm 3.9).
The new gcc compiler that I installed to compile llvm 3.9 had libraries using newer GLIBCXX libraries under /usr/local/lib64 So I fixed LD_LIBRARY_PATH for the linker to see /usr/local/lib64 first.
That solved this problem.
doReturn( value1, value2, value3 ).when( method-call )
<div style="width: 200px; height: 150px; border: 1px solid black;position:relative">
<div style="width: 100%; height: 50px; border: 1px solid red;position:absolute;bottom:0">
</div>
</div>
For people looking to do if statements with multiple 'or' values.
<div ng-if="::(a || b || c || d || e || f)"><div>
When you use laravel modules, you may add the name's module:
@include('cimple::shared.posts_list')
Jay Gilford's answer will work, but I think really the easiest way is to just slap a display: none;
on a submit button in the form.
Here's the complete regexp to parse a URL.
(?:http://(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.
)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)
){3}))(?::(?:\d+))?)(?:/(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F
\d]{2}))|[;:@&=])*)(?:/(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{
2}))|[;:@&=])*))*)(?:\?(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{
2}))|[;:@&=])*))?)?)|(?:ftp://(?:(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?
:%[a-fA-F\d]{2}))|[;?&=])*)(?::(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-
fA-F\d]{2}))|[;?&=])*))?@)?(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-
)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?
:\d+)(?:\.(?:\d+)){3}))(?::(?:\d+))?))(?:/(?:(?:(?:(?:[a-zA-Z\d$\-_.+!
*'(),]|(?:%[a-fA-F\d]{2}))|[?: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\d\$\-_.!~*'
(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d\$\-_.!~*'(),
])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?)))?)|(?:/(?:(?:(?:(?:(?:[a-zA-Z\d
\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d\$\
-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?))|(?:(?:(?:(?:(?:[a-zA-
Z\d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d
\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?)))
Given its complexibility, I think you should go the urlparse way.
For completeness, here's the pseudo-BNF of the above regex (as a documentation):
; The generic form of a URL is: genericurl = scheme ":" schemepart ; Specific predefined schemes are defined here; new schemes ; may be registered with IANA url = httpurl | ftpurl | newsurl | nntpurl | telneturl | gopherurl | waisurl | mailtourl | fileurl | prosperourl | otherurl ; new schemes follow the general syntax otherurl = genericurl ; the scheme is in lower case; interpreters should use case-ignore scheme = 1*[ lowalpha | digit | "+" | "-" | "." ] schemepart = *xchar | ip-schemepart ; URL schemeparts for ip based protocols: ip-schemepart = "//" login [ "/" urlpath ] login = [ user [ ":" password ] "@" ] hostport hostport = host [ ":" port ] host = hostname | hostnumber hostname = *[ domainlabel "." ] toplabel domainlabel = alphadigit | alphadigit *[ alphadigit | "-" ] alphadigit toplabel = alpha | alpha *[ alphadigit | "-" ] alphadigit alphadigit = alpha | digit hostnumber = digits "." digits "." digits "." digits port = digits user = *[ uchar | ";" | "?" | "&" | "=" ] password = *[ uchar | ";" | "?" | "&" | "=" ] urlpath = *xchar ; depends on protocol see section 3.1 ; The predefined schemes: ; FTP (see also RFC959) ftpurl = "ftp://" login [ "/" fpath [ ";type=" ftptype ]] fpath = fsegment *[ "/" fsegment ] fsegment = *[ uchar | "?" | ":" | "@" | "&" | "=" ] ftptype = "A" | "I" | "D" | "a" | "i" | "d" ; FILE fileurl = "file://" [ host | "localhost" ] "/" fpath ; HTTP httpurl = "http://" hostport [ "/" hpath [ "?" search ]] hpath = hsegment *[ "/" hsegment ] hsegment = *[ uchar | ";" | ":" | "@" | "&" | "=" ] search = *[ uchar | ";" | ":" | "@" | "&" | "=" ] ; GOPHER (see also RFC1436) gopherurl = "gopher://" hostport [ / [ gtype [ selector [ "%09" search [ "%09" gopher+_string ] ] ] ] ] gtype = xchar selector = *xchar gopher+_string = *xchar ; MAILTO (see also RFC822) mailtourl = "mailto:" encoded822addr encoded822addr = 1*xchar ; further defined in RFC822 ; NEWS (see also RFC1036) newsurl = "news:" grouppart grouppart = "*" | group | article group = alpha *[ alpha | digit | "-" | "." | "+" | "_" ] article = 1*[ uchar | ";" | "/" | "?" | ":" | "&" | "=" ] "@" host ; NNTP (see also RFC977) nntpurl = "nntp://" hostport "/" group [ "/" digits ] ; TELNET telneturl = "telnet://" login [ "/" ] ; WAIS (see also RFC1625) waisurl = waisdatabase | waisindex | waisdoc waisdatabase = "wais://" hostport "/" database waisindex = "wais://" hostport "/" database "?" search waisdoc = "wais://" hostport "/" database "/" wtype "/" wpath database = *uchar wtype = *uchar wpath = *uchar ; PROSPERO prosperourl = "prospero://" hostport "/" ppath *[ fieldspec ] ppath = psegment *[ "/" psegment ] psegment = *[ uchar | "?" | ":" | "@" | "&" | "=" ] fieldspec = ";" fieldname "=" fieldvalue fieldname = *[ uchar | "?" | ":" | "@" | "&" ] fieldvalue = *[ uchar | "?" | ":" | "@" | "&" ] ; Miscellaneous definitions lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" hialpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" alpha = lowalpha | hialpha digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" safe = "$" | "-" | "_" | "." | "+" extra = "!" | "*" | "'" | "(" | ")" | "," national = "{" | "}" | "|" | "\" | "^" | "~" | "[" | "]" | "`" punctuation = "" | "#" | "%" | reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" hex = digit | "A" | "B" | "C" | "D" | "E" | "F" | "a" | "b" | "c" | "d" | "e" | "f" escape = "%" hex hex unreserved = alpha | digit | safe | extra uchar = unreserved | escape xchar = unreserved | reserved | escape digits = 1*digit
Perhaps you should not store data that way. It is a bad practice to ever store a comma delimited list in a field. IT is very inefficient for querying. This should be a related table.
Alternate Solution :
reduce(lambda x,y : filter(lambda z: z!=y,x) ,[2,3,5,8],[1,2,6,8])
You also can use
NSString *className = [[myObject class] description];
on any NSObject
You can rename a file using git
's mv
command:
$ git mv file_from file_to
Example:
$ git mv helo.txt hello.txt
$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# renamed: helo.txt -> hello.txt
#
$ git commit -m "renamed helo.txt to hello.txt"
[master 14c8c4f] renamed helo.txt to hello.txt
1 files changed, 0 insertions(+), 0 deletions(-)
rename helo.txt => hello.txt (100%)
You have 3 choices:
atoi
This is probably the fastest if you're using it in performance-critical code, but it does no error reporting. If the string does not begin with an integer, it will return 0. If the string contains junk after the integer, it will convert the initial part and ignore the rest. If the number is too big to fit in int
, the behaviour is unspecified.
sscanf
Some error reporting, and you have a lot of flexibility for what type to store (signed/unsigned versions of char/short/int/long/long long/size_t/ptrdiff_t/intmax_t
).
The return value is the number of conversions that succeed, so scanning for "%d"
will return 0 if the string does not begin with an integer. You can use "%d%n"
to store the index of the first character after the integer that's read in another variable, and thereby check to see if the entire string was converted or if there's junk afterwards. However, like atoi
, behaviour on integer overflow is unspecified.
strtol
and familyRobust error reporting, provided you set errno
to 0 before making the call. Return values are specified on overflow and errno
will be set. You can choose any number base from 2 to 36, or specify 0 as the base to auto-interpret leading 0x
and 0
as hex and octal, respectively. Choices of type to convert to are signed/unsigned versions of long/long long/intmax_t
.
If you need a smaller type you can always store the result in a temporary long
or unsigned long
variable and check for overflow yourself.
Since these functions take a pointer to pointer argument, you also get a pointer to the first character following the converted integer, for free, so you can tell if the entire string was an integer or parse subsequent data in the string if needed.
Personally, I would recommend the strtol
family for most purposes. If you're doing something quick-and-dirty, atoi might meet your needs.
As an aside, sometimes I find I need to parse numbers where leading whitespace, sign, etc. are not supposed to be accepted. In this case it's pretty damn easy to roll your own for loop, eg.,
for (x=0; (unsigned)*s-'0'<10; s++)
x=10*x+(*s-'0');
Or you can use (for robustness):
if (isdigit(*s))
x=strtol(s, &s, 10);
else /* error */
@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :
<h:inputHidden value="#{loginBean.loginStatus}"/>
and in your bean code:
public void setLoginStatus(String loginStatus) {
this.loginStatus = loginStatus;
}
public String getLoginStatus() {
// Do your stuff here.
return loginStatus;
}
I'm currently achieving the task, by using the following
#!/usr/bin/python
import boto3
s3=boto3.client('s3')
list=s3.list_objects(Bucket='bucket')['Contents']
for s3_key in list:
s3_object = s3_key['Key']
if not s3_object.endswith("/"):
s3.download_file('bucket', s3_object, s3_object)
else:
import os
if not os.path.exists(s3_object):
os.makedirs(s3_object)
Although, it does the job, I'm not sure its good to do this way. I'm leaving it here to help other users and further answers, with better manner of achieving this
In my case the function throwing error was async so I followed here:
await expectAsync(asyncFunction()).toBeRejected();
await expectAsync(asyncFunction()).toBeRejectedWithError(...);
In Crockford's JavaScript The Good Parts, there is a function to check if the given argument is an array:
var is_array = function (value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
He explains:
First, we ask if the value is truthy. We do this to reject null and other falsy values. Second, we ask if the typeof value is 'object'. This will be true for objects, arrays, and (weirdly) null. Third, we ask if the value has a length property that is a number. This will always be true for arrays, but usually not for objects. Fourth, we ask if the value contains a splice method. This again will be true for all arrays. Finally, we ask if the length property is enumerable (will length be produced by a for in loop?). That will be false for all arrays. This is the most reliable test for arrayness that I have found. It is unfortunate that it is so complicated.
I've got:
ssh user@host bash -c "echo mypass | sudo -S mycommand"
Works for me.
For the complete list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the getattr
built-in function. As the user can reimplement __getattr__
, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The dir
function returns the keys in the __dict__
attribute, i.e. all the attributes accessible if the __getattr__
method is not reimplemented.
For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the inspect
module determine the class methods, methods or functions.
Well we don't actually need inspect
here.
>>> func = lambda x, y: (x, y)
>>>
>>> func.__code__.co_argcount
2
>>> func.__code__.co_varnames
('x', 'y')
>>>
>>> def func2(x,y=3):
... print(func2.__code__.co_varnames)
... pass # Other things
...
>>> func2(3,3)
('x', 'y')
>>>
>>> func2.__defaults__
(3,)
For Python 2.5 and older, use func_code
instead of __code__
, and func_defaults
instead of __defaults__
.
I recently had the same problem and used the solution provided by Harry Joy. That solution only works with with zero-based enumaration though. I also wouldn't consider it save as it doesn't deal with indexes that are out of range.
The solution I ended up using might not be as simple but it's completely save and won't hurt the performance of your code even with big enums:
public enum Example {
UNKNOWN(0, "unknown"), ENUM1(1, "enum1"), ENUM2(2, "enum2"), ENUM3(3, "enum3");
private static HashMap<Integer, Example> enumById = new HashMap<>();
static {
Arrays.stream(values()).forEach(e -> enumById.put(e.getId(), e));
}
public static Example getById(int id) {
return enumById.getOrDefault(id, UNKNOWN);
}
private int id;
private String description;
private Example(int id, String description) {
this.id = id;
this.description= description;
}
public String getDescription() {
return description;
}
public int getId() {
return id;
}
}
If you are sure that you will never be out of range with your index and you don't want to use UNKNOWN
like I did above you can of course also do:
public static Example getById(int id) {
return enumById.get(id);
}
Google just released the NDK which allows exactly that.
It can be found here: http://developer.android.com/sdk/ndk/1.5_r1/index.html
I am using React Bootstrap, which is based on Bootstrap 4. The approach is to use Sass, simliar to Nelson Rothermel's answer above.
The idea is to override Bootstraps Sass variable for font family in your custom Sass file. If you are using Google Fonts, then make sure you import it at the top of your custom Sass file.
For example, my custom Sass file is called custom.sass
with the following content:
@import url('https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap');
$font-family-sans-serif: "Dancing Script", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji" !default;
I simply added the font I want to the front of the default values, which can be found in ..\node_modules\boostrap\dist\scss\_variables.scss
.
How the custom.scss
file is used is shown here, which is obtained from here, which is obtained from here...
Because the React app is created by the Create-React-App utility, there's no need to go through all the crufts like Gulp; I just saved the files and React will compile the Sass for me automagically behind the scene.
Adding one more answer as the solution is from different contexts:
I connected to MongoDB Atlas and whitelisted my machine's IP by following the below steps:
The @Qualifier
annotation is used to resolve the autowiring conflict, when there are multiple beans of same type.
The @Qualifier
annotation can be used on any class annotated with @Component
or on methods annotated with @Bean
. This annotation can also be applied on constructor arguments or method parameters.
Ex:-
public interface Vehicle {
public void start();
public void stop();
}
There are two beans, Car and Bike implements Vehicle interface
@Component(value="car")
public class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started");
}
@Override
public void stop() {
System.out.println("Car stopped");
}
}
@Component(value="bike")
public class Bike implements Vehicle {
@Override
public void start() {
System.out.println("Bike started");
}
@Override
public void stop() {
System.out.println("Bike stopped");
}
}
Injecting Bike bean in VehicleService using @Autowired
with @Qualifier
annotation. If you didn't use @Qualifier
, it will throw NoUniqueBeanDefinitionException.
@Component
public class VehicleService {
@Autowired
@Qualifier("bike")
private Vehicle vehicle;
public void service() {
vehicle.start();
vehicle.stop();
}
}
Reference:- @Qualifier annotation example
<ul>
<li>this is my text</li>
<li>this is my text</li>
<li>this is my text</li>
<li>this is my text</li>
<li>this is my text</li>
</ul>
you can use this simple css style
ul {
list-style-type: '\2713';
}
If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.
<input id="addButton" type="button" value="Add" />
<script type="text/javascript" language="javascript">
$(document).ready(function()
{
$('#addButton').click(function()
{
showDialog('#addPerson');
});
});
</script>
If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:
<asp:Button ID="buttonAdd" runat="server" Text="Add" />
<script type="text/javascript" language="javascript">
$(document).ready(function()
{
$('#<%= buttonAdd.ClientID %>').click(function(e)
{
showDialog('#addPerson');
if(/*Some Condition Is Not Met*/)
return false;
});
});
</script>
Order of magnitude: zero.
In other words, you won't see your throughput cut in half, or anything like it, when you add TLS. Answers to the "duplicate" question focus heavily on application performance, and how that compares to SSL overhead. This question specifically excludes application processing, and seeks to compare non-SSL to SSL only. While it makes sense to take a global view of performance when optimizing, that is not what this question is asking.
The main overhead of SSL is the handshake. That's where the expensive asymmetric cryptography happens. After negotiation, relatively efficient symmetric ciphers are used. That's why it can be very helpful to enable SSL sessions for your HTTPS service, where many connections are made. For a long-lived connection, this "end-effect" isn't as significant, and sessions aren't as useful.
Here's an interesting anecdote. When Google switched Gmail to use HTTPS, no additional resources were required; no network hardware, no new hosts. It only increased CPU load by about 1%.
Here is one that works with Twitter Bootstrap.
Here is syntax for showing hours and minutes for a field coming out of a SELECT statement. In this example, the SQL field is named "UpdatedOnAt" and is a DateTime. Tested with MS SQL 2014.
SELECT Format(UpdatedOnAt ,'hh:mm') as UpdatedOnAt from MyTable
I like the format that shows the day of the week as a 3-letter abbreviation, and includes the seconds:
SELECT Format(UpdatedOnAt ,'ddd hh:mm:ss') as UpdatedOnAt from MyTable
The "as UpdatedOnAt" suffix is optional. It gives you a column heading equal tot he field you were selecting to begin with.
Try adding this to your CSS
html, body {
max-width: 100%;
overflow-x: hidden;
}
I would use a value that gets set when more button get pushed closed the first dialog and then have the original form test the value and then display the the there dialog.
For the Ex
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool DrawText = false;
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
if (f2.ShowMoreActions)
{
Form3 f3 = new Form3();
f3.ShowDialog();
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public bool ShowMoreActions = false;
private void button1_Click(object sender, EventArgs e)
{
ShowMoreActions = true;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
Or you can always map
over an iterator, without the need to build an intermediate list:
>>> _ = map(sys.stdout.write, (x for x in string.letters if x in (y for y in "BigMan on campus")))
acgimnopsuBM
The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
index.php
<html>
<body>
<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
site2.php
<html>
<body>
Hello <?php echo $_POST["name"]; ?>!<br>
Your mail is <?php echo $_POST["mail"]; ?>.
</body>
</html>
output
Hello "name" !
Your email is "[email protected]" .
You need to make it a generic method, like this:
public static T ConfigSetting<T>(string settingName)
{
return /* code to convert the setting to T... */
}
But the caller will have to specify the type they expect. You could then potentially use Convert.ChangeType
, assuming that all the relevant types are supported:
public static T ConfigSetting<T>(string settingName)
{
object value = ConfigurationManager.AppSettings[settingName];
return (T) Convert.ChangeType(value, typeof(T));
}
I'm not entirely convinced that all this is a good idea, mind you...
Reference the System.Web
dll in your model and use System.Web.Caching.Cache
public string[] GetNames()
{
string[] names = Cache["names"] as string[];
if(names == null) //not in cache
{
names = DB.GetNames();
Cache["names"] = names;
}
return names;
}
A bit simplified but I guess that would work. This is not MVC specific and I have always used this method for caching data.
This is the code that I have used.
Container(
width: 200.0,
height: 200.0,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('Network_Image_Link')),
color: Colors.blue,
borderRadius: BorderRadius.all(Radius.circular(25.0)),
),
),
Thank you!!!
Use CTRL+D
at each line and it will find the matching words and select them then you can use multiple cursors.
You can also use find to find all the occurrences and then it would be multiple cursors too.
A simple way is to put tabindex="-1" in the field(s) you don't want to be tabbed to. Eg
<input type="text" tabindex="-1" name="f1">
// 24-hour time to 12-hour time
$time_in_12_hour_format = date("g:i a", strtotime("13:30"));
// 12-hour time to 24-hour time
$time_in_24_hour_format = date("H:i", strtotime("1:30 PM"));
dplyr >= 1.0.0
In newer versions of dplyr
you can use rowwise()
along with c_across
to perform row-wise aggregation for functions that do not have specific row-wise variants, but if the row-wise variant exists it should be faster.
Since rowwise()
is just a special form of grouping and changes the way verbs work you'll likely want to pipe it to ungroup()
after doing your row-wise operation.
To select a range of rows:
df %>%
dplyr::rowwise() %>%
dplyr::mutate(sumrange = sum(dplyr::c_across(x1:x5), na.rm = T))
# %>% dplyr::ungroup() # you'll likely want to ungroup after using rowwise()
To select rows by type:
df %>%
dplyr::rowwise() %>%
dplyr::mutate(sumnumeric = sum(c_across(where(is.numeric)), na.rm = T))
# %>% dplyr::ungroup() # you'll likely want to ungroup after using rowwise()
In your specific case a row-wise variant exists so you can do the following (note the use of across
instead):
df %>%
dplyr::mutate(sumrow = rowSums(dplyr::across(x1:x5), na.rm = T))
For more information see the page on rowwise.
The finally block is always run after the try block ends, whether try ends normally or abnormally due to an exception, er, throwable.
If an exception is thrown by any of the code within the try block, then the current method simply re-throws (or continues to throw) the same exception (after running the finally block).
If the finally block throws an exception / error / throwable, and there is already a pending throwable, it gets ugly. Quite frankly, I forget exactly what happens (so much for my certification years ago). I think both throwables get linked together, but there is some special voodoo you have to do (i.e. - a method call I would have to look up) to get the original problem before the "finally" barfed, er, threw up.
Incidentally, try/finally is a pretty common thing to do for resource management, since java has no destructors.
E.g. -
r = new LeakyThing();
try { useResource( r); }
finally { r.release(); } // close, destroy, etc
"Finally", one more tip: if you do bother to put in a catch, either catch specific (expected) throwable subclasses, or just catch "Throwable", not "Exception", for a general catch-all error trap. Too many problems, such as reflection goofs, throw "Errors", rather than "Exceptions", and those will slip right by any "catch all" coded as:
catch ( Exception e) ... // doesn't really catch *all*, eh?
do this instead:
catch ( Throwable t) ...
A regular pipe can only connect two related processes. It is created by a process and will vanish when the last process closes it.
A named pipe, also called a FIFO for its behavior, can be used to connect two unrelated processes and exists independently of the processes; meaning it can exist even if no one is using it. A FIFO is created using the mkfifo()
library function.
writer.c
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
/* create the FIFO (named pipe) */
mkfifo(myfifo, 0666);
/* write "Hi" to the FIFO */
fd = open(myfifo, O_WRONLY);
write(fd, "Hi", sizeof("Hi"));
close(fd);
/* remove the FIFO */
unlink(myfifo);
return 0;
}
reader.c
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_BUF 1024
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
char buf[MAX_BUF];
/* open, read, and display the message from the FIFO */
fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX_BUF);
printf("Received: %s\n", buf);
close(fd);
return 0;
}
Note: Error checking was omitted from the above code for simplicity.
Maybe good ol' cfront will do?
This is how it worked for me
- hosts: main
vars:
# created with:
# python -c "from passlib.hash import sha512_crypt; print sha512_crypt.encrypt('<password>')"
# above command requires the PassLib library: sudo pip install passlib
- password: '$6$rounds=100000$H/83rErWaObIruDw$DEX.DgAuZuuF.wOyCjGHnVqIetVt3qRDnTUvLJHBFKdYr29uVYbfXJeHg.IacaEQ08WaHo9xCsJQgfgZjqGZI0'
tasks:
- user: name=spree password={{password}} groups=sudo,www-data shell=/bin/bash append=yes
sudo: yes
I tried this and now working
Configuration for c_cpp_properties.json
{
"configurations": [
{
"name": "Win32",
"compilerPath": "C:/MinGW/bin/g++.exe",
"includePath": [
"C:/MinGW/lib/gcc/mingw32/9.2.0/include/c++"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "windows-gcc-x64"
}
],
"version": 4
}
task.json configuration
File
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++.exe build active file",
"command": "C:\\MinGW\\bin\\g++.exe",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "C:\\MinGW\\bin"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "compiler: C:\\MinGW\\bin\\g++.exe"
}
]}
You can either
fig, ax = plt.subplots() #create figure and axes
candlestick(ax, quotes, ...)
or
candlestick(plt.gca(), quotes) #get the axis when calling the function
The first gives you more flexibility. The second is much easier if candlestick is the only thing you want to plot
I would like to give one additional answer, while the other ones will suffice in most cases.
I wanted to write a string over multiple lines, but its contents needed to be single-line.
sql=" \
SELECT c1, c2 \
from Table1, ${TABLE2} \
where ... \
"
I am sorry if this if a bit off-topic (I did not need this for SQL). However, this post comes up among the first results when searching for multi-line shell variables and an additional answer seemed appropriate.
In Xcode 5.1
Enable Done Button
Hide Keyboard when Done is pressed
Add this method to your ViewController
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
Cleaning the Project using Build in Menu Bar work for many error scenarios in Android Studio and so it does in this case.
INSERT INTO destination_table (
Field_1,
Field_2,
Field_3)
SELECT Field_1,
Field_2,
Field_3
FROM source_table;
BUT this is a BAD MYSQL
Do this instead:
drop the destination table: DROP DESTINATION_TABLE;
CREATE TABLE DESTINATION_TABLE AS (SELECT * FROM SOURCE_TABLE);
you have to add parameter also @zip
SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
conn.Open();
SqlCommand command = new SqlCommand("Select id from [table1] where name=@zip", conn);
//
// Add new SqlParameter to the command.
//
command.Parameters.AddWithValue("@zip","india");
int result = (Int32) (command.ExecuteScalar());
using (SqlDataReader reader = command.ExecuteReader())
{
// iterate your results here
Console.WriteLine(String.Format("{0}",reader["id"]));
}
conn.Close();
If you would like to support all versions: Try this:
myTextView.setBackgroundColor(ContextCompat.getColor(this,R.color.mycolor));
Removing Python 3 was the worst thing I did since I recently moved to the world of Linux. It removed Firefox, my launcher and, as I read while trying to fix my problem, it may also remove your desktop and terminal! Finally fixed after a long daytime nightmare. Just don't remove Python 3. Keep it there!
If that happens to you, here is the fix:
Here is working code that defines a subroutine make_3d_array
to allocate a multidimensional 3D array with N1
, N2
and N3
elements in each dimension, and then populates it with random numbers. You can use the notation A[i][j][k]
to access its elements.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Method to allocate a 2D array of floats
float*** make_3d_array(int nx, int ny, int nz) {
float*** arr;
int i,j;
arr = (float ***) malloc(nx*sizeof(float**));
for (i = 0; i < nx; i++) {
arr[i] = (float **) malloc(ny*sizeof(float*));
for(j = 0; j < ny; j++) {
arr[i][j] = (float *) malloc(nz * sizeof(float));
}
}
return arr;
}
int main(int argc, char *argv[])
{
int i, j, k;
size_t N1=10,N2=20,N3=5;
// allocates 3D array
float ***ran = make_3d_array(N1, N2, N3);
// initialize pseudo-random number generator
srand(time(NULL));
// populates the array with random numbers
for (i = 0; i < N1; i++){
for (j=0; j<N2; j++) {
for (k=0; k<N3; k++) {
ran[i][j][k] = ((float)rand()/(float)(RAND_MAX));
}
}
}
// prints values
for (i=0; i<N1; i++) {
for (j=0; j<N2; j++) {
for (k=0; k<N3; k++) {
printf("A[%d][%d][%d] = %f \n", i,j,k,ran[i][j][k]);
}
}
}
free(ran);
}