Smoke Testing:-
Smoke test is scripted, i.e you have either manual test cases or automated scripts for it.
Sanity Testing:-
Sanity tests are mostly non scripted.
The syntax to disable an HTML input is as follows:
<input type="text" id="input_id" DISABLED />
I was also facing the same issue and I went through lot of answer on stackoverflow. Then i found one solution which help me resolve this issue.
Check package name in AndroidManifest.xml file. I forgot to change it while copy pasting another project into new project.
You can refer in this line - Difference between ASP.NET Core (.NET Core) and ASP.NET Core (.NET Framework)
Xamarin is not a debate at all. When you want to build mobile (iOS, Android, and Windows Mobile) apps using C#, Xamarin is your only choice.
The .NET Framework supports Windows and Web applications. Today, you can use Windows Forms, WPF, and UWP to build Windows applications in .NET Framework. ASP.NET MVC is used to build Web applications in .NET Framework.
.NET Core is the new open-source and cross-platform framework to build applications for all operating system including Windows, Mac, and Linux. .NET Core supports UWP and ASP.NET Core only. UWP is used to build Windows 10 targets Windows and mobile applications. ASP.NET Core is used to build browser based web applications.
you want more details refer this links
https://blogs.msdn.microsoft.com/dotnet/2016/07/15/net-core-roadmap/
https://docs.microsoft.com/en-us/dotnet/articles/standard/choosing-core-framework-server
It probably aimed to select all the informations in your table. If you use this kind of query (for example in PHP) :
mysql_query("SELECT * FROM newsletter WHERE email = '$email'");
The email ' OR 1=1/* will give this kind of query :
mysql_query("SELECT * FROM newsletter WHERE email = '' OR 1=1/*");
So it selects all the rows (because 1=1 is always true and the rest of the query is 'commented'). But it was not successful
In order to refresh a table layout (TableLayout) I ended up having to use the recursive approach mentioned above to get all the children's children and so forth.
My situation was somewhat simplified because I only needed to work with LinearLayout and those classes extended from it such as TableLayout. And I was only interested in finding TextView children. But I think it's still applicable to this question.
The final class runs as a separate thread, which means it can do other things in the background before parsing for the children. The code is small and simple and can be found at github: https://github.com/jkincali/Android-LinearLayout-Parser
In Excel, there is a way to embed relative reference to file or directory. You can try type in excel cell : =HYPERLINK("..\Name_of_file_or_folder\","DisplayLinkName")
from operator import attrgetter
ut.sort(key = attrgetter('count'), reverse = True)
Go to wherever you installed Android Studio (for me it's under C:\Users\username\AppData\Local\Android\android-studio\
) and open sdk\tools
, then run android.bat
. From here, update and download any missing build-tools and make sure you update the Android Support Repository and Android Support Library under Extras. Restart Android Studio after the SDK Manager finishes.
It seems that Android Studio completely ignores any installed Android SDK files and keeps a copy of its own. After running an update, everything compiled successfully for me using compile com.android.support:appcompat-v7:18.0.+
I recommend the Java VisualVM distributed with the JDK (jvisualvm.exe). It can connect dynamically and access the threads and heap. I have found in invaluable for some problems.
When I originally wrote this answer it was under an assumption that the question was regarding 'offline' validation of licence keys. Most of the other answers address online verification, which is significantly easier to handle (most of the logic can be done server side).
With offline verification the most difficult thing is ensuring that you can generate a huge number of unique licence keys, and still maintain a strong algorithm that isnt easily compromised (such as a simple check digit)
I'm not very well versed in mathematics, but it struck me that one way to do this is to use a mathematical function that plots a graph
The plotted line can have (if you use a fine enough frequency) thousands of unique points, so you can generate keys by picking random points on that graph and encoding the values in some way
As an example, we'll plot this graph, pick four points and encode into a string as "0,-500;100,-300;200,-100;100,600"
We'll encrypt the string with a known and fixed key (horribly weak, but it serves a purpose), then convert the resulting bytes through Base32 to generate the final key
The application can then reverse this process (base32 to real number, decrypt, decode the points) and then check each of those points is on our secret graph.
Its a fairly small amount of code which would allow for a huge number of unique and valid keys to be generated
It is however very much security by obscurity. Anyone taking the time to disassemble the code would be able to find the graphing function and encryption keys, then mock up a key generator, but its probably quite useful for slowing down casual piracy.
For Binary Search, T(N) = T(N/2) + O(1) // the recurrence relation
Apply Masters Theorem for computing Run time complexity of recurrence relations : T(N) = aT(N/b) + f(N)
Here, a = 1, b = 2 => log (a base b) = 1
also, here f(N) = n^c log^k(n) //k = 0 & c = log (a base b)
So, T(N) = O(N^c log^(k+1)N) = O(log(N))
OutOfMemoryException (on 32-bit machines) is just as often about Fragmentation as actual hard limits on memory - you'll find lots about this, but here's my first google hit briefly discussing it: http://blogs.msdn.com/b/joshwil/archive/2005/08/10/450202.aspx. (@Anthony Pegram is referring to the same problem in his comment above).
That said, there is one other possibility that comes to mind for your code above: As you're using the "IEnumerable" constructor to the List, you may not giving the object any hints as to the size of the collection you're passing to the List constructor. If the object you are passing is is not a collection (does not implement the ICollection
interface), then behind-the-scenes the List implementation is going to need to grow several (or many) times, each time leaving behind a too-small array that needs to be garbage collected. The garbage collector probably won't get to those discarded arrays fast enough, and you'll get your error.
The simplest fix for this would be to use the List(int capacity)
constructor to tell the framework what backing array size to allocate (even if you're estimating and just guessing "50000" for example), and then use the AddRange(IEnumerable collection)
method to actually populate your list.
So, simplest "Fix" if I'm right: replace
List<Vehicle> vList = new List<Vehicle>(selectedVehicles);
with
List<Vehicle> vList = new List<Vehicle>(50000);
vList.AddRange(selectedVehicles);
All the other comments and answers still apply in terms of overall design decisions - but this might be a quick fix.
Note (as @Alex commented below), this is only an issue if selectedVehicles
is not an ICollection.
Simplest solution seems to be specifying the ylim
range. Here is some code to do this automatically (left default, right - adjusted):
# default y-axis
barplot(dat, beside=TRUE)
# automatically adjusted y-axis
barplot(dat, beside=TRUE, ylim=range(pretty(c(0, dat))))
The trick is to use pretty()
which returns a list of interval breaks covering all values of the provided data. It guarantees that the maximum returned value is 1) a round number 2) greater than maximum value in the data.
In the example 0 was also added pretty(c(0, dat))
which makes sure that axis starts from 0.
The Maven Wrapper is an excellent choice for projects that need a specific version of Maven (or for users that don't want to install Maven at all). Instead of installing many versions of it in the operating system, we can just use the project-specific wrapper script.
mvnw: it's an executable Unix shell script used in place of a fully installed Maven
mvnw.cmd: it's for Windows environment
Use Cases
The wrapper should work with different operating systems such as:
After that, we can run our goals like this for the Unix system:
./mvnw clean install
And the following command for Batch:
./mvnw.cmd clean install
If we don't have the specified Maven in the wrapper properties, it'll be downloaded and installed in the folder $USER_HOME/.m2/wrapper/dists
of the system.
Maven Wrapper plugin
Maven Wrapper plugin to make auto installation in a simple Spring Boot project.
First, we need to go in the main folder of the project and run this command:
mvn -N io.takari:maven:wrapper
We can also specify the version of Maven:
mvn -N io.takari:maven:wrapper -Dmaven=3.5.2
The option -N means –non-recursive so that the wrapper will only be applied to the main project of the current directory, not in any submodules.
Source 1 (further reading): https://www.baeldung.com/maven-wrapper
In general, there is no way to know when something on another site has been changed. If the site offers an RSS feed, you should try that. If the site does not offer an RSS feed (or if the RSS feed doesn't include the information you're looking for), then you have to scrape and compare.
I saw a case where Chrome had installed WidgetBlock which was blocking the Facebook script. The result was exactly this error message. Make sure you disable any extensions that may interfere.
The patch is here: https://code.ros.org/trac/opencv/attachment/ticket/862/OpenCV-2.2-nov4l1.patch
By adding #ifdef HAVE_CAMV4L
around
#include <linux/videodev.h>
in OpenCV-2.2.0/modules/highgui/src/cap_v4l.cpp
and removing || defined (HAVE_CAMV4L2)
from line 174
allowed me to compile.
try regular expression method at this URL: http://www.dotnetperls.com/remove-html-tags
/// <summary>
/// Remove HTML from string with Regex.
/// </summary>
public static string StripTagsRegex(string source)
{
return Regex.Replace(source, "<.*?>", string.Empty);
}
/// <summary>
/// Compiled regular expression for performance.
/// </summary>
static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);
/// <summary>
/// Remove HTML from string with compiled Regex.
/// </summary>
public static string StripTagsRegexCompiled(string source)
{
return _htmlRegex.Replace(source, string.Empty);
}
Here is example code you could run to make such test:
var f = 10000000;
var p = new int[f];
for(int i = 0; i < f; ++i)
{
p[i] = i % 2;
}
var time = DateTime.Now;
p.Sum();
Console.WriteLine(DateTime.Now - time);
int x = 0;
time = DateTime.Now;
foreach(var item in p){
x += item;
}
Console.WriteLine(DateTime.Now - time);
x = 0;
time = DateTime.Now;
for(int i = 0, j = f; i < j; ++i){
x += p[i];
}
Console.WriteLine(DateTime.Now - time);
The same example for complex object is:
void Main()
{
var f = 10000000;
var p = new Test[f];
for(int i = 0; i < f; ++i)
{
p[i] = new Test();
p[i].Property = i % 2;
}
var time = DateTime.Now;
p.Sum(k => k.Property);
Console.WriteLine(DateTime.Now - time);
int x = 0;
time = DateTime.Now;
foreach(var item in p){
x += item.Property;
}
Console.WriteLine(DateTime.Now - time);
x = 0;
time = DateTime.Now;
for(int i = 0, j = f; i < j; ++i){
x += p[i].Property;
}
Console.WriteLine(DateTime.Now - time);
}
class Test
{
public int Property { get; set; }
}
My results with compiler optimizations off are:
00:00:00.0570370 : Sum()
00:00:00.0250180 : Foreach()
00:00:00.0430272 : For(...)
and for second test are:
00:00:00.1450955 : Sum()
00:00:00.0650430 : Foreach()
00:00:00.0690510 : For()
it looks like LINQ is generally slower than foreach(...) but what is weird for me is that foreach(...) appears to be faster than for loop.
For general purpose like 3D or higher multidimensional nested arrays, try this:
import numpy as np
def unique_nested_arrays(ar):
origin_shape = ar.shape
origin_dtype = ar.dtype
ar = ar.reshape(origin_shape[0], np.prod(origin_shape[1:]))
ar = np.ascontiguousarray(ar)
unique_ar = np.unique(ar.view([('', origin_dtype)]*np.prod(origin_shape[1:])))
return unique_ar.view(origin_dtype).reshape((unique_ar.shape[0], ) + origin_shape[1:])
which satisfies your 2D dataset:
a = np.array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 0]])
unique_nested_arrays(a)
gives:
array([[0, 1, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 0]])
But also 3D arrays like:
b = np.array([[[1, 1, 1], [0, 1, 1]],
[[0, 1, 1], [1, 1, 1]],
[[1, 1, 1], [0, 1, 1]],
[[1, 1, 1], [1, 1, 1]]])
unique_nested_arrays(b)
gives:
array([[[0, 1, 1], [1, 1, 1]],
[[1, 1, 1], [0, 1, 1]],
[[1, 1, 1], [1, 1, 1]]])
Try this one:
try
{
device_version = getPackageManager().getPackageInfo("com.google.android.gms", 0).versionName;
}
catch (PackageManager.NameNotFoundException e)
{
e.printStackTrace();
}
According to the URI standard the path is for hierarchical parameters and the query is for non-hierarchical parameters. Ofc. it can be very subjective what is hierarchical for you.
In situations where multiple URIs are assigned to the same resource I like to put the parameters - necessary for identification - into the path and the parameters - necessary to build the representation - into the query. (For me this way it is easier to route.)
For example:
/users/123
and /users/123?fields="name, age"
/users
and /users?name="John"&age=30
For map reduce I like to use the following approaches:
/users?name="John"&age=30
/users/name:John/age:30
So it is really up to you (and your server side router) how you construct your URIs.
note: Just to mention these parameters are query parameters. So what you are really doing is defining a simple query language. By complex queries (which contain operators like and, or, greater than, etc.) I suggest you to use an already existing query language. The capabilities of URI templates are very limited...
In your function form
is a DOM object, In order to use attr()
you need to convert it to jQuery object.
function f(form, fname, lname) {
action = $(form).attr("action");
$.post(att, {fname : fname , lname :lname}).done(function (data) {
alert(data);
});
return true;
}
With .serialize()
function f(form, fname, lname) {
action = $(form).attr("action");
$.post(att, $(form).serialize() ).done(function (data) {
alert(data);
});
return true;
}
Additionally, You can use .serialize()
Regular expressions work well if needing to find a range of starting characters. The following finds all employee names starting with A, B, C or D and adds the “UPPER” call in case a name is in the database with a starting lowercase letter. My query works in Oracle (I did not test other DB's). The following would return for example:
Adams
adams
Dean
dean
This query also ignores case in the ORDER BY via the "lower" call:
SELECT employee_name
FROM employees
WHERE REGEXP_LIKE(UPPER(TRIM(employee_name)), '^[A-D]')
ORDER BY lower(employee_name)
extrac Guid values from database functions:
#region GUID
public static Guid GGuid(SqlDataReader reader, string field)
{
try
{
return reader[field] == DBNull.Value ? Guid.Empty : (Guid)reader[field];
}
catch { return Guid.Empty; }
}
public static Guid GGuid(SqlDataReader reader, int ordinal = 0)
{
try
{
return reader[ordinal] == DBNull.Value ? Guid.Empty : (Guid)reader[ordinal];
}
catch { return Guid.Empty; }
}
public static Guid? NGuid(SqlDataReader reader, string field)
{
try
{
if (reader[field] == DBNull.Value) return (Guid?)null; else return (Guid)reader[field];
}
catch { return (Guid?)null; }
}
public static Guid? NGuid(SqlDataReader reader, int ordinal = 0)
{
try
{
if (reader[ordinal] == DBNull.Value) return (Guid?)null; else return (Guid)reader[ordinal];
}
catch { return (Guid?)null; }
}
#endregion
var theDiff24 = (b-a).Hours
While not yet supported on iOS (as of iOS 10), websites can send push notifications to Firefox and Chrome (Desktop/Android) with the Push API.
The Push API is used in conjunction with the older Web Notifications to display the message. The advantage is that the Push API allow the notification to be delivered even when the user is not surfing your website, because they are built upon Service Workers (scripts that are registered by the browser and can be executed in background at a later time even after your user has left your website).
The process of sending a notification involves the following:
The Push API is currently supported on desktop and Android by Chrome, Firefox and Opera.
You can also send push notifications to Apple / Safari desktop using APNs. The approach is similar, but with many complications (apple developer certificates, push packages, low-level TCP connection to APNs).
If you want to implement the push notifications by yourself start with these tutorials:
If you are looking for a drop in solution I would suggest Pushpad, which is a service I have built.
Update (September 2017): Apple has started developing the service workers for WebKit (status). Since the service workers are a fundamental technology for web push, this is a big step forward.
JSch is a pure Java implementation of SSH2 that helps you run commands on remote machines. You can find it here, and there are some examples here.
You can use exec.java
.
The dir
you specified is a working directory of running process - it doesn't help to find executable. Use cmd /c winrar ...
to run process looking for executable in PATH or try to use absolute path to winrar.
I've had multenum for "Multi-column enumerated lists" recommended to me, but I've never actually used it myself, yet.
Edit: The syntax doesn't exactly look like you could easily copy+paste lists into the LaTeX code. So, it may not be the best solution for your use case!
A degree of control is possible over how information travels from a third-party website to Facebook when a page is shared (or liked, etc.). In order to make this possible, information is sent via Open Graph meta tags in the <head>
part of the website’s code.
In Sass we can write:
background-color: rgba(#ff0000, 0.5);
as it was suggested in Hex representation of a color with alpha channel?
I use XSD
in a batch script to generate .xsd
file and classes from XML
directly :
set XmlFilename=Your__Xml__Here
set WorkingFolder=Your__Xml__Path_Here
set XmlExtension=.xml
set XsdExtension=.xsd
set XSD="C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1\Tools\xsd.exe"
set XmlFilePath=%WorkingFolder%%XmlFilename%%XmlExtension%
set XsdFilePath=%WorkingFolder%%XmlFilename%%XsdExtension%
%XSD% %XmlFilePath% /out:%WorkingFolder%
%XSD% %XsdFilePath% /c /out:%WorkingFolder%
Response.Redirect is more costly since it adds an extra trip to the server to figure out where to go.
Server.Transfer is more efficient however it can be a little mis-leading to the user since the Url doesn't physically change.
In my experience, the difference in performance has not been significant enough to use the latter approach
I have found this answer and I edit that in more reliable way
def download_photo(self, img_url, filename):
try:
image_on_web = urllib.urlopen(img_url)
if image_on_web.headers.maintype == 'image':
buf = image_on_web.read()
path = os.getcwd() + DOWNLOADED_IMAGE_PATH
file_path = "%s%s" % (path, filename)
downloaded_image = file(file_path, "wb")
downloaded_image.write(buf)
downloaded_image.close()
image_on_web.close()
else:
return False
except:
return False
return True
From this you never get any other resources or exceptions while downloading.
The quick answer.
Separate rules with commas:
@media handheld, (min-width: 650px), (orientation: landscape) { ... }
The long answer.
There's a lot here, but I've tried to make it information dense, not just fluffy writing. It's been a good chance to learn myself! Take the time to systematically read though and I hope it will be helpful.
Media queries essentially are used in web design to create device- or situation-specific browsing experiences; this is done using the @media
declaration within a page's CSS. This can be used to display a webpage differently under a large number of circumstances: whether you are on a tablet or TV with different aspect ratios, whether your device has a color or black-and-white screen, or, perhaps most frequently, when a user changes the size of their browser or switches between browsing devices with varying screen sizes (very generally speaking, designing like this is referred to as Responsive Web Design)
In designing for these situations, there appear to be four Logical Operators that can be used to require more complex combinations of requirements when targeting a variety of devices or viewport sizes.
(Note: If you don't understand the the differences between media rules, media queries, and feature queries, browse the bottom section of this answer first to get a bit better acquainted with the terminology associated with media query syntax
1. AND (and keyword)
Requires that all conditions specified must be met before the styling rules will take effect.
@media screen and (min-width: 700px) and (orientation: landscape) { ... }
The specified styling rules won't go into place unless all of the following evaluate as true:
Note: I believe that used together, these three feature queries make up a single media query.
2. OR (Comma-separated lists)
Rather than an or keyword, comma-separated lists are used in chaining multiple media queries together to form a more complex media rule
@media handheld, (min-width: 650px), (orientation: landscape) { ... }
The specified styling rules will go into effect once any one media query evaluates as true:
3. NOT (not keyword)
The not keyword can be used to negate a single media query (and NOT a full media rule--meaning that it only negates entries between a set of commas and not the full media rule following the @media declaration).
Similarly, note that the not keyword negates media queries, it cannot be used to negate an individual feature query within a media query.*
@media not screen and (min-resolution: 300dpi), (min-width: 800px) { ... }
The styling specified here will go into effect if
In other words, if the media type is 'screen' and the min-resolution is 300 dpi, the rule will not go into effect unless the min-width of the viewport is at least 800 pixels.
(The not keyword can be a little funky to state. Let me know if I can do better. ;)
4. ONLY (only keyword)
As I understand it, the only keyword is used to prevent older browsers from misinterpreting newer media queries as the earlier-used, narrower media type. When used correctly, older/non-compliant browsers should just ignore the styling altogether.
<link rel="stylesheet" media="only screen and (color)" href="example.css" />
An older / non-compliant browser would just ignore this line of code altogether, I believe as it would read the only keyword and consider it an incorrect media type. (See here and here for more info from smarter people)
FOR MORE INFO
For more info (including more features that can be queried), see: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries#Logical_operators
Note: I needed to learn the following terminology for everything here to make sense, particularly concerning the not keyword. Here it is as I understand it:
A media rule (MDN also seems to call these media statements) includes the term @media
with all of its ensuing media queries
@media all and (min-width: 800px)
@media only screen and (max-resolution:800dpi), not print
@media screen and (min-width: 700px), (orientation: landscape)
@media handheld, (min-width: 650px), (min-aspect-ratio: 1/1)
A media query is a set of feature queries. They can be as simple as one feature query or they can use the and keyword to form a more complex query. Media queries can be comma-separated to form more complex media rules (see the or keyword above).
screen
(Note: Only one feature query in use here.)
only screen
only screen and (max-resolution:800dpi)
only tv and (device-aspect-ratio: 16/9) and (color)
NOT handheld, (min-width: 650px)
. (Note the comma: there are two media queries here.)
A feature query is the most basic portion of a media rule and simply concerns a given feature and its status in a given browsing situation.
screen
(min-width: 650px)
(orientation: landscape)
(device-aspect-ratio: 16/9)
Code snippets and information derived from:
CSS media queries by Mozilla Contributors (licensed under CC-BY-SA 2.5). Some code samples were used with minor alterations to (hopefully) increase clarity of explanation.
My problem was caused by having external ip in $ZBX_SERVER setting.
I changed it to localhost instead so that ip was resolved internally,
$sudo nano /etc/zabbix/web/zabbix.conf.php
Changed
$ZBX_SERVER = 'external ip was written here';
to
$ZBX_SERVER = 'localhost';
then
$sudo service zabbix-server restart
Zabbix 3.4 on Ubuntu 14.04.3 LTS
You can retrieve the email address from the logged in user's profile. Here is the code snippet
<?php
$facebook = new Facebook(array(
'appId' => $initMe["appId"],
'secret' => $initMe["appSecret"],
));
$facebook->setAccessToken($initMe["accessToken"]);
$user = $facebook->getUser();
if ($user) {
$user_profile = $facebook->api('/me');
print_r($user_profile["email"]);
}
?>
How does Scrum fit into Agile Development?
While the Agile methodology can be applied to product development not only in the software industry but in other industries as well, Scrum is specific to software development.
Scrum is not a methodology. It simply provides structure, discipline and a framework for Agile development. The whole project is made up of a series of Sprints or Sprint Cycles (1 to n) where each Sprint is of the same duration. If ‘time’ is denoted by T, then T1 = T2 = T3 =… Tn. Sprints could be anywhere between 2 to 4 weeks. Sprints shorter than 2 weeks are not ideal and are used less frequently. At the end of each Sprint, a functional / working piece of software is produced that the users can actually test.
Original article is here...
Use
.title{
display: inline-block;
height: 25px;
}
The only trick is browser support. Check if your list of supported browsers handles inline-block here.
You can use google map Obtaining User Location here!
After obtaining your location(longitude and latitude), you can use google place api
This code can help you get your location easily but not the best way.
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
With Java 7 and later version, you can specify a byte literal in this way:
byte aByte = (byte)0b00100001;
Reference: http://docs.oracle.com/javase/8/docs/technotes/guides/language/binary-literals.html
File.AppendAllText
does not know about the stream you have opened, so will internally try to open the file again. Because your stream is blocking access to the file, File.AppendAllText
will fail, throwing the exception you see.
I suggest you used str.Write
or str.WriteLine
instead, as you already do elsewhere in your code.
Your file is created but contains nothing because the exception is thrown before str.Flush()
and str.Close()
are called.
Using the Stuff and for xml path operator to concatenate rows to string :Group By two columns -->
CREATE TABLE #YourTable ([ID] INT, [Name] CHAR(1), [Value] INT)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'A',4)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'B',8)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'B',5)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)
-- retrieve each unique id and name columns and concatonate the values into one column
SELECT
[ID],
STUFF((
SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) -- CONCATONATES EACH APPLICATION : VALUE SET
FROM #YourTable
WHERE (ID = Results.ID and Name = results.[name] )
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
,1,2,'') AS NameValues
FROM #YourTable Results
GROUP BY ID
SELECT
[ID],[Name] , --these are acting as the group by clause
STUFF((
SELECT ', '+ CAST([Value] AS VARCHAR(MAX)) -- CONCATONATES THE VALUES FOR EACH ID NAME COMBINATION
FROM #YourTable
WHERE (ID = Results.ID and Name = results.[name] )
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
,1,2,'') AS NameValues
FROM #YourTable Results
GROUP BY ID, name
DROP TABLE #YourTable
I tried some of the supplied answers but none of them seemed to work. Then I tried this:
new webpack.ProvidePlugin({
'window.jQuery' : 'jquery',
'window.$' : 'jquery',
'jQuery' : 'jquery',
'$' : 'jquery'
});
Seems to work no matter which version I'm using
In Postgresql:
select *
from comments
where id in (1,3,2,4)
order by position(id::text in '1,3,2,4')
If you are making repeated calls and are concerned with performance, This test reveals the BASH method is ~15x faster than forking to sed and likely any other external process.
hello=123456789X123456789X123456789X123456789X123456789X123456789X123456789X123456789X123456789X123456789X123456789X
P1=$(date +%s)
for i in {1..10000}
do
echo $hello | sed s/X//g > /dev/null
done
P2=$(date +%s)
echo $[$P2-$P1]
for i in {1..10000}
do
echo ${hello//X/} > /dev/null
done
P3=$(date +%s)
echo $[$P3-$P2]
Everything in Java is passed by value. In case of an array (which is nothing but an Object), the array reference is passed by value (just like an object reference is passed by value).
When you pass an array to other method, actually the reference to that array is copied.
See this post: Is Java "pass-by-reference" or "pass-by-value"?
See this working example:
public static void changeContent(int[] arr) {
// If we change the content of arr.
arr[0] = 10; // Will change the content of array in main()
}
public static void changeRef(int[] arr) {
// If we change the reference
arr = new int[2]; // Will not change the array in main()
arr[0] = 15;
}
public static void main(String[] args) {
int [] arr = new int[2];
arr[0] = 4;
arr[1] = 5;
changeContent(arr);
System.out.println(arr[0]); // Will print 10..
changeRef(arr);
System.out.println(arr[0]); // Will still print 10..
// Change the reference doesn't reflect change here..
}
Expanding on the answers provided here.
You can just do set idx = 1
to set a variable, but that syntax is not recommended because the variable name may clash with a set sub-command. As an example set w=1
would not be valid.
This means that you should prefer the syntax: set variable idx = 1
or set var idx = 1
.
Last but not least, you can just use your trusty old print command, since it evaluates an expression. The only difference being that he also prints the result of the expression.
(gdb) p idx = 1
$1 = 1
You can read more about gdb here.
You can pass the parameter(s) as a property of the function object, not as a parameter:
var f = this.someFunction; //use 'this' if called from class
f.parameter1 = obj;
f.parameter2 = this;
f.parameter3 = whatever;
setInterval(f, 1000);
Then in your function someFunction
, you will have access to the parameters. This is particularly useful inside classes where the scope goes to the global space automatically and you lose references to the class that called setInterval to begin with. With this approach, "parameter2" in "someFunction", in the example above, will have the right scope.
#Use this, THIS IS FOR EXTRACTING NUMBER FROM STRING IN GENERAL. #To get all the numeric occurences.
*split function to convert string to list and then the list comprehension which can help us iterating through the list and is digit function helps to get the digit out of a string.
test_string = "i have four ballons for 2 kids"
print("The original string : "+ test_string)
# list comprehension + isdigit() +split()
res = [int(i) for i in test_string.split() if i.isdigit()]
print("The numbers list is : "+ str(res))
#To extract numeric values from a string in python
*Find list of all integer numbers in string separated by lower case characters using re.findall(expression,string)
method.
*Convert each number in form of string into decimal number and then find max of it.
import re
def extractMax(input):
# get a list of all numbers separated by lower case characters
numbers = re.findall('\d+',input)
# \d+ is a regular expression which means one or more digit
number = map(int,numbers)
print max(numbers)
if __name__=="__main__":
input = 'sting'
extractMax(input)
Change your systemPath.
<dependency>
<groupId>stuff</groupId>
<artifactId>library</artifactId>
<version>1.0</version>
<systemPath>${project.basedir}/MyLibrary.jar</systemPath>
<scope>system</scope>
</dependency>
This is not exactly what you were asking about and it can only be used from the command line (and may be useless in a batch file), but one quick way to check file size is just to use dir
:
> dir Microsoft.WindowsAzure.Storage.xml
Results in:
Directory of C:\PathToTheFile
08/10/2015 10:57 AM 2,905,897 Microsoft.WindowsAzure.Storage.xml
1 File(s) 2,905,897 bytes
0 Dir(s) 759,192,064,000 bytes free
This Javascript function purports to show the difference between the Blob File API and the Data API to download a JSON file in the client browser:
/**_x000D_
* Save a text as file using HTML <a> temporary element and Blob_x000D_
* @author Loreto Parisi_x000D_
*/_x000D_
_x000D_
var saveAsFile = function(fileName, fileContents) {_x000D_
if (typeof(Blob) != 'undefined') { // Alternative 1: using Blob_x000D_
var textFileAsBlob = new Blob([fileContents], {type: 'text/plain'});_x000D_
var downloadLink = document.createElement("a");_x000D_
downloadLink.download = fileName;_x000D_
if (window.webkitURL != null) {_x000D_
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);_x000D_
} else {_x000D_
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);_x000D_
downloadLink.onclick = document.body.removeChild(event.target);_x000D_
downloadLink.style.display = "none";_x000D_
document.body.appendChild(downloadLink);_x000D_
}_x000D_
downloadLink.click();_x000D_
} else { // Alternative 2: using Data_x000D_
var pp = document.createElement('a');_x000D_
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' +_x000D_
encodeURIComponent(fileContents));_x000D_
pp.setAttribute('download', fileName);_x000D_
pp.onclick = document.body.removeChild(event.target);_x000D_
pp.click();_x000D_
}_x000D_
} // saveAsFile_x000D_
_x000D_
/* Example */_x000D_
var jsonObject = {"name": "John", "age": 30, "car": null};_x000D_
saveAsFile('out.json', JSON.stringify(jsonObject, null, 2));
_x000D_
The function is called like saveAsFile('out.json', jsonString);
. It will create a ByteStream immediately recognized by the browser that will download the generated file directly using the File API URL.createObjectURL
.
In the else
, it is possible to see the same result obtained via the href
element plus the Data API, but this has several limitations that the Blob API has not.
Set it within button
instead of div
if you don't care about its little visual 3D effect.
#box_x000D_
{_x000D_
height: 120px;_x000D_
width: 300px;_x000D_
background: #000;_x000D_
font-size: 48px;_x000D_
font-style: oblique;_x000D_
color: #FFF;_x000D_
}
_x000D_
<button Id="box" disabled>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit._x000D_
</button>
_x000D_
RichTextBox will allow you to use html to specify the color. Another alternative is using a listbox and using the DrawItem event to draw how you would like. AFAIK, textbox itself can't be used in the way you're hoping.
inspired from https://stackoverflow.com/a/10892768/2087666 but I use the selector instead of a class and prefer if over switch:
function clearAllInputs(selector) {
$(selector).find(':input').each(function() {
if(this.type == 'submit'){
//do nothing
}
else if(this.type == 'checkbox' || this.type == 'radio') {
this.checked = false;
}
else if(this.type == 'file'){
var control = $(this);
control.replaceWith( control = control.clone( true ) );
}else{
$(this).val('');
}
});
}
this should take care of almost all input inside any selector.
This should now work with Internet Explorer, Firefox v12+ and Chrome 28+
<img src="'../images/foo.gif'"
alt="line 1
line 2" title="line 1
line 2">
Try a JavaScript tooltip library for a better result, something like OverLib.
swift 4.2
let textString = "Hello world"
let range = (textString as NSString).range(of: "world")
let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)
self.textUIlable.attributedText = attributedString
element.style
comes from the markup.
<li style="display: none;">
Just remove the style
attribute from the HTML.
Using map or other similar solution do not help to clone deeply an array of object. An easier way to do this without adding a new library is using JSON.stringfy and then JSON.parse.
In your case this should work :
this.backupData = JSON.parse(JSON.stringify(genericItems));
For small objet lodash cloneDeep can be faster but for larger/deeper object json clone become faster. So in this cases you should not hesitate to use it. check https://www.measurethat.net/Benchmarks/Show/6039/0/lodash-clonedeep-vs-json-clone-larger-object and for infos https://v8.dev/blog/cost-of-javascript-2019#json
The inconvenient is that your source object must be convertible to JSON.
# check if git repo
if [ $(git rev-parse --is-inside-work-tree) = true ]; then
echo "yes, is a git repo"
git pull
else
echo "no, is not a git repo"
git clone url --depth 1
fi
This should do it:
SELECT *
FROM INFORMATION_SCHEMA.VIEWS
WHERE VIEW_DEFINITION like '%YourTableName%'
In the Websphere case, you have an older version of slf4j-api.jar, 1.4.x. or 1.5.x lying around somewhere. The behavior you observe on tcServer, that is fail-over to NOP, occurs on slf4j versions 1.6.0 and later. Make sure that you are using slf4j-api-1.6.x.jar on all platforms and that no older version of slf4j-api is placed on the class path.
Just add vertical-align:top for first td alone needed not for all td.
tr>td:first-child {_x000D_
vertical-align: top;_x000D_
}
_x000D_
<tr>_x000D_
<td>Description</td>_x000D_
<td>more text</td>_x000D_
</tr>
_x000D_
Here is what I just did right now:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.javafx.runtime.VersionInfo;
public class ConnectToMySql {
public static ConnectBean dataBean = new ConnectBean();
public static void main(String args[]) {
getData();
}
public static void getData () {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage",
"root", "root");
// here mynewpage is database name, root is username and password
Statement stmt = con.createStatement();
System.out.println("stmt " + stmt);
ResultSet rs = stmt.executeQuery("select * from carsData");
System.out.println("rs " + rs);
int count = 1;
while (rs.next()) {
String vehicleType = rs.getString("VHCL_TYPE");
System.out.println(count +": " + vehicleType);
count++;
}
con.close();
} catch (Exception e) {
Logger lgr = Logger.getLogger(VersionInfo.class.getName());
lgr.log(Level.SEVERE, e.getMessage(), e);
System.out.println(e.getMessage());
}
}
}
The Above code will get you the first column of the table you have.
This is the table which you might need to create in your MySQL database
CREATE TABLE
carsData
(
VHCL_TYPE CHARACTER(10) NOT NULL,
);
You'll first require to close the file using fclose($handle);
it's not deleting because the file is in use. So first close the file and then try.
Even better solution:
<p style="position:relative;">
<a name="anchor" style="position:absolute; top:-100px;"></a>
I should be 100px below where I currently am!
</p>
Just position the <a>
tag with absolute positioning inside of a relatively positioned object.
Works when entering the page or through a hash change within page.
The same may be achieved with the stringi package:
library('stringi')
char_array <- c("foo_bar","bar_foo","apple","beer")
a <- data.frame("data"=char_array, "data2"=1:4)
(a$data <- stri_sub(a$data, 1, -4)) # from the first to the last but 4th char
## [1] "foo_" "bar_" "ap" "b"
Because if you don't make a copy then the indices can still be manipulated elsewhere even if you assign the dataFrame to a different name.
For example:
df2 = df
func1(df2)
func2(df)
func1 can modify df by modifying df2, so to avoid that:
df2 = df.copy()
func1(df2)
func2(df)
Just don't set the height property in HighCharts and it will handle it dynamically for you so long as you set a height on the chart's containing element. It can be a fixed number or a even a percent if position is absolute.
By default the height is calculated from the offset height of the containing element
Example: http://jsfiddle.net/wkkAd/149/
#container {
height:100%;
width:100%;
position:absolute;
}
$(".pushme").click(function () {
var button = $(this);
button.text(button.text() == "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME")
});
This ternary operator has an implicit return.
If the expression before ?
is true
it returns "DON'T PUSH ME"
, else returns "PUSH ME"
This if-else statement:
if (condition) { return A }
else { return B }
has the equivalent ternary expression:
condition ? A : B
You can use this sql statement to get the history for any date:
SELECT * FROM V$SQL V where to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss') > sysdate - 60
First create assets
folder then create fonts
folder in it.
Then you can set font
from assets
or directory
like bellow :
public class FontSampler extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.custom);
Typeface face = Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
tv.setTypeface(face);
File font = new File(Environment.getExternalStorageDirectory(), "MgOpenCosmeticaBold.ttf");
if (font.exists()) {
tv = (TextView) findViewById(R.id.file);
face = Typeface.createFromFile(font);
tv.setTypeface(face);
} else {
findViewById(R.id.filerow).setVisibility(View.GONE);
}
}
}
For the usual usages of label
and input
, it's just easier to wrap input into a label like this:
import React from 'react'
const Field = props => (
<label>
<span>{props.label}</span>
<input type="text"/>
</label>
)
It's also makes it possible in checkboxes/radiobuttons to apply padding to root element and still getting feedback of click on input.
The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.
Your criticism is entirely justified.
I discuss this problem in detail here:
Closing over the loop variable considered harmful
Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?
The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.
I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.
The for
loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.
I created a Eclipse plugin, which can count the lines of source code. It support Kotlin, Java, Java Script, JSP, XML, C/C++, C#, and many other file types.
Please take a look at it. Any feedback would be appreciated!
I don't have enough rep to comment here, so I'm submitting a new answer to improve on dogbane's answer. The dot . in the regexp
[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched
will actually match any character, not only the literal dot between 'tar.bz2', for example
[[ sed-4.2.2.tar4bz2 =~ tar.bz2$ ]] && echo matched
[[ sed-4.2.2.tar§bz2 =~ tar.bz2$ ]] && echo matched
or anything that doesn't require escaping with '\'. The strict syntax should then be
[[ sed-4.2.2.tar.bz2 =~ tar\.bz2$ ]] && echo matched
or you can go even stricter and also include the previous dot in the regex:
[[ sed-4.2.2.tar.bz2 =~ \.tar\.bz2$ ]] && echo matched
Here's a tidy solution where you provide the target date as a Calendar object.
// Used to translate the Month value of a JQuery calendar to the month value expected by a Calendar.
private static final Map<String,Integer> MONTH_TO_CALENDAR_INDEX = new HashMap<String,Integer>();
static {
MONTH_TO_CALENDAR_INDEX.put("January", 0);
MONTH_TO_CALENDAR_INDEX.put("February",1);
MONTH_TO_CALENDAR_INDEX.put("March",2);
MONTH_TO_CALENDAR_INDEX.put("April",3);
MONTH_TO_CALENDAR_INDEX.put("May",4);
MONTH_TO_CALENDAR_INDEX.put("June",5);
MONTH_TO_CALENDAR_INDEX.put("July",6);
MONTH_TO_CALENDAR_INDEX.put("August",7);
MONTH_TO_CALENDAR_INDEX.put("September",8);
MONTH_TO_CALENDAR_INDEX.put("October",9);
MONTH_TO_CALENDAR_INDEX.put("November",10);
MONTH_TO_CALENDAR_INDEX.put("December",11);
}
// ====================================================================================================
// setCalendarPicker
// ====================================================================================================
/**
* Sets the value of specified web element while assuming the element is a JQuery calendar.
* @param byOpen The By phrase that locates the control that opens the JQuery calendar when clicked.
* @param byPicker The By phrase that locates the JQuery calendar.
* @param targetDate The target date that you want set.
* @throws AssertionError if the method is unable to set the date.
*/
public void setCalendarPicker(By byOpen, By byPicker, Calendar targetDate) {
// Open the JQuery calendar.
WebElement opener = driver.findElement(byOpen);
opener.click();
// Locate the JQuery calendar.
WebElement picker = driver.findElement(byPicker);
// Calculate the target and current year-and-month as an integer where value = year*12+month.
// The difference between the two is the number of months we have to move ahead or backward.
int targetYearMonth = targetDate.get(Calendar.YEAR) * 12 + targetDate.get(Calendar.MONTH);
int currentYearMonth = Integer.valueOf(picker.findElement(By.className("ui-datepicker-year")).getText()) * 12
+ Integer.valueOf(MONTH_TO_CALENDAR_INDEX.get(picker.findElement(By.className("ui-datepicker-month")).getText()));
// Calculate the number of months we need to move the JQuery calendar.
int delta = targetYearMonth - currentYearMonth;
// As a sanity check, let's not allow more than 10 years so that we don't inadvertently spin in a loop for zillions of months.
if (Math.abs(delta) > 120) throw new AssertionError("Target date is more than 10 years away");
// Push the JQuery calendar forward or backward as appropriate.
if (delta > 0) {
while (delta-- > 0) picker.findElement(By.className("ui-icon-circle-triangle-e")).click();
} else if (delta < 0 ){
while (delta++ < 0) picker.findElement(By.className("ui-icon-circle-triangle-w")).click();
}
// Select the day within the month.
String dayOfMonth = String.valueOf(targetDate.get(Calendar.DAY_OF_MONTH));
WebElement tableOfDays = picker.findElement(By.cssSelector("tbody:nth-child(2)"));
for (WebElement we : tableOfDays.findElements(By.tagName("td"))) {
if (dayOfMonth.equals(we.getText())) {
we.click();
// Send a tab to completely leave this control. If the next control the user will access is another CalendarPicker,
// the picker might not get selected properly if we stay on the current control.
opener.sendKeys("\t");
return;
}
}
throw new AssertionError(String.format("Unable to select specified day"));
}
Now Junit5 provides a way to assert the exceptions
You can test both general exceptions and customized exceptions
A general exception scenario:
ExpectGeneralException.java
public void validateParameters(Integer param ) {
if (param == null) {
throw new NullPointerException("Null parameters are not allowed");
}
}
ExpectGeneralExceptionTest.java
@Test
@DisplayName("Test assert NullPointerException")
void testGeneralException(TestInfo testInfo) {
final ExpectGeneralException generalEx = new ExpectGeneralException();
NullPointerException exception = assertThrows(NullPointerException.class, () -> {
generalEx.validateParameters(null);
});
assertEquals("Null parameters are not allowed", exception.getMessage());
}
You can find a sample to test CustomException here : assert exception code sample
ExpectCustomException.java
public String constructErrorMessage(String... args) throws InvalidParameterCountException {
if(args.length!=3) {
throw new InvalidParameterCountException("Invalid parametercount: expected=3, passed="+args.length);
}else {
String message = "";
for(String arg: args) {
message += arg;
}
return message;
}
}
ExpectCustomExceptionTest.java
@Test
@DisplayName("Test assert exception")
void testCustomException(TestInfo testInfo) {
final ExpectCustomException expectEx = new ExpectCustomException();
InvalidParameterCountException exception = assertThrows(InvalidParameterCountException.class, () -> {
expectEx.constructErrorMessage("sample ","error");
});
assertEquals("Invalid parametercount: expected=3, passed=2", exception.getMessage());
}
if you are using lazy loading then must load that module in any router module , like in app-routing.module.ts {path:'home',loadChildren:'./home.module#HomeModule'}
You can now do this in most "modern" browsers!
Here is the original article I read (posted July 10, 2010): HTML5: Changing the browser-URL without refreshing page.
For a more in-depth look into pushState/replaceState/popstate (aka the HTML5 History API) see the MDN docs.
TL;DR, you can do this:
window.history.pushState("object or string", "Title", "/new-url");
See my answer to Modify the URL without reloading the page for a basic how-to.
you can use below to deep copy Hash objects.
deeply_copied_hash = Marshal.load(Marshal.dump(original_hash))
I had a similar issue, also seeing "Failed to load resource: net::ERR_CONTENT_DECODING_FAILED" and "ILLEGAL TOKEN" errors when loading JS files locally. Pressing CTRL+SHIFT+DEL and deleting all "Cookies and other site and plugin data" and "Cached images and files" fixed it.
BSTR
to std::wstring
:
// given BSTR bs
assert(bs != nullptr);
std::wstring ws(bs, SysStringLen(bs));
std::wstring
to BSTR
:
// given std::wstring ws
assert(!ws.empty());
BSTR bs = SysAllocStringLen(ws.data(), ws.size());
Doc refs:
git-credential-osxkeychain stores passwords in the Apple Keychain, as noted above.
By default, gitcredentials only considers the domain name. If you want Git to consider the full path (e.g. if you have multiple GitHub accounts), set the useHttpPath
variable to true
, as described at http://git-scm.com/docs/gitcredentials.html. Note that changing this setting will ask your credentials again for each URL.
We had a requirement where we needed to test all of these, here is what I wish to share
document.getElementById("tooltip").setAttribute("title", "Tool\x0ATip\x0AOn\x0ANew\x0ALine")
_x000D_
<p title='Tool_x000D_
Tip_x000D_
On_x000D_
New_x000D_
Line'>Tooltip with <pre>_x000D_
new _x000D_
line</pre> Works in all browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title="Tool Tip On New Line">Tooltip with <code>&#13;</code> Not works Firefox browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title='Tool Tip On New Line'>Tooltip with <code>&#10;</code> Works in some browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title='Tool
Tip
On
New
Line'>Tooltip with <code>&#xD;</code> May work in some browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p id='tooltip'>Tooltip with <code>document.getElementById("tooltip").setAttribute("title", "Tool\x0ATip\x0AOn\x0ANew\x0ALine")</code> May work in some browsers</p>_x000D_
<hr/>_x000D_
_x000D_
_x000D_
<p title="List:_x000D_
• List item here_x000D_
• Another list item here_x000D_
• Aaaand another list item, lol">Tooltip with <code>• </code>Unordered list tooltip</p>_x000D_
<hr/>_x000D_
_x000D_
_x000D_
<p title='Tool\nTip\nOn\nNew\nLine'>Tooltip with <code>\n</code> May not work in modern browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title='Tool\tTip\tOn\tNew\tLine'>Tooltip with <code>\t</code> May not work in modern browsers</p>_x000D_
<hr/>_x000D_
_x000D_
<p title='Tool
Tip
On
New
Line'>Tooltip with <code>&#013;</code> Works in most browsers</p>_x000D_
<hr/>
_x000D_
In Python, you can't just embed arbitrary Python expressions into literal strings and have it substitute the value of the string. You need to either:
sys.stderr.write("Usage: " + sys.argv[0])
or
sys.stderr.write("Usage: %s" % sys.argv[0])
Also, you may want to consider using the following syntax of print
(for Python earlier than 3.x):
print >>sys.stderr, "Usage:", sys.argv[0]
Using print
arguably makes the code easier to read. Python automatically adds a space between arguments to the print
statement, so there will be one space after the colon in the above example.
In Python 3.x, you would use the print
function:
print("Usage:", sys.argv[0], file=sys.stderr)
Finally, in Python 2.6 and later you can use .format
:
print >>sys.stderr, "Usage: {0}".format(sys.argv[0])
Go to preferences(settings) : click on Build,Execution,Deployment .....then select : Instant Run ......and uncheck its topmost checkbox (i.e Disable Instant Run)
Description and examples can be found in IEEE Std 1800-2017 § 11.5.1 "Vector bit-select and part-select addressing". First IEEE appearance is IEEE 1364-2001 (Verilog) § 4.2.1 "Vector bit-select and part-select addressing". Here is an direct example from the LRM:
logic [31: 0] a_vect; logic [0 :31] b_vect; logic [63: 0] dword; integer sel; a_vect[ 0 +: 8] // == a_vect[ 7 : 0] a_vect[15 -: 8] // == a_vect[15 : 8] b_vect[ 0 +: 8] // == b_vect[0 : 7] b_vect[15 -: 8] // == b_vect[8 :15] dword[8*sel +: 8] // variable part-select with fixed width
If sel
is 0 then dword[8*(0) +: 8] == dword[7:0]
If sel
is 7 then dword[8*(7) +: 8] == dword[63:56]
The value to the left always the starting index. The number to the right is the width and must be a positive constant. the +
and -
indicates to select the bits of a higher or lower index value then the starting index.
Assuming address
is in little endian ([msb:lsb]) format, then if(address[2*pointer+:2])
is the equivalent of if({address[2*pointer+1],address[2*pointer]})
If you are using jQuery then
$("#fileupload").val();
Are you sure you want to do this? In essence, you're duplicating the data that is in the three original columns. From that point on, you'll need to make sure that the data in the combined field matches the data in the first three columns. This is more overhead for your application, and other processes that update the system will need to understand the relationship.
If you need the data, why not select in when you need it? The SQL for selecting what would be in that field would be:
SELECT CONCAT(zipcode, ' - ', city, ', ', state) FROM Table;
This way, if the data in the fields changes, you don't have to update your combined field.
The right way to iterate over objects is
Object.keys(someObject).map(function(item)...
Object.keys(someObject).forEach(function(item)...;
// ES way
Object.keys(data).map(item => {...});
Object.keys(data).forEach(item => {...});
byte[] iso88591Data = theString.getBytes("ISO-8859-1");
Will do the trick. From your description it seems as if you're trying to "store an ISO-8859-1 String". String objects in Java are always implicitly encoded in UTF-16. There's no way to change that encoding.
What you can do, 'though is to get the bytes that constitute some other encoding of it (using the .getBytes()
method as shown above).
You can use the exif-js library in combination with the HTML5 File API: http://jsfiddle.net/xQnMd/1/.
$("input").change(function() {
var file = this.files[0]; // file
fr = new FileReader; // to read file contents
fr.onloadend = function() {
// get EXIF data
var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));
// alert a value
alert(exif.Make);
};
fr.readAsBinaryString(file); // read the file
});
I'd just like to add some comments from my personal experience (using both sagas and thunk):
Sagas are great to test:
Sagas are more powerful. All what you can do in one thunk's action creator you can also do in one saga, but not vice versa (or at least not easily). For example:
take
)cancel
, takeLatest
, race
)take
, takeEvery
, ...)Sagas also offers other useful functionality, which generalize some common application patterns:
channels
to listen on external event sources (e.g. websockets)fork
, spawn
)Sagas are great and powerful tool. However with the power comes responsibility. When your application grows you can get easily lost by figuring out who is waiting for the action to be dispatched, or what everything happens when some action is being dispatched. On the other hand thunk is simpler and easier to reason about. Choosing one or another depends on many aspects like type and size of the project, what types of side effect your project must handle or dev team preference. In any case just keep your application simple and predictable.
if you know the length of your rows you can make something like this:
a=rand(9,3);
b=rand(9,3);
arrayfun(@(x1,x2,y1,y2,z1,z2) line([x1,x2],[y1,y2],[z1,z2]) , a(:,1),b(:,1),a(:,2),b(:,2),a(:,3),b(:,3) )
As myJSON
is an object you can just set its properties, for example:
myJSON.list1 = ["1","2"];
If you dont know the name of the properties, you have to use the array access syntax:
myJSON['list'+listnum] = ["1","2"];
If you want to add an element to one of the properties, you can do;
myJSON.list1.push("3");
Use Python's json module, or simplejson if you don't have python 2.6 or higher.
In order to solve this I made sure that I upgraded to the newest MVC version using NuGet and Package Manager Console.
Install-Package Microsoft.AspNet.Mvc -Version 5.2.4
Then upgraded to the latest Razor version
Install-Package Microsoft.AspNet.Razor -Version 3.2.4
Then I changed all the web.config files to reflect the change. As you will see below:
In the main web.config file, make sure that the webpages:version is correct. This is where it can be found (ignore the other keys):
<configuration>
<appSettings>
<add key="webpages:Version" value="3.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
</configuration>
Then look for the other versions listed in the assemblies, check the version of the assembly against the version of the library listed in your project references! You may not need all of these.
<system.web>
<compilation debug="true" targetFramework="4.6">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
</system.web>
Runtime assemblyBinding should show the "newversion" as well, see where it reads NewVersion 5.2.4.0? But also check all the other versions.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-5.2.4.0" newVersion="5.2.4.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
THEN in the Views Web.Config section, make sure that Razor is the correct version:
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<configuration>
And Lastlt there is the Pages section of the Views Web.Config
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
In my project , I use the XMLHttpRequest to send multipart/form-data. I think it will fit you to.
and the uploader code
let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://www.example.com/rest/api', true);
xhr.withCredentials = true;
xhr.send(formData);
Here is example : https://github.com/wangzilong/angular2-multipartForm
Here's the Java code using registerDefaultNetworkCallback
(and registerNetworkCallback
for API < 24):
ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
// network available
}
@Override
public void onLost(Network network) {
// network unavailable
}
};
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(networkCallback);
} else {
NetworkRequest request = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
connectivityManager.registerNetworkCallback(request, networkCallback);
}
The initial question has been posted quite some time ago and in the meantime Debian has made huge headway in the area of multiarch support.
Multiarch is a great achievement for cross compilation!
In a nutshell the following steps are required to leverage multiarch for Raspbian Jessie cross compilation:
Since this is a lot of work I have automated the above setup. You can read about it here:
The is a simple and faster way to solve the problem.
You don't need to open a services
or write any cmd
code just follow my steps:
from XAMPP control
panel click Explorer
button
from directory find mysql_stop.bat
file and run it.
Thats all!! super easy.
Refresh your netstat
list, you will see that it has gone.
please make it as best answer.
The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):
Mikhail,
The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.
Good luck with your implementation.
Whenever you have heavyweight initialization that should be done once for many
RDD
elements rather than once perRDD
element, and if this initialization, such as creation of objects from a third-party library, cannot be serialized (so that Spark can transmit it across the cluster to the worker nodes), usemapPartitions()
instead ofmap()
.mapPartitions()
provides for the initialization to be done once per worker task/thread/partition instead of once perRDD
data element for example : see below.
val newRd = myRdd.mapPartitions(partition => {
val connection = new DbConnection /*creates a db connection per partition*/
val newPartition = partition.map(record => {
readMatchingFromDB(record, connection)
}).toList // consumes the iterator, thus calls readMatchingFromDB
connection.close() // close dbconnection here
newPartition.iterator // create a new iterator
})
Q2. does
flatMap
behave like map or likemapPartitions
?
Yes. please see example 2 of flatmap
.. its self explanatory.
Q1. What's the difference between an RDD's
map
andmapPartitions
map
works the function being utilized at a per element level whilemapPartitions
exercises the function at the partition level.
Example Scenario : if we have 100K elements in a particular RDD
partition then we will fire off the function being used by the mapping transformation 100K times when we use map
.
Conversely, if we use mapPartitions
then we will only call the particular function one time, but we will pass in all 100K records and get back all responses in one function call.
There will be performance gain since map
works on a particular function so many times, especially if the function is doing something expensive each time that it wouldn't need to do if we passed in all the elements at once(in case of mappartitions
).
Applies a transformation function on each item of the RDD and returns the result as a new RDD.
Listing Variants
def map[U: ClassTag](f: T => U): RDD[U]
Example :
val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
val b = a.map(_.length)
val c = a.zip(b)
c.collect
res0: Array[(String, Int)] = Array((dog,3), (salmon,6), (salmon,6), (rat,3), (elephant,8))
This is a specialized map that is called only once for each partition. The entire content of the respective partitions is available as a sequential stream of values via the input argument (Iterarator[T]). The custom function must return yet another Iterator[U]. The combined result iterators are automatically converted into a new RDD. Please note, that the tuples (3,4) and (6,7) are missing from the following result due to the partitioning we chose.
preservesPartitioning
indicates whether the input function preserves the partitioner, which should befalse
unless this is a pair RDD and the input function doesn't modify the keys.Listing Variants
def mapPartitions[U: ClassTag](f: Iterator[T] => Iterator[U], preservesPartitioning: Boolean = false): RDD[U]
Example 1
val a = sc.parallelize(1 to 9, 3)
def myfunc[T](iter: Iterator[T]) : Iterator[(T, T)] = {
var res = List[(T, T)]()
var pre = iter.next
while (iter.hasNext)
{
val cur = iter.next;
res .::= (pre, cur)
pre = cur;
}
res.iterator
}
a.mapPartitions(myfunc).collect
res0: Array[(Int, Int)] = Array((2,3), (1,2), (5,6), (4,5), (8,9), (7,8))
Example 2
val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
def myfunc(iter: Iterator[Int]) : Iterator[Int] = {
var res = List[Int]()
while (iter.hasNext) {
val cur = iter.next;
res = res ::: List.fill(scala.util.Random.nextInt(10))(cur)
}
res.iterator
}
x.mapPartitions(myfunc).collect
// some of the number are not outputted at all. This is because the random number generated for it is zero.
res8: Array[Int] = Array(1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 7, 7, 7, 9, 9, 10)
The above program can also be written using flatMap as follows.
Example 2 using flatmap
val x = sc.parallelize(1 to 10, 3)
x.flatMap(List.fill(scala.util.Random.nextInt(10))(_)).collect
res1: Array[Int] = Array(1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10)
mapPartitions
transformation is faster than map
since it calls your function once/partition, not once/element..
Further reading : foreach Vs foreachPartitions When to use What?
I would use compileall. It works nicely both from scripts and from the command line. It's a bit higher level module/tool than the already mentioned py_compile that it also uses internally.
Set is a unique collection of items. So there is no notion of first element. If you want items in the sorted order, you can use TreeSet from which you can retrieve the first element using TreeSet#first().
this.setState({ [`${event.target.id}`]: event.target.value}, () => {
console.log("State updated: ", JSON.stringify(this.state[event.target.id]));
});
Please mind the quote character.
You can do this all in the File.open block:
Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'
File.open playlist_name, 'w' do |f|
music.each do |z|
f.puts z
end
end
the strtok runtime function works like this
the first time you call strtok you provide a string that you want to tokenize
char s[] = "this is a string";
in the above string space seems to be a good delimiter between words so lets use that:
char* p = strtok(s, " ");
what happens now is that 's' is searched until the space character is found, the first token is returned ('this') and p points to that token (string)
in order to get next token and to continue with the same string NULL is passed as first argument since strtok maintains a static pointer to your previous passed string:
p = strtok(NULL," ");
p now points to 'is'
and so on until no more spaces can be found, then the last string is returned as the last token 'string'.
more conveniently you could write it like this instead to print out all tokens:
for (char *p = strtok(s," "); p != NULL; p = strtok(NULL, " "))
{
puts(p);
}
EDIT:
If you want to store the returned values from strtok
you need to copy the token to another buffer e.g. strdup(p);
since the original string (pointed to by the static pointer inside strtok
) is modified between iterations in order to return the token.
In Opera 12 when you bind using the plain JavaScript, 'oTransitionEnd' will work:
document.addEventListener("oTransitionEnd", function(){
alert("Transition Ended");
});
however if you bind through jQuery, you need to use 'otransitionend'
$(document).bind("otransitionend", function(){
alert("Transition Ended");
});
In case you are using Modernizr or bootstrap-transition.js you can simply do a change:
var transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd otransitionend',
'msTransition' : 'MSTransitionEnd',
'transition' : 'transitionend'
},
transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];
You can find some info here as well http://www.ianlunn.co.uk/blog/articles/opera-12-otransitionend-bugs-and-workarounds/
You can scale bitmaps by using canvas.drawBitmap with providing matrix, for example:
public static Bitmap scaleBitmap(Bitmap bitmap, int wantedWidth, int wantedHeight) {
Bitmap output = Bitmap.createBitmap(wantedWidth, wantedHeight, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Matrix m = new Matrix();
m.setScale((float) wantedWidth / bitmap.getWidth(), (float) wantedHeight / bitmap.getHeight());
canvas.drawBitmap(bitmap, m, new Paint());
return output;
}
In my case I convert DBresponse to XML in Camel ctx. JDBC executor return the ArrayList (rows) with LinkedCaseInsensitiveMap (single row). Task - create XML object based on DBResponce.
import java.io.StringWriter;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.springframework.util.LinkedCaseInsensitiveMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class ConvertDBToXMLProcessor implements Processor {
public void process(List body) {
if (body instanceof ArrayList) {
ArrayList<LinkedCaseInsensitiveMap> rows = (ArrayList) body;
DocumentBuilder builder = null;
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.newDocument();
Element rootElement = document.createElement("DBResultSet");
for (LinkedCaseInsensitiveMap row : rows) {
Element newNode = document.createElement("Row");
row.forEach((key, value) -> {
if (value != null) {
Element newKey = document.createElement((String) key);
newKey.setTextContent(value.toString());
newNode.appendChild(newKey);
}
});
rootElement.appendChild(newNode);
}
document.appendChild(rootElement);
/*
* If you need return string view instead org.w3c.dom.Document
*/
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
DOMSource domSource = new DOMSource(document);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.transform(domSource, result);
// return document
// return writer.toString()
}
}
}
Here is the list of valid timezones:
http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
You can use
TIME_ZONE = 'Europe/Istanbul'
for UTC+02:00
var myArray = [2,5,6,7,9,6];
myArray.includes(2) // is true
myArray.includes(14) // is false
If you're using express, you can get it from the request object:
req.app.settings.port // => 8080 or whatever your app is listening at.
From commons-lang3
org.apache.commons.lang3.text.WordUtils.capitalizeFully(String str)
try this:
select TITLE,
(length(DESCRIPTION )-length(replace(DESCRIPTION ,'value','')))/5 as COUNT
FROM <table>
You could do:
var matchingDog = AllDogs.FirstOrDefault(dog => dog.Id == "2"));
This will return the matching dog, else it will return null
.
You can then set the property like follows:
if (matchingDog != null)
matchingDog.Name = "New Dog Name";
Here is a simple way to define those constants, and I'm pretty sure it's portable:
const double inf = 1.0/0.0;
const double nan = 0.0/0.0;
When I run this code:
printf("inf = %f\n", inf);
printf("-inf = %f\n", -inf);
printf("nan = %f\n", nan);
printf("-nan = %f\n", -nan);
I get:
inf = inf
-inf = -inf
nan = -nan
-nan = nan
Does this help?
a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8)
a = 5;
i=a++ + ++a + ++a; =>
i=5 + 7 + 8; (a=8)
The main point is that ++a
increments the value and immediately returns it.
a++
also increments the value (in the background) but returns unchanged value of the variable - what looks like it is executed later.
To forget directory recursively add /*/*
to the path:
git update-index --assume-unchanged wordpress/wp-content/uploads/*/*
Using git rm --cached
is not good for collaboration. More details here: How to stop tracking and ignore changes to a file in Git?
This way you get the intersection of two lists and also get the common duplicates.
>>> from collections import Counter
>>> a = Counter([1,2,3,4,5])
>>> b = Counter([1,3,5,6])
>>> a &= b
>>> list(a.elements())
[1, 3, 5]
<div class="divider-line-x"><span>Next section</span></div>
/***** Divider *****/
.divider-line-x {
position: relative;
text-align: center;
font-family: Arial;
font-weight: bold;
font-size: 12px;
color: #333;
border-bottom: 1px dashed #ccc;
}
.divider-line-x span {
position: relative;
top: 10px;
padding: 0 25px;
background: #fff;
}
data = (['President','George','Bush','is','.'],['O','B-PERSON','I-PERSON','O','O'])
corpus = []
for(doc,tags) in data:
doc_tag = []
for word,tag in zip(doc,tags):
doc_tag.append((word,tag))
corpus.append(doc_tag)
print(corpus)
You can also refine Hash::each
so it will support recursive enumeration. Here is my version of Hash::each
(Hash::each_pair
) with block and enumerator support:
module HashRecursive
refine Hash do
def each(recursive=false, &block)
if recursive
Enumerator.new do |yielder|
self.map do |key, value|
value.each(recursive=true).map{ |key_next, value_next| yielder << [[key, key_next].flatten, value_next] } if value.is_a?(Hash)
yielder << [[key], value]
end
end.entries.each(&block)
else
super(&block)
end
end
alias_method(:each_pair, :each)
end
end
using HashRecursive
Here are usage examples of Hash::each
with and without recursive
flag:
hash = {
:a => {
:b => {
:c => 1,
:d => [2, 3, 4]
},
:e => 5
},
:f => 6
}
p hash.each, hash.each {}, hash.each.size
# #<Enumerator: {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}:each>
# {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}
# 2
p hash.each(true), hash.each(true) {}, hash.each(true).size
# #<Enumerator: [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]:each>
# [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]
# 6
hash.each do |key, value|
puts "#{key} => #{value}"
end
# a => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# f => 6
hash.each(true) do |key, value|
puts "#{key} => #{value}"
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :b] => {:c=>1, :d=>[2, 3, 4]}
# [:a, :e] => 5
# [:a] => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# [:f] => 6
hash.each_pair(recursive=true) do |key, value|
puts "#{key} => #{value}" unless value.is_a?(Hash)
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :e] => 5
# [:f] => 6
Here is example from the question itself:
hash = {
1 => ["a", "b"],
2 => ["c"],
3 => ["a", "d", "f", "g"],
4 => ["q"]
}
hash.each(recursive=false) do |key, value|
puts "#{key} => #{value}"
end
# 1 => ["a", "b"]
# 2 => ["c"]
# 3 => ["a", "d", "f", "g"]
# 4 => ["q"]
Also take a look at my recursive version of Hash::merge
(Hash::merge!
) here.
In both examples, you are assigning a new int[10]
to a reference variable.
Assigning to a reference variable either way will be equal in performance.
int[] array = new int[10];
The notation above is considered best practice for readability.
Cheers
My solution,
load the app using
NODE_ENV=production node app.js
Then setup config.js
as a function rather than an object
module.exports = function(){
switch(process.env.NODE_ENV){
case 'development':
return {dev setting};
case 'production':
return {prod settings};
default:
return {error or other settings};
}
};
Then as per Jans solution load the file and create a new instance which we could pass in a value if needed, in this case process.env.NODE_ENV
is global so not needed.
var Config = require('./conf'),
conf = new Config();
Then we can access the config object properties exactly as before
conf.twitter.consumerKey
I'm not really a fan of the most-upvoted answer here (in part because it seems like it isn't correct since it should continue
if it reads a null terminator in either string--but not both strings at once--and it doesn't do this), so I wrote my own.
strncmp()
, and has been tested with numerous test cases, as shown below.It is identical to strncmp()
except:
strncmp()
has undefined behavior if either string is a null ptr (see: https://en.cppreference.com/w/cpp/string/byte/strncmp).INT_MIN
as a special sentinel error value if either input string is a NULL
ptr.LIMITATIONS: Note that this code works on the original 7-bit ASCII character set only (decimal values 0 to 127, inclusive), NOT on unicode characters, such as unicode character encodings UTF-8 (the most popular), UTF-16, and UTF-32.
Here is the code only (no comments):
int strncmpci(const char * str1, const char * str2, size_t num)
{
int ret_code = 0;
size_t chars_compared = 0;
if (!str1 || !str2)
{
ret_code = INT_MIN;
return ret_code;
}
while ((chars_compared < num) && (*str1 || *str2))
{
ret_code = tolower((int)(*str1)) - tolower((int)(*str2));
if (ret_code != 0)
{
break;
}
chars_compared++;
str1++;
str2++;
}
return ret_code;
}
Fully-commented version:
/// \brief Perform a case-insensitive string compare (`strncmp()` case-insensitive) to see
/// if two C-strings are equal.
/// \note 1. Identical to `strncmp()` except:
/// 1. It is case-insensitive.
/// 2. The behavior is NOT undefined (it is well-defined) if either string is a null
/// ptr. Regular `strncmp()` has undefined behavior if either string is a null ptr
/// (see: https://en.cppreference.com/w/cpp/string/byte/strncmp).
/// 3. It returns `INT_MIN` as a special sentinel value for certain errors.
/// - Posted as an answer here: https://stackoverflow.com/a/55293507/4561887.
/// - Aided/inspired, in part, by `strcicmp()` here:
/// https://stackoverflow.com/a/5820991/4561887.
/// \param[in] str1 C string 1 to be compared.
/// \param[in] str2 C string 2 to be compared.
/// \param[in] num max number of chars to compare
/// \return A comparison code (identical to `strncmp()`, except with the addition
/// of `INT_MIN` as a special sentinel value):
///
/// INT_MIN (usually -2147483648 for int32_t integers) Invalid arguments (one or both
/// of the input strings is a NULL pointer).
/// <0 The first character that does not match has a lower value in str1 than
/// in str2.
/// 0 The contents of both strings are equal.
/// >0 The first character that does not match has a greater value in str1 than
/// in str2.
int strncmpci(const char * str1, const char * str2, size_t num)
{
int ret_code = 0;
size_t chars_compared = 0;
// Check for NULL pointers
if (!str1 || !str2)
{
ret_code = INT_MIN;
return ret_code;
}
// Continue doing case-insensitive comparisons, one-character-at-a-time, of `str1` to `str2`, so
// long as 1st: we have not yet compared the requested number of chars, and 2nd: the next char
// of at least *one* of the strings is not zero (the null terminator for a C-string), meaning
// that string still has more characters in it.
// Note: you MUST check `(chars_compared < num)` FIRST or else dereferencing (reading) `str1` or
// `str2` via `*str1` and `*str2`, respectively, is undefined behavior if you are reading one or
// both of these C-strings outside of their array bounds.
while ((chars_compared < num) && (*str1 || *str2))
{
ret_code = tolower((int)(*str1)) - tolower((int)(*str2));
if (ret_code != 0)
{
// The 2 chars just compared don't match
break;
}
chars_compared++;
str1++;
str2++;
}
return ret_code;
}
Download the entire sample code, with unit tests, from my eRCaGuy_hello_world repository here: "strncmpci.c":
(this is just a snippet)
int main()
{
printf("-----------------------\n"
"String Comparison Tests\n"
"-----------------------\n\n");
int num_failures_expected = 0;
printf("INTENTIONAL UNIT TEST FAILURE to show what a unit test failure looks like!\n");
EXPECT_EQUALS(strncmpci("hey", "HEY", 3), 'h' - 'H');
num_failures_expected++;
printf("------ beginning ------\n\n");
const char * str1;
const char * str2;
size_t n;
// NULL ptr checks
EXPECT_EQUALS(strncmpci(NULL, "", 0), INT_MIN);
EXPECT_EQUALS(strncmpci("", NULL, 0), INT_MIN);
EXPECT_EQUALS(strncmpci(NULL, NULL, 0), INT_MIN);
EXPECT_EQUALS(strncmpci(NULL, "", 10), INT_MIN);
EXPECT_EQUALS(strncmpci("", NULL, 10), INT_MIN);
EXPECT_EQUALS(strncmpci(NULL, NULL, 10), INT_MIN);
EXPECT_EQUALS(strncmpci("", "", 0), 0);
EXPECT_EQUALS(strncmp("", "", 0), 0);
str1 = "";
str2 = "";
n = 0;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hey";
str2 = "HEY";
n = 0;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hey";
str2 = "HEY";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'h' - 'H');
str1 = "heY";
str2 = "HeY";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'h' - 'H');
str1 = "hey";
str2 = "HEdY";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 'y' - 'd');
EXPECT_EQUALS(strncmp(str1, str2, n), 'h' - 'H');
str1 = "heY";
str2 = "hEYd";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'e' - 'E');
str1 = "heY";
str2 = "heyd";
n = 6;
EXPECT_EQUALS(strncmpci(str1, str2, n), -'d');
EXPECT_EQUALS(strncmp(str1, str2, n), 'Y' - 'y');
str1 = "hey";
str2 = "hey";
n = 6;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hey";
str2 = "heyd";
n = 6;
EXPECT_EQUALS(strncmpci(str1, str2, n), -'d');
EXPECT_EQUALS(strncmp(str1, str2, n), -'d');
str1 = "hey";
str2 = "heyd";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hEY";
str2 = "heyYOU";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'E' - 'e');
str1 = "hEY";
str2 = "heyYOU";
n = 10;
EXPECT_EQUALS(strncmpci(str1, str2, n), -'y');
EXPECT_EQUALS(strncmp(str1, str2, n), 'E' - 'e');
str1 = "hEYHowAre";
str2 = "heyYOU";
n = 10;
EXPECT_EQUALS(strncmpci(str1, str2, n), 'h' - 'y');
EXPECT_EQUALS(strncmp(str1, str2, n), 'E' - 'e');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE TO MEET YOU.,;", 100), 0);
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "NICE TO MEET YOU.,;", 100), 'n' - 'N');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice to meet you.,;", 100), 0);
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE TO UEET YOU.,;", 100), 'm' - 'u');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice to uEET YOU.,;", 100), 'm' - 'u');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice to UEET YOU.,;", 100), 'm' - 'U');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE TO MEET YOU.,;", 5), 0);
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "NICE TO MEET YOU.,;", 5), 'n' - 'N');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE eo UEET YOU.,;", 5), 0);
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice eo uEET YOU.,;", 5), 0);
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE eo UEET YOU.,;", 100), 't' - 'e');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice eo uEET YOU.,;", 100), 't' - 'e');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "nice-eo UEET YOU.,;", 5), ' ' - '-');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice-eo UEET YOU.,;", 5), ' ' - '-');
if (globals.error_count == num_failures_expected)
{
printf(ANSI_COLOR_GRN "All unit tests passed!" ANSI_COLOR_OFF "\n");
}
else
{
printf(ANSI_COLOR_RED "FAILED UNIT TESTS! NUMBER OF UNEXPECTED FAILURES = %i"
ANSI_COLOR_OFF "\n", globals.error_count - num_failures_expected);
}
assert(globals.error_count == num_failures_expected);
return globals.error_count;
}
$ gcc -Wall -Wextra -Werror -ggdb -std=c11 -o ./bin/tmp strncmpci.c && ./bin/tmp ----------------------- String Comparison Tests ----------------------- INTENTIONAL UNIT TEST FAILURE to show what a unit test failure looks like! FAILED at line 250 in function main! strncmpci("hey", "HEY", 3) != 'h' - 'H' a: strncmpci("hey", "HEY", 3) is 0 b: 'h' - 'H' is 32 ------ beginning ------ All unit tests passed!
A simple solution using fscanf
:
void read_ints (const char* file_name)
{
FILE* file = fopen (file_name, "r");
int i = 0;
fscanf (file, "%d", &i);
while (!feof (file))
{
printf ("%d ", i);
fscanf (file, "%d", &i);
}
fclose (file);
}
It is terrible, but you can try to use
select
SUBSTRING(Table1.Col1,0,PATINDEX('%|%=',Table1.Col1)) as myString
from
Table1
This code is probably not 100% right though. need to be adjusted
I found this post trying to figure why I kept getting the following error which is explained by the other answers.
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
Use a nullable DateTime object.
public DateTime? PurchaseDate { get; set; }
If you are using entity framework Set the nullable property in the edmx file to True
If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.
Here an example:
print ('This is \x1b[31mred\x1b[0m.')
980 is not the "defacto standard", you'll generally see most people targeting a size a little bit less than 1024px wide to account for browser chrome such as scrollbars, etc.
Usually people target between 960 and 990px wide. Often people use a grid system (like 960.gs) which is opinionated about what the default width should be.
Also note, just recently the most common screen size now averages quite a bit bigger than 1024px wide, ranking in at 1366px wide. See http://techcrunch.com/2012/04/11/move-over-1024x768-the-most-popular-screen-resolution-on-the-web-is-now-1366x768/
What had worked for me with PHP version 5.2.8, was to open up php.ini
and allow the php_mcrypt.dll
extension by removing the ;
, i.e. changing:
;extension=php_mcrypt.dll
to extension=php_mcrypt.dll
You have to configure a CORS policy at application startup in the ConfigureServices
method:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
// ...
}
The CorsPolicyBuilder
in builder
allows you to configure the policy to your needs. You can now use this name to apply the policy to controllers and actions:
[EnableCors("MyPolicy")]
Or apply it to every request:
public void Configure(IApplicationBuilder app)
{
app.UseCors("MyPolicy");
// ...
// This should always be called last to ensure that
// middleware is registered in the correct order.
app.UseMvc();
}
As Sagiv b.g. pointed out, the npm start
command is a shortcut for npm run start
. I just wanted to add a real-life example to clarify it a bit more.
The setup below comes from the create-react-app
github repo. The package.json
defines a bunch of scripts which define the actual flow.
"scripts": {
"start": "npm-run-all -p watch-css start-js",
"build": "npm run build-css && react-scripts build",
"watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
"build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
"start-js": "react-scripts start"
},
For clarity, I added a diagram.
The blue boxes are references to scripts, all of which you could executed directly with an npm run <script-name>
command. But as you can see, actually there are only 2 practical flows:
npm run start
npm run build
The grey boxes are commands which can be executed from the command line.
So, for instance, if you run npm start
(or npm run start
) that actually translate to the npm-run-all -p watch-css start-js
command, which is executed from the commandline.
In my case, I have this special npm-run-all
command, which is a popular plugin that searches for scripts that start with "build:", and executes all of those. I actually don't have any that match that pattern. But it can also be used to run multiple commands in parallel, which it does here, using the -p <command1> <command2>
switch. So, here it executes 2 scripts, i.e. watch-css
and start-js
. (Those last mentioned scripts are watchers which monitor file changes, and will only finish when killed.)
The watch-css
makes sure that the *.scss
files are translated to *.css
files, and looks for future updates.
The start-js
points to the react-scripts start
which hosts the website in a development mode.
In conclusion, the npm start
command is configurable. If you want to know what it does, then you have to check the package.json
file. (and you may want to make a little diagram when things get complicated).
Nevermind everyone, I managed to solve the problem by adding an additional div between the wrapper and box.
CSS
#wrapper {
position: absolute;
}
#middle {
border-radius: 100px;
overflow: hidden;
}
#box {
width: 300px; height: 300px;
background-color: #cde;
}
HTML
<div id="wrapper">
<div id="middle">
<div id="box"></div>
</div>
</div>
Thanks everyone who helped!
It will overflow and wrap around to Long.MIN_VALUE
.
Its not too likely though. Even if you increment 1,000,000 times per second it will take about 300,000 years to overflow.
Just get the position of the last character occurrence.
for(String serverId : serverIds) {
sb.append(serverId);
sb.append(",");
}
sb.deleteCharAt(sb.lastIndexOf(","));
Since lastIndexOf
will perform a reverse search, and you know that it will find at the first try, performance won't be an issue here.
EDIT
Since I keep getting ups on my answer (thanks folks ), it is worth regarding that:
On Java 8 onward it would just be more legible and explicit to use StringJoiner. It has one method for a simple separator, and an overload for prefix and suffix.
Examples taken from here: example
Example using simple separator:
StringJoiner mystring = new StringJoiner("-"); // Joining multiple strings by using add() method mystring.add("Logan"); mystring.add("Magneto"); mystring.add("Rogue"); mystring.add("Storm"); System.out.println(mystring);
Output:
Logan-Magneto-Rogue-Storm
Example with suffix and prefix:
StringJoiner mystring = new StringJoiner(",", "(", ")"); // Joining multiple strings by using add() method mystring.add("Negan"); mystring.add("Rick"); mystring.add("Maggie"); mystring.add("Daryl"); System.out.println(mystring);
Output
(Negan,Rick,Maggie,Daryl)
You can now do this without the use of Android SDK.
In the latest version of chrome (I am working on 34.0.x):
chrome://inspect/
Discover USB Devices
There will now be an item on the chrome://inspect/
pages for your phone, and you can click inspect
. Dev tools will spawn and voila!
I extended Ronnie's answer with a fluent implementation so you can use it like so:
dm.Context.SetCommandTimeout(120).Database.SqlQuery...
public static class EF
{
public static DbContext SetCommandTimeout(this DbContext db, TimeSpan? timeout)
{
((IObjectContextAdapter)db).ObjectContext.CommandTimeout = timeout.HasValue ? (int?) timeout.Value.TotalSeconds : null;
return db;
}
public static DbContext SetCommandTimeout(this DbContext db, int seconds)
{
return db.SetCommandTimeout(TimeSpan.FromSeconds(seconds));
}
}
new[]
std::vector
, for example, to prevent careless programmers from accidentally introducing copiesThere is a general rule that C++ containers are to be preferred over rolling-your-own with pointers. It is a general rule; it has exceptions. There's more; these are just examples.
Uncomment this line (in /conf/logging.properties
)
org.apache.jasper.compiler.TldLocationsCache.level = FINE
Work's for me in tomcat 7.0.53!
http://msdn.microsoft.com/en-us/library/system.convert.aspx
l1 = Convert.ToInt64(strValue)
Though the example you gave isn't an integer, so I'm not sure why you want it as a long.
In the interest of coverage. I put forward an implementation using lambda expressions.
C++11
#include <vector>
#include <algorithm>
using namespace std;
vector< MyStruct > values;
sort( values.begin( ), values.end( ), [ ]( const MyStruct& lhs, const MyStruct& rhs )
{
return lhs.key < rhs.key;
});
C++14
#include <vector>
#include <algorithm>
using namespace std;
vector< MyStruct > values;
sort( values.begin( ), values.end( ), [ ]( const auto& lhs, const auto& rhs )
{
return lhs.key < rhs.key;
});
FWIW CloudFront supports streaming as well. Might be better than plain streaming from instances.
In 2019 you can use querySelector for that.
It's supported by most browsers (https://caniuse.com/#search=querySelector)
document.querySelector('body').appendChild(i);
I was curious about this as well and found a few interesting articles. I may not answer your question to its full extent, but this at least provides some more information.
http://restful-api-design.readthedocs.org/en/latest/methods.html
The HTTP RFC specifies that PUT must take a full new resource representation as the request entity. This means that if for example only certain attributes are provided, those should be remove (i.e. set to null).
Given that, then a PUT should send the entire object. For instance,
/users/1
PUT {id: 1, username: 'skwee357', email: '[email protected]'}
This would effectively update the email. The reason PUT may not be too effective is that your only really modifying one field and including the username is kind of useless. The next example shows the difference.
/users/1
PUT {id: 1, email: '[email protected]'}
Now, if the PUT was designed according the spec, then the PUT would set the username to null and you would get the following back.
{id: 1, username: null, email: '[email protected]'}
When you use a PATCH, you only update the field you specify and leave the rest alone as in your example.
The following take on the PATCH is a little different than I have never seen before.
http://williamdurand.fr/2014/02/14/please-do-not-patch-like-an-idiot/
The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it also MAY have side effects on other resources; i.e., new resources may be created, or existing ones modified, by the application of a PATCH.
PATCH /users/123
[
{ "op": "replace", "path": "/email", "value": "[email protected]" }
]
You are more or less treating the PATCH as a way to update a field. So instead of sending over the partial object, you're sending over the operation. i.e. Replace email with value.
The article ends with this.
It is worth mentioning that PATCH is not really designed for truly REST APIs, as Fielding's dissertation does not define any way to partially modify resources. But, Roy Fielding himself said that PATCH was something [he] created for the initial HTTP/1.1 proposal because partial PUT is never RESTful. Sure you are not transferring a complete representation, but REST does not require representations to be complete anyway.
Now, I don't know if I particularly agree with the article as many commentators point out. Sending over a partial representation can easily be a description of the changes.
For me, I am mixed on using PATCH. For the most part, I will treat PUT as a PATCH since the only real difference I have noticed so far is that PUT "should" set missing values to null. It may not be the 'most correct' way to do it, but good luck coding perfect.
I agree with Jon about having a hash of actions to class name. If you keep your pattern, you might want to consider using the "as" construct instead:
A a = o as A;
if (a != null) {
a.Hop();
return;
}
B b = o as B;
if (b != null) {
b.Skip();
return;
}
throw new ArgumentException("...");
The difference is that when you use the patter if (foo is Bar) { ((Bar)foo).Action(); } you're doing the type casting twice. Now maybe the compiler will optimize and only do that work once - but I wouldn't count on it.
i'd rather go to menu source em click on "Cleanup Document"
Here is the actual implementation of both methods ( decompiled using dotPeek)
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool IsNullOrEmpty(string value)
{
if (value != null)
return value.Length == 0;
else
return true;
}
/// <summary>
/// Indicates whether a specified string is null, empty, or consists only of white-space characters.
/// </summary>
///
/// <returns>
/// true if the <paramref name="value"/> parameter is null or <see cref="F:System.String.Empty"/>, or if <paramref name="value"/> consists exclusively of white-space characters.
/// </returns>
/// <param name="value">The string to test.</param>
public static bool IsNullOrWhiteSpace(string value)
{
if (value == null)
return true;
for (int index = 0; index < value.Length; ++index)
{
if (!char.IsWhiteSpace(value[index]))
return false;
}
return true;
}
YES, you can, because undefined is defined as undefined.
console.log(
/*global.*/undefined === window['undefined'] &&
/*global.*/undefined === (function(){})() &&
window['undefined'] === (function(){})()
) //true
your case:
test("value1", undefined, "value2")
you can also create your own undefined variable:
Object.defineProperty(this, 'u', {value : undefined});
console.log(u); //undefined
If you want multiple string replacement:
NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo
Check the Bit Twiddling Hacks. You need to get the base 2 logarithm, then add 1 to that. Example for a 32-bit value:
Round up to the next highest power of 2
unsigned int v; // compute the next highest power of 2 of 32-bit v v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++;
The extension to other widths should be obvious.
Expanding on @lhunath's and @GregV's answers, here's the code for the people who want to easily put that check inside an if
statement:
exists()
{
command -v "$1" >/dev/null 2>&1
}
Here's how to use it:
if exists bash; then
echo 'Bash exists!'
else
echo 'Your system does not have Bash'
fi
What you need is a jQuery UI Datepicker
Check out the demo and the source code.
You can also use this (based on a few of the above answers):
file = open('filename.txt', 'w')
file.close()
of course this is a really bad way to clear a file because it requires so many lines of code, but I just wrote this to show you that it can be done in this method too.
happy coding!
If you don't "care" about the data you can just do something like:
search_params = params[:search].valid_encoding? ? params[:search].gsub(/\W+/, '') : "nothing"
I just used valid_encoding?
to get passed it. Mine is a search field, and so i was finding the same weirdness over and over so I used something like: just to have the system not break. Since i don't control the user experience to autovalidate prior to sending this info (like auto feedback to say "dummy up!") I can just take it in, strip it out and return blank results.
I use a way that may look stupid but it works for me. I simply concat the columns I want to compare and use NOT IN:
SELECT *
FROM table1 t1
WHERE CONCAT(t1.first_name,t1.last_name) NOT IN (SELECT CONCAT(t2.first_name,t2.last_name) FROM table2 t2)
After inspecting closely, looks like both of you are using closure.
In your friends case, i
is accessed inside anonymous function 1 and i2
is accessed in anonymous function 2 where the console.log
is present.
In your case you are accessing i2
inside anonymous function where console.log
is present. Add a debugger;
statement before console.log
and in chrome developer tools under "Scope variables" it will tell under what scope the variable is.
In Java you can only import class Names, or static methods/fields.
To import class use
import full.package.name.of.SomeClass;
to import static methods/fields use
import static full.package.name.of.SomeClass.staticMethod;
import static full.package.name.of.SomeClass.staticField;
I wish there was a way to do this without additional modules for something so minuscule and common, but this is the best I could come up with.
Update: Should now work on Windows (tested Windows 10), and should also work on Linux/Unix/BSD/Mac systems.
const
execSync = require("child_process").execSync,
fs = require("fs"),
os = require("os");
let removeDirCmd, theDir;
removeDirCmd = os.platform() === 'win32' ? "rmdir /s /q " : "rm -rf ";
theDir = __dirname + "/../web-ui/css/";
// WARNING: Do not specify a single file as the windows rmdir command will error.
if (fs.existsSync(theDir)) {
console.log(' removing the ' + theDir + ' directory.');
execSync(removeDirCmd + '"' + theDir + '"', function (err) {
console.log(err);
});
}
UPDATE
By Android Support Library 23.2 update, all WRAP_CONTENT should work correctly.
Please update version of a library in gradle file.
compile 'com.android.support:recyclerview-v7:23.2.0'
Original Answer
As answered on other question, you need to use original onMeasure() method when your recycler view height is bigger than screen height. This layout manager can calculate ItemDecoration and can scroll with more.
public class MyLinearLayoutManager extends LinearLayoutManager {
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
// If child view is more than screen size, there is no need to make it wrap content. We can use original onMeasure() so we can scroll view.
if (height < heightSize && width < widthSize) {
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
} else {
super.onMeasure(recycler, state, widthSpec, heightSpec);
}
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
// For adding Item Decor Insets to view
super.measureChildWithMargins(view, 0, 0);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight() + getDecoratedLeft(view) + getDecoratedRight(view), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom() + getPaddingBottom() + getDecoratedBottom(view) , p.height);
view.measure(childWidthSpec, childHeightSpec);
// Get decorated measurements
measuredDimension[0] = getDecoratedMeasuredWidth(view) + p.leftMargin + p.rightMargin;
measuredDimension[1] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}
}
original answer : https://stackoverflow.com/a/28510031/1577792
find out commit id
git reflog
recover local branch you deleted by mistake
git branch need-recover-branch-name commitId
push need-recover-branch-name again if you deleted remote branch too before
git push origin need-recover-branch-name
Try DBVis - download at https://www.dbvis.com/download - there is a pro version (not needed) and a open version that should suffice.
All you have to do is to get the right JDBC - database driver for SQL Server, the tool shows tables and references orthogonal, hierarchical, in a circle ;-) etc. just by pressing one single button. I use the free version for years now.
Okay, my problem wasn't the port, but the binding address. My server has an internal address (10.0.0.4) and an external address (52.175.223.XX). When I tried connecting with:
$sock = @stream_socket_server('tcp://52.175.223.XX:123', $errNo, $errStr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN);
It failed because the local socket was 10.0.0.4 and not the external 52.175.223.XX. You can checkout the local available interfaces with sudo ifconfig
.
Updated code:
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.your_color)));
Here you have another solution based on the one provided by @tarheel
function onEdit() {
var sheetWithNestedSelectsName = "Sitemap";
var columnWithNestedSelectsRoot = 1;
var sheetWithOptionPossibleValuesSuffix = "TabSections";
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = SpreadsheetApp.getActiveSheet();
// If we're not in the sheet with nested selects, exit!
if ( activeSheet.getName() != sheetWithNestedSelectsName ) {
return;
}
var activeCell = SpreadsheetApp.getActiveRange();
// If we're not in the root column or a content row, exit!
if ( activeCell.getColumn() != columnWithNestedSelectsRoot || activeCell.getRow() < 2 ) {
return;
}
var sheetWithActiveOptionPossibleValues = activeSpreadsheet.getSheetByName( activeCell.getValue() + sheetWithOptionPossibleValuesSuffix );
// Get all possible values
var activeOptionPossibleValues = sheetWithActiveOptionPossibleValues.getSheetValues( 1, 1, -1, 1 );
var possibleValuesValidation = SpreadsheetApp.newDataValidation();
possibleValuesValidation.setAllowInvalid( false );
possibleValuesValidation.requireValueInList( activeOptionPossibleValues, true );
activeSheet.getRange( activeCell.getRow(), activeCell.getColumn() + 1 ).setDataValidation( possibleValuesValidation.build() );
}
It has some benefits over the other approach:
So, how to use it:
Enjoy!
Wouldn't lambdaj's project function do what you are looking for?
It'll look something like this:
List<UserDTO> userNDtos = project(users, UserDTO.class, on(User.class).getUserName(), on(User.class).getFullName(), .....);
(Define the constructor for UserDTO accordingly...)
Also see here for examples...
The dataframe.sort() method is - so my understanding - deprecated in pandas > 0.18. In order to solve your problem you should use dataframe.sort_values() instead:
f.sort_values(by=["c1","c2"], ascending=[False, True])
The output looks like this:
c1 c2
3 10
2 15
2 30
2 100
1 20
There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.
Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.
import Tkinter as tk
root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")
frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")
root.mainloop()
This is Java. You have to make your own tailored Pair class with descriptive class and field names, and not to mind that you will reinvent the wheel by writing hashCode()/equals() or implementing Comparable again and again.
The connection string generated by the project containing the .edmx file generates the connection string, this would appear to be a holdover from the app.config sorts of files that were copied to the output directory and referenced by the executable to store runtime config information.
This breaks in the web project as there is no automatic process to add random .config information into the web.config file for the web project.
Easiest is to copy the connection string from the config file to the connections section of the web.config file and disregard the config file contents.
@KyleMit's answer on Bootstrap 4 has changed a little
<div class="input-group">
<input type="text" class="form-control">
<div class="input-group-prepend">
<span class="input-group-text">-</span>
</div>
<input type="text" class="form-control">
</div>
First download the dex2jar tool from Following link http://code.google.com/p/dex2jar/downloads/list
Extract the file it create dex2jar
folder
Now you pick your apk file and change its extension .apk to .zip after changing extension it seems to be zip file then extract this zip file you found classes.dex
file
Now pick classes.dex file and put it into dex2jar
folder
Now open cmd window and type the path of dex2jar
folder
Now type the command dex2jar.bat classes.dex
and press Enter
Now Open the dex2jar
folder you found classes_dex2jar.jar
file
Next you download the java decompiler tool from the following link http://java.decompiler.free.fr/?q=jdgui
Last Step Open the file classes_dex2jar.jar
in java decompiler tool now you can see apk code
Not sure what you meant, but you can permanently turn showing whitespaces on and off in Settings -> Editor -> General -> Appearance -> Show whitespaces
.
Also, you can set it for a current file only in View -> Active Editor -> Show WhiteSpaces
.
Edit:
Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to give it a try.
Use DATESTR
>> datestr(40189)
ans =
12-Jan-0110
Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM
>> datenum(2010,1,11)
ans =
734149
>> datenum(2010,1,11)-40189
ans =
693960
>> datestr(40189+693960)
ans =
11-Jan-2010
In other words, to convert any serial Excel date, call
datestr(excelSerialDate + 693960)
EDIT
To get the date in mm/dd/yyyy format, call datestr
with the specified format
excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010
Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things
excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010
set variable as
@JsonIgnore
This allows variable to get skipped by json serializer
From http://docs.python-requests.org/en/latest/user/quickstart/
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get
or .post
method.
So more specific to your question:
headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)
My solution is change module name in "AppDelegate.m"
from
moduleName:@"AwesomeProject"
to
moduleName:@"YourNewProjectName"
Some scenarios don't always allow developers to switch scripting language.
My preference is definitely for JavaScript (and I have used it in new projects). However, maintaining older projects is still required and necessary. Unfortunately, these are written in VBScript.
So even though this solution doesn't offer true "try/catch" functionaility, the result is the same, and that's good enough for me to get the job done.
At eBay it’s the kabob.
Also heard it called the snowman or sushi roll.
A less robust approach, but it works.
a = [2, 4, 5].toString();
b = [2, 4, 5].toString();
console.log(a===b);
select
Field1, Field2...
from
Table1
order by
isnumeric(Field1) desc,
case when isnumeric(Field1) = 1 then cast(Field1 as int) else null end,
Field1
This will return values in the order you gave in your question.
Performance won't be too great with all that casting going on, so another approach is to add another column to the table in which you store an integer copy of the data and then sort by that first and then the column in question. This will obviously require some changes to the logic that inserts or updates data in the table, to populate both columns. Either that, or put a trigger on the table to populate the second column whenever data is inserted or updated.
DFS APPROACH WITH A CONDITION(parent != next node) Let's see the code and then understand what's going on :
bool Graph::isCyclicUtil(int v, bool visited[], int parent)
{
// Mark the current node as visited
visited[v] = true;
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
{
// If an adjacent is not visited, then recur for that adjacent
if (!visited[*i])
{
if (isCyclicUtil(*i, visited, v))
return true;
}
// If an adjacent is visited and not parent of current vertex,
// then there is a cycle.
else if (*i != parent)
return true;
}
return false;
}
The above code explains itself but I will try to explain one condition i.e *i != parent Here if suppose graph is
1--2
Then when we are at 1 and goes to 2, the parent for 2 becomes 1 and when we go back to 1 as 1 is in adj matrix of 2 then since next vertex 1 is also the parent of 2 Therefore cycle will not be detected for the immediate parent in this DFS approach. Hence Code works fine
The ECMAscript standard does not specify which sort algorithm is to be used. Indeed, different browsers feature different sort algorithms. For example, Mozilla/Firefox's sort() is not stable (in the sorting sense of the word) when sorting a map. IE's sort() is stable.
RewriteEngine On
RewriteCond %{SERVER_PORT} 443
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
It's the directory where java
was run from, where you started the JVM. Does not have to be within the user's home directory. It can be anywhere where the user has permission to run java.
So if you cd
into /somedir
, then run your program, user.dir
will be /somedir
.
A different property, user.home
, refers to the user directory. As in /Users/myuser
or /home/myuser
or C:\Users\myuser
.
See here for a list of system properties and their descriptions.
So i tried all the suggested solutions to no avail. All i did was to set run the app from the server and it displayed the error in full, this should have worked when i set customErrors mode to false but it didn't. The moment i browsed the API form the server i was able to see the problem.
Make sure the main
in public static void main(String[] args)
is lower case. For me it didn't work when I had it with capital letter.
It is worth noting that git also has a syntax for tracking "from-where-you-came"/"want-to-go-back-now" - for example, HEAD@{1}
will reference the place from where you jumped to new commit location.
Basically HEAD@{}
variables capture the history of HEAD movement, and you can decide to use a particular head by looking into reflogs of git using the command git reflog
.
Example:
0aee51f HEAD@{0}: reset: moving to HEAD@{5}
290e035 HEAD@{1}: reset: moving to HEAD@{7}
0aee51f HEAD@{2}: reset: moving to HEAD@{3}
290e035 HEAD@{3}: reset: moving to HEAD@{3}
9e77426 HEAD@{4}: reset: moving to HEAD@{3}
290e035 HEAD@{5}: reset: moving to HEAD@{3}
0aee51f HEAD@{6}: reset: moving to HEAD@{3}
290e035 HEAD@{7}: reset: moving to HEAD@{3}
9e77426 HEAD@{8}: reset: moving to HEAD@{3}
290e035 HEAD@{9}: reset: moving to HEAD@{1}
0aee51f HEAD@{10}: reset: moving to HEAD@{4}
290e035 HEAD@{11}: reset: moving to HEAD^
9e77426 HEAD@{12}: reset: moving to HEAD^
eb48179 HEAD@{13}: reset: moving to HEAD~
f916d93 HEAD@{14}: reset: moving to HEAD~
0aee51f HEAD@{15}: reset: moving to HEAD@{5}
f19fd9b HEAD@{16}: reset: moving to HEAD~1
290e035 HEAD@{17}: reset: moving to HEAD~2
eb48179 HEAD@{18}: reset: moving to HEAD~2
0aee51f HEAD@{19}: reset: moving to HEAD@{5}
eb48179 HEAD@{20}: reset: moving to HEAD~2
0aee51f HEAD@{21}: reset: moving to HEAD@{1}
f916d93 HEAD@{22}: reset: moving to HEAD@{1}
0aee51f HEAD@{23}: reset: moving to HEAD@{1}
f916d93 HEAD@{24}: reset: moving to HEAD^
0aee51f HEAD@{25}: commit (amend): 3rd commmit
35a7332 HEAD@{26}: checkout: moving from temp2_new_br to temp2_new_br
35a7332 HEAD@{27}: commit (amend): 3rd commmit
72c0be8 HEAD@{28}: commit (amend): 3rd commmit
An example could be that I did local-commits a->b->c->d and then I went back discarding 2 commits to check my code - git reset HEAD~2
- and then after that I want to move my HEAD back to d - git reset HEAD@{1}
.
There is a simple function subtract
which moment library gives us to subtract time from some time.
Using it is also very simple.
moment(Date.now()).subtract(7, 'days'); // This will subtract 7 days from current time
moment(Date.now()).subtract(3, 'd'); // This will subtract 3 days from current time
//You can do this for days, years, months, hours, minutes, seconds
//You can also subtract multiple things simulatneously
//You can chain it like this.
moment(Date.now()).subtract(3, 'd').subtract(5. 'h'); // This will subtract 3 days and 5 hours from current time
//You can also use it as object literal
moment(Date.now()).subtract({days:3, hours:5}); // This will subtract 3 days and 5 hours from current time
Hope this helps!
You can wrap a constant in a numpy array, flag it write only, and always call it by index zero.
import numpy as np
# declare a constant
CONSTANT = 'hello'
# put constant in numpy and make read only
CONSTANT = np.array([CONSTANT])
CONSTANT.flags.writeable = False
# alternatively: CONSTANT.setflags(write=0)
# call our constant using 0 index
print 'CONSTANT %s' % CONSTANT[0]
# attempt to modify our constant with try/except
new_value = 'goodbye'
try:
CONSTANT[0] = new_value
except:
print "cannot change CONSTANT to '%s' it's value '%s' is immutable" % (
new_value, CONSTANT[0])
# attempt to modify our constant producing ValueError
CONSTANT[0] = new_value
>>>
CONSTANT hello
cannot change CONSTANT to 'goodbye' it's value 'hello' is immutable
Traceback (most recent call last):
File "shuffle_test.py", line 15, in <module>
CONSTANT[0] = new_value
ValueError: assignment destination is read-only
of course this only protects the contents of the numpy, not the variable "CONSTANT" itself; you can still do:
CONSTANT = 'foo'
and CONSTANT
would change, however that would quickly throw an TypeError the first time CONSTANT[0]
is later called in the script.
although... I suppose if you at some point changed it to
CONSTANT = [1,2,3]
now you wouldn't get the TypeError anymore. hmmmm....
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.setflags.html
You can still using the devil logic of setting options depending on your current Tmux version: see my previous answer.
But since Tmux v1.7, set-option
adds "-q" to silence errors and not print out anything (see changelog).
I recommend to use this feature, it's more readable and easily expandable.
Add this to your ~/.tmux.conf
:
# from v2.1
set -gq mouse on
# before v2.1
set -gq mode-mouse on
set -gq mouse-resize-pane on
set -gq mouse-select-pane on
set -gq mouse-select-window on
Restar tmux or source-file
your new .tmux.conf
Side note: I'm open to remove my old answer if people prefer this one
If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:
PARAMETERS SomeParam Text(10);
SELECT Field FROM Table
WHERE OtherField=SomeParam
You can also say:
CREATE PROCEDURE ProcedureName
(Parameter1 datatype, Parameter2 datatype) AS
SQLStatement
From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs
Note that the procedure contains only one statement.