I think the easiest way to do that is to use so called projection. It can map query results to interfaces. Using SqlResultSetMapping
is inconvienient and makes your code ugly :).
An example right from spring data JPA source code:
public interface UserRepository extends JpaRepository<User, Integer> {
@Query(value = "SELECT firstname, lastname FROM SD_User WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);
public static interface NameOnly {
String getFirstname();
String getLastname();
}
}
You can also use this method to get a list of projections.
Check out this spring data JPA docs entry for more info about projections.
Note 1:
Remember to have your User
entity defined as normal - the fields from projected interface must match fields in this entity. Otherwise field mapping might be broken (getFirstname()
might return value of last name et cetera).
Note 2:
If you use SELECT table.column ...
notation always define aliases matching names from entity. For example this code won't work properly (projection will return nulls for each getter):
@Query(value = "SELECT user.firstname, user.lastname FROM SD_User user WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);
But this works fine:
@Query(value = "SELECT user.firstname AS firstname, user.lastname AS lastname FROM SD_User user WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);
In case of more complex queries I'd rather use JdbcTemplate
with custom repository instead.
I am assuming you know the length of the part before the _
and after the underscore, as well as the extension. If you don't it might be more complex than a simple substring.
cd C:\path\to\the\files
for /f %%a IN ('dir /b *.jpg') do (
set p=%a:~0,3%
set q=%a:~4,4%
set b=%p_%q.jpg
ren %a %b
)
I just came up with this script, and I did not test it. Check out this and that for more info.
IF you want to assume you don't know the positions of the _
and the lengths and the extension, I think you could do something with for loops to check the index of the _
, then the last index of the .
, wrap it in a goto
thing and make it work. If you're willing to go through that trouble, I'd suggest you use WindowsPowerShell (or Cygwin) at least (for your own sake) or install a more advanced scripting language (think Python/Perl) you'll get more support either way.
check this question and the selected answer: Stop EditText from gaining focus at Activity startup It's ugly but it works, and as far as I know there's no better solution.
C++0x only:
vector<int> v; // and fill with data
int sum {}; // or = 0 ... :)
for (int n : v) sum += n;
This is similar to the BOOST_FOREACH mentioned elsewhere and has the same benefit of clarity in more complex situations, compared to stateful functors used with accumulate or for_each.
I have encountered similar problem and my solution is much clear than above.
I simply used the pattern in @JsonFormat
annotation
Basically my class has a DateTime
field, so I put an annotation around the getter:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public DateTime getDate() {
return date;
}
I serialize the class with ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
ObjectWriter ow = mapper.writer();
try {
String logStr = ow.writeValueAsString(log);
outLogger.info(logStr);
} catch (IOException e) {
logger.warn("JSON mapping exception", e);
}
We use Jackson 2.5.4
To randomly select 20 rows I think you'd be better off selecting the lot of them randomly ordered and selecting the first 20 of that set.
Something like:
Select *
from (select *
from table
order by dbms_random.value) -- you can also use DBMS_RANDOM.RANDOM
where rownum < 21;
Best used for small tables to avoid selecting large chunks of data only to discard most of it.
Ah, since I had no dependencies in my master project, "gradle dependencies" only lists those and not subproject dependencies so the correct command ended up being
gradle :<subproject>:dependencies
so for me this was
gradle :master:dependencies
I used the solution below to export all datagrid values to a text file, rather than using the column names you can use the column index instead.
foreach (DataGridViewRow row in xxxCsvDG.Rows)
{
File.AppendAllText(csvLocation, row.Cells[0].Value + "," + row.Cells[1].Value + "," + row.Cells[2].Value + "," + row.Cells[3].Value + Environment.NewLine);
}
You can use this lines in the css file:
ul[rn-carousel] {
> li {
position: relative;
margin-left: -100%;
&:first-child {
margin-left: 0;
}
}
}
Simply, you can use FormCollection
like:
[HttpPost]
public ActionResult SubmitAction(FormCollection collection)
{
// Get Post Params Here
string var1 = collection["var1"];
}
You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:
//Defined in another file
class MyForm
{
public string var1 { get; set; }
}
[HttpPost]
public ActionResult SubmitAction(MyForm form)
{
string var1 = form1.Var1;
}
public static class ExceptByProperty
{
public static List<T> ExceptBYProperty<T, TProperty>(this List<T> list, List<T> list2, Expression<Func<T, TProperty>> propertyLambda)
{
Type type = typeof(T);
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
if (type != propInfo.ReflectedType &&
!type.IsSubclassOf(propInfo.ReflectedType))
throw new ArgumentException(string.Format(
"Expresion '{0}' refers to a property that is not from type {1}.",
propertyLambda.ToString(),
type));
Func<T, TProperty> func = propertyLambda.Compile();
var ids = list2.Select<T, TProperty>(x => func(x)).ToArray();
return list.Where(i => !ids.Contains(((TProperty)propInfo.GetValue(i, null)))).ToList();
}
}
public class testClass
{
public int ID { get; set; }
public string Name { get; set; }
}
For Test this:
List<testClass> a = new List<testClass>();
List<testClass> b = new List<testClass>();
a.Add(new testClass() { ID = 1 });
a.Add(new testClass() { ID = 2 });
a.Add(new testClass() { ID = 3 });
a.Add(new testClass() { ID = 4 });
a.Add(new testClass() { ID = 5 });
b.Add(new testClass() { ID = 3 });
b.Add(new testClass() { ID = 5 });
a.Select<testClass, int>(x => x.ID);
var items = a.ExceptBYProperty(b, u => u.ID);
If anyone comes to this thread and has this issue when you remote to a VMware VM with windows 10 1903, disabling 3d in the graphics card worked for me.
Are you escaping? Try the mysql_real_escape_string() function and it will handle the special characters.
You have to declare your functions before main()
(or declare the function prototypes before main()
)
As it is, the compiler sees my_print (my_string);
in main()
as a function declaration.
Move your functions above main()
in the file, or put:
void my_print (char *);
void my_print2 (char *);
Above main()
in the file.
You probably want SETLOCAL ENABLEDELAYEDEXPANSION
. See https://devblogs.microsoft.com/oldnewthing/20060823-00/?p=29993 for details.
Basically: Normal %variables%
are expanded right aftercmd.exe
reads the command. In your case the "command" is the whole
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo %z%
echo %%a
)
loop. At that point z
has no value yet, so echo %z%
turns into echo
. Then the loop is executed and z
is set, but its value isn't used anymore.
SETLOCAL ENABLEDELAYEDEXPANSION
enables an additional syntax, !variable!
. This also expands variables but it only does so right before each (sub-)command is executed.
SETLOCAL ENABLEDELAYEDEXPANSION
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo !z!
echo %%a
)
This gives you the current value of z
each time the echo
runs.
select * from (select * from table order by value desc limit 999999999) v group by v.name
Another alternative is the following, although not the cleanest as it assumes the image to be the only element in a container, such as in this case:
<header class="siteHeader">
<img src="img" class="siteLogo" />
</header>
You can then use the container as a mask with the desired size, and surround the image with a negative margin to move it into the right position:
.siteHeader{
width: 50px;
height: 50px;
overflow: hidden;
}
.siteHeader .siteLogo{
margin: -100px;
}
Demo can be seen in this JSFiddle.
Only seems to work in IE>9, and probably all significant versions of all other browsers.
important: in this kind of error you should look for simple mistakes in most cases
besides syntax error, I should say once I had same problem and it was because of bad name I have chosen for function. I have never searched for the reason but I remember that I copied another function and change it to use. I add "1" after the name to changed the function name and I got this error.
Any mature enough SQL database should be able to execute that just as effectively as the equivalent JOIN
. Use whatever is more readable to you.
If you are facing this issue in Mac-OSX terminal with python, try updating the versions of the packages you are using. So, go to your files in python and where you specified the packages, update them to the latest versions available on the internet.
even with the environment variables set, I found that ant -version
does not work in scripts. Try call ant -version
That doesn't set the format of the string; it sets the format of the file. Even with that header, "hello"
is a byte string, not a Unicode string. To make it Unicode, you're going to have to use u"hello"
everywhere. The header is just a hint of what format to use when reading the .py
file.
It should be like this:
<TextView android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No Results" />
Note the id attribute.
Also as I tried, when use ajax in select2, the programmatic control methods for set new values in select2 does not work for me! Now I write these code for resolve the problem:
$('#sel')
.empty() //empty select
.append($("<option/>") //add option tag in select
.val("20") //set value for option to post it
.text("nabi")) //set a text for show in select
.val("20") //select option of select2
.trigger("change"); //apply to select2
You can test complete sample code in here link: https://jsfiddle.net/NabiKAZ/2g1qq26v/32/
In this sample code there is a ajax select2 and you can set new value with a button.
$("#btn").click(function() {_x000D_
$('#sel')_x000D_
.empty() //empty select_x000D_
.append($("<option/>") //add option tag in select_x000D_
.val("20") //set value for option to post it_x000D_
.text("nabi")) //set a text for show in select_x000D_
.val("20") //select option of select2_x000D_
.trigger("change"); //apply to select2_x000D_
});_x000D_
_x000D_
$("#sel").select2({_x000D_
ajax: {_x000D_
url: "https://api.github.com/search/repositories",_x000D_
dataType: 'json',_x000D_
delay: 250,_x000D_
data: function(params) {_x000D_
return {_x000D_
q: params.term, // search term_x000D_
page: params.page_x000D_
};_x000D_
},_x000D_
processResults: function(data, params) {_x000D_
// parse the results into the format expected by Select2_x000D_
// since we are using custom formatting functions we do not need to_x000D_
// alter the remote JSON data, except to indicate that infinite_x000D_
// scrolling can be used_x000D_
params.page = params.page || 1;_x000D_
_x000D_
return {_x000D_
results: data.items,_x000D_
pagination: {_x000D_
more: (params.page * 30) < data.total_count_x000D_
}_x000D_
};_x000D_
},_x000D_
cache: true_x000D_
},_x000D_
escapeMarkup: function(markup) {_x000D_
return markup;_x000D_
}, // let our custom formatter work_x000D_
minimumInputLength: 1,_x000D_
templateResult: formatRepo, // omitted for brevity, see the source of this page_x000D_
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page_x000D_
});_x000D_
_x000D_
function formatRepo(repo) {_x000D_
if (repo.loading) return repo.text;_x000D_
_x000D_
var markup = "<div class='select2-result-repository clearfix'>" +_x000D_
"<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +_x000D_
"<div class='select2-result-repository__meta'>" +_x000D_
"<div class='select2-result-repository__title'>" + repo.full_name + "</div>";_x000D_
_x000D_
if (repo.description) {_x000D_
markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";_x000D_
}_x000D_
_x000D_
markup += "<div class='select2-result-repository__statistics'>" +_x000D_
"<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + repo.forks_count + " Forks</div>" +_x000D_
"<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + repo.stargazers_count + " Stars</div>" +_x000D_
"<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + repo.watchers_count + " Watchers</div>" +_x000D_
"</div>" +_x000D_
"</div></div>";_x000D_
_x000D_
return markup;_x000D_
}_x000D_
_x000D_
function formatRepoSelection(repo) {_x000D_
return repo.full_name || repo.text;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css">_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link rel="stylesheet" type="text/css" href="https://select2.org/assets/a7be624d756ba99faa354e455aed250d.css">_x000D_
_x000D_
<select id="sel" multiple="multiple" class="col-xs-5">_x000D_
</select>_x000D_
_x000D_
<button id="btn">Set Default</button>
_x000D_
right click on first file and select
then right click on second file and select
Screencast:
The OP expects two things:
A. to round up to the higher tenths, and
B. to show a zero in the hundredths place (a typical need with currency).
Meeting both requirement would seem to necessitate a separate method for each of the above. Here's an approach that builds on suryakiran's suggested answer:
//Arguments: number to round, number of decimal places.
function roundPrice(rnum, rlength) {
var newnumber = Math.ceil(rnum * Math.pow(10, rlength-1)) / Math.pow(10, rlength-1);
var toTenths = newnumber.toFixed(rlength);
return toTenths;
}
alert(roundPrice(678.91011,2)); // returns 679.00
alert(roundPrice(876.54321,2)); // returns 876.60
Important note: this solution produces a very different result with negative and exponential numbers.
For the sake of comparison between this answer and two that are very similar, see the following 2 approaches. The first simply rounds to the nearest hundredth per usual, and the second simply rounds up to the nearest hundredth (larger).
function roundNumber(rnum, rlength) {
var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
return newnumber;
}
alert(roundNumber(678.91011,2)); // returns 678.91
function ceilNumber(rnum, rlength) {
var newnumber = Math.ceil(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
return newnumber;
}
alert(ceilNumber(678.91011,2)); // returns 678.92
You can look into Windows installed folder from here of your pc path:
C:\Program Files (x86)\Microsoft ASP.NET
View of Opened file where showing installed MVC 3, MVC 4
In the first case, the data are passed to the script via GET, in the second via POST.
http://docs.jquery.com/Ajax/load#urldatacallback
I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.
Iterators make your code more generic.
Every standard library container provides an iterator hence if you change your container class in future the loop wont be affected.
actually I think your code is just fine.. you can save those values as strings (TEXT) just like you did.. (if you want to)
and you probably get the error for the System.currentTimeMillis() that might be too big for INTEGER
There is no default database for user. There is default database for current session.
You can get it using DATABASE() function -
SELECT DATABASE();
And you can set it using USE statement -
USE database1;
You should set it manually - USE db_name
, or in the connection string.
Modulo API consistency, why JUnit didn't provide assertNotEquals()
is the same reason why JUnit never provided methods like
assertStringMatchesTheRegex(regex, str)
vs. assertStringDoesntMatchTheRegex(regex, str)
assertStringBeginsWith(prefix, str)
vs. assertStringDoesntBeginWith(prefix, str)
i.e. there's no end to providing a specific assertion methods for the kinds of things you might want in your assertion logic!
Far better to provide composable test primitives like equalTo(...)
, is(...)
, not(...)
, regex(...)
and let the programmer piece those together instead for more readability and sanity.
If your targetSdkVersion >= 24
, then we have to use FileProvider
class to give access to the particular file or folder to make them accessible for other apps. We create our own class inheriting FileProvider
in order to make sure our FileProvider doesn't conflict with FileProviders declared in imported dependencies as described here.
Steps to replace file://
URI with content://
URI:
<provider>
tag in AndroidManifest.xml
under <application>
tag. Specify a unique authority for the android:authorities
attribute to avoid conflicts, imported dependencies might specify ${applicationId}.provider
and other commonly used authorities.<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
<application
...
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
</application>
</manifest>
provider_paths.xml
file in res/xml
folder. A folder may be needed to be created if it doesn't exist yet. The content of the file is shown below. It describes that we would like to share access to the External Storage at root folder (path=".")
with the name external_files.<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>
The final step is to change the line of code below in
Uri photoURI = Uri.fromFile(createImageFile());
to
Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", createImageFile());
Edit: If you're using an intent to make the system open your file, you may need to add the following line of code:
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Please refer to the full code and solution that have been explained here.
If your key is NOT guaranteed to be unique for all elements in the list, you should convert it to a Map<String, List<Choice>>
instead of a Map<String, Choice>
Map<String, List<Choice>> result =
choices.stream().collect(Collectors.groupingBy(Choice::getName));
Make sure your oracle services are running automatically. Just press Win+R. Type services.msc in textbox then press O to find oracle services.
In your PC name might be like OracleserviceXYZ. Right click on highlighted services.
I want to understand the lock each transaction isolation takes on the table
For example, you have 3 concurrent processes A, B and C. A starts a transaction, writes data and commit/rollback (depending on results). B just executes a SELECT
statement to read data. C reads and updates data. All these process work on the same table T.
WHERE aField > 10 AND aField < 20
, A inserts data where aField
value is between 10 and 20, then B reads the data again and get a different result.I want to understand where we define these isolation levels: only at JDBC/hibernate level or in DB also
Using JDBC, you define it using Connection#setTransactionIsolation
.
Using Hibernate:
<property name="hibernate.connection.isolation">2</property>
Where
Hibernate configuration is taken from here (sorry, it's in Spanish).
By the way, you can set the isolation level on RDBMS as well:
SET ISOLATION TO DIRTY READ
sentence.)and on and on...
The accepted answer is good. But if you have a scenario like this:
http://www.mydomain.me/index.php?state=California.php#Berkeley
You can treat the named anchor as a query string like this:
http://www.mydomain.me/index.php?state=California.php&city=Berkeley
Then, access it like this:
$Url = $_GET['state']."#".$_GET['city'];
I wrote a little function where you only have to parse the name of the query parameter. So if you have: ?Project=12&Mode=200&date=2013-05-27 and you want the 'Mode' parameter you only have to parse the 'Mode' name into the function:
function getParameterByName( name ){
var regexS = "[\\?&]"+name+"=([^&#]*)",
regex = new RegExp( regexS ),
results = regex.exec( window.location.search );
if( results == null ){
return "";
} else{
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
}
// example caller:
var result = getParameterByName('Mode');
I work at an imaging vendor and wrote an adapter for WPF to our image format which is similar to a System.Drawing.Bitmap.
I wrote this KB to explain it to our customers:
http://www.atalasoft.com/kb/article.aspx?id=10156
And there is code there that does it. You need to replace AtalaImage with Bitmap and do the equivalent thing that we are doing -- it should be pretty straightforward.
Try using an a link element and click it with javascriipt
<a id="SimulateOpenLink" href="#" target="_blank" rel="noopener noreferrer"></a>
and the script
function openURL(url) {
document.getElementById("SimulateOpenLink").href = url
document.getElementById("SimulateOpenLink").click()
}
Use it like this
//do stuff
var id = 123123141;
openURL("/api/user/" + id + "/print") //this open webpage bypassing pop-up blocker
openURL("https://www.google.com") //Another link
Apart from the solutions already mentioned, you can also download jquery.min.js
locally and then use it -
For downloading -
wget "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"
manifest.json -
"content_scripts": [
{
"js": ["/path/to/jquery.min.js", ...]
}
],
in html -
<script src="/path/to/jquery.min.js"></script>
Reference - https://developer.chrome.com/extensions/contentSecurityPolicy
A loop like this one:
else if (!(Character.isLowerCase(ch)))
{
for (int i=1; i<password.length(); i++)
{
ch = password.charAt(i);
if (!Character.isLowerCase(ch))
{
System.out.println("Invalid password - Must have a Lower Case character.");
password = "";
}
// end if
} //end for
}
Has an obvious logical flaw: You enter it if the first character is not lowercase, then test if the second character is not lower case. At that point you throw an error.
Instead, you should do something like this (not full code, just an example):
boolean hasLower = false, hasUpper = false, hasNumber = false, hasSpecial = false; // etc - all the rules
for ( ii = 0; ii < password.length(); ii++ ) {
ch = password.charAt(ii);
// check each rule in turn, with code like this:
if Character.isLowerCase(ch) hasLower = true;
if Character.isUpperCase(ch) hasUpper = true;
// ... etc for all the tests you want to do
}
if(hasLower && hasUpper && ...) {
// password is good
}
else {
// password is bad
}
Of course the code snippet you provided, besides the faulty logic, did not have code to test for the other conditions that your "help" option printed out. As was pointed out in one of the other answers, you could consider using regular expressions to help you speed up the process of finding each of these things. For example,
hasNumber : use regex pattern "\d+" for "find at least one digit"
hasSpecial : use regex pattern "[!@#$%^&*]+" for "find at least one of these characters"
In code:
hasNumber = password.matches(".*\\d.*"); // "a digit with anything before or after"
hasSpecial = password.matches(".*[!@#$%^&*].*");
hasNoNOT = !password.matches(".*NOT.*");
hasNoAND = !password.matches(".*AND.*");
It is possible to combine these things in clever ways - but especially when you are a novice regex user, it is much better to be a little bit "slow and tedious", and get code that works first time (plus you will be able to figure out what you did six months from now).
Specifying a float by placing a '.' after the number will also cause it to default to float.
>>> 1 / 2
0
>>> 1. / 2.
0.5
/// <summary>
/// Returns the call that occurred just before the "GetCallingMethod".
/// </summary>
public static string GetCallingMethod()
{
return GetCallingMethod("GetCallingMethod");
}
/// <summary>
/// Returns the call that occurred just before the the method specified.
/// </summary>
/// <param name="MethodAfter">The named method to see what happened just before it was called. (case sensitive)</param>
/// <returns>The method name.</returns>
public static string GetCallingMethod(string MethodAfter)
{
string str = "";
try
{
StackTrace st = new StackTrace();
StackFrame[] frames = st.GetFrames();
for (int i = 0; i < st.FrameCount - 1; i++)
{
if (frames[i].GetMethod().Name.Equals(MethodAfter))
{
if (!frames[i + 1].GetMethod().Name.Equals(MethodAfter)) // ignores overloaded methods.
{
str = frames[i + 1].GetMethod().ReflectedType.FullName + "." + frames[i + 1].GetMethod().Name;
break;
}
}
}
}
catch (Exception) { ; }
return str;
}
The simple answer is that you can't reliably log out of http-authentication.
The long answer:
Http-auth (like the rest of the HTTP spec) is meant to be stateless. So being "logged in" or "logged out" isn't really a concept that makes sense. The better way to see it is to ask, for each HTTP request (and remember a page load is usually multiple requests), "are you allowed to do what you're requesting?". The server sees each request as new and unrelated to any previous requests.
Browsers have chosen to remember the credentials you tell them on the first 401, and re-send them without the user's explicit permission on subsequent requests. This is an attempt at giving the user the "logged in/logged out" model they expect, but it's purely a kludge. It's the browser that's simulating this persistence of state. The web server is completely unaware of it.
So "logging out", in the context of http-auth is purely a simulation provided by the browser, and so outside the authority of the server.
Yes, there are kludges. But they break RESTful-ness (if that's of value to you) and they are unreliable.
If you absolutely require a logged-in/logged-out model for your site authentication, the best bet is a tracking cookie, with the persistence of state stored on the server in some manner (mysql, sqlite, flatfile, etc). This will require all requests to be evaluated, for instance, with PHP.
Make sure branch "master" exists! It's not just a name apparently.
I got this error after creating a blank bare repo, pushing a branch named "dev" to it, and trying to use git log in the bare repo. Interestingly, git branch knows that dev is the only branch existing (so I think this is a git bug).
Solution: I repeated the procedure, this time having renamed "dev" to "master" on the working repo before pushing to the bare repo. Success!
Good answer. Note that if the value to encode is undefined
or null
with jQuery 1.4.2 you might get errors such as:
jQuery("<div/>").text(value).html is not a function
OR
Uncaught TypeError: Object has no method 'html'
The solution is to modify the function to check for an actual value:
function htmlEncode(value){
if (value) {
return jQuery('<div/>').text(value).html();
} else {
return '';
}
}
You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.
You should use this request:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
Right Click on Project > Properties > Java Build Path > Libraries > select classpath -> add Library -> Junit -> select junit version -> finish -> applay
You can find that row with
DataRow row = table.Select("Product_id=2").FirstOrDefault();
and update it
row["Product_name"] = "cde";
No javascript, just CSS. Works fine!
.no-break-out {
/* These are technically the same, but use both */
overflow-wrap: break-word;
word-wrap: break-word;
-ms-word-break: break-all;
/* This is the dangerous one in WebKit, as it breaks things wherever */
word-break: break-all;
/* Instead use this non-standard one: */
word-break: break-word;
/* Adds a hyphen where the word breaks, if supported (No Blink) */
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
String enums look different than regular ones, for example:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which just gives you this object:
{
A: "a",
B: "b",
C: "c"
}
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
I assume that you have some sort of List
component and some sort of Item
component. The way I did it in one project was to let the item know if it was active or not; the item would ask the list to scroll it into view if necessary. Consider the following pseudocode:
class List extends React.Component {
render() {
return <div>{this.props.items.map(this.renderItem)}</div>;
}
renderItem(item) {
return <Item key={item.id} item={item}
active={item.id === this.props.activeId}
scrollIntoView={this.scrollElementIntoViewIfNeeded} />
}
scrollElementIntoViewIfNeeded(domNode) {
var containerDomNode = React.findDOMNode(this);
// Determine if `domNode` fully fits inside `containerDomNode`.
// If not, set the container's scrollTop appropriately.
}
}
class Item extends React.Component {
render() {
return <div>something...</div>;
}
componentDidMount() {
this.ensureVisible();
}
componentDidUpdate() {
this.ensureVisible();
}
ensureVisible() {
if (this.props.active) {
this.props.scrollIntoView(React.findDOMNode(this));
}
}
}
A better solution is probably to make the list responsible for scrolling the item into view (without the item being aware that it's even in a list). To do so, you could add a ref
attribute to a certain item and find it with that:
class List extends React.Component {
render() {
return <div>{this.props.items.map(this.renderItem)}</div>;
}
renderItem(item) {
var active = item.id === this.props.activeId;
var props = {
key: item.id,
item: item,
active: active
};
if (active) {
props.ref = "activeItem";
}
return <Item {...props} />
}
componentDidUpdate(prevProps) {
// only scroll into view if the active item changed last render
if (this.props.activeId !== prevProps.activeId) {
this.ensureActiveItemVisible();
}
}
ensureActiveItemVisible() {
var itemComponent = this.refs.activeItem;
if (itemComponent) {
var domNode = React.findDOMNode(itemComponent);
this.scrollElementIntoViewIfNeeded(domNode);
}
}
scrollElementIntoViewIfNeeded(domNode) {
var containerDomNode = React.findDOMNode(this);
// Determine if `domNode` fully fits inside `containerDomNode`.
// If not, set the container's scrollTop appropriately.
}
}
If you don't want to do the math to determine if the item is visible inside the list node, you could use the DOM method scrollIntoView()
or the Webkit-specific scrollIntoViewIfNeeded
, which has a polyfill available so you can use it in non-Webkit browsers.
I have read all the answers related to getting this message in Android Studio
:
More than one file was found with OS independent path 'META-INF/LICENSE'
but in this case excluding classes is no neccessary, we only need to exclude 'META-INF/DEPENDENCIES'
, this can be done inside the /app/build.gradle
:
android{
...
...
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
}
}
I try almost everything in here to solve this problem... I share here the answer that help me:
Another way to resolve the issue :
- in IIS console, go to application pool managing your site, and note the identity running it (usually Network Service)
- make sure this identity can read KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog (rigth-click, authorisations)
- now change the identity of this application pool to Local System, apply, and switch back to Network Service
Credentials will be reloaded and EventLog reacheable
in http://geekswithblogs.net/timh/archive/2005/10/05/56029.aspx , thanks Michael Freidgeim
A java.util.Date
is not a java.sql.Date
. It's the other way around. A java.sql.Date
is a java.util.Date
.
You'll need to convert it to a java.sql.Date
by using the constructor that takes a long
that a java.util.Date
can supply.
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
\r
can do the work here for you.
You can simply set the status code of the response to 200 like the following
public ActionResult SomeMethod(parameters...)
{
//others code here
...
Response.StatusCode = 200;
return YourObject;
}
1).(expression1 | expression2), | operator will evaluate expression2 irrespective of whether the result of expression1 is true or false.
Example:
class Or
{
public static void main(String[] args)
{
boolean b=true;
if (b | test());
}
static boolean test()
{
System.out.println("No short circuit!");
return false;
}
}
2).(expression1 || expression2), || operator will not evaluate expression2 if expression1 is true.
Example:
class Or
{
public static void main(String[] args)
{
boolean b=true;
if (b || test())
{
System.out.println("short circuit!");
}
}
static boolean test()
{
System.out.println("No short circuit!");
return false;
}
}
It's true, they are both - or more precisely, they are "inline block" elements. This means that they flow inline like text, but also have a width and height like block elements.
Just use android:enabled="false"
. This will also give an appearance to the EditText
which will make it look not editable.
string outString= number.ToString("####0.00");
DATABASE
MongoDB states a nice example:
To select a database to use, in the mongo shell, issue the use <db> statement, as in the following example:
use myDB
use myNewDB
Content from: https://docs.mongodb.com/manual/core/databases-and-collections/#databases
COLLECTIONS
Lowercase names: avoids case sensitivity issues, MongoDB collection names are case sensitive.
Plural: more obvious to label a collection of something as the plural, e.g. "files" rather than "file"
>No word separators: Avoids issues where different people (incorrectly) separate words (username <-> user_name, first_name <->
firstname). This one is up for debate according to a few people
around here but provided the argument is isolated to collection names I don't think it should be ;) If you find yourself improving the
readability of your collection name by adding underscores or
camelCasing your collection name is probably too long or should use
periods as appropriate which is the standard for collection
categorization.Dot notation for higher detail collections: Gives some indication to how collections are related. For example you can be reasonably sure you could delete "users.pagevisits" if you deleted "users", provided the people that designed the schema did a good job.
Content from: http://www.tutespace.com/2016/03/schema-design-and-naming-conventions-in.html
For collections I'm following these suggested patterns until I find official MongoDB documentation.
For anyone looking at this and had no result with adding the Access-Control-Allow-Origin
try also adding the Access-Control-Allow-Headers
. May safe somebody from a headache.
G'day,
The declaration
static uint8_t l_matrix[10][20];
has set aside storage for 10 rows of 20 unit8_t locations, i.e. 200 uint8_t sized locations, with each element being found by calculating 20 x row + column.
So doesn't
uint8_t (*matrix_ptr)[20] = l_matrix;
give you what you need and point to the column zero element of the first row of the array?
Edit: Thinking about this a bit further, isn't an array name, by definition, a pointer? That is, the name of an array is a synonym for the location of the first element, i.e. l_matrix[0][0]?
Edit2: As mentioned by others, the comment space is a bit too small for further discussion. Anyway:
typedef uint8_t array_of_20_uint8_t[20];
array_of_20_uint8_t *matrix_ptr = l_matrix;
does not provide any allocation of storage for the array in question.
As mentioned above, and as defined by the standard, the statement:
static uint8_t l_matrix[10][20];
has set aside 200 sequential locations of type uint8_t.
Referring to l_matrix using statements of the form:
(*l_matrix + (20 * rowno) + colno)
will give you the contents of the colno'th element found in row rowno.
All pointer manipulations automatically take into account the size of the object pointed to. - K&R Section 5.4, p.103
This is also the case if any padding or byte alignment shifting is involved in the storage of the object at hand. The compiler will automatically adjust for these. By definition of the C ANSI standard.
HTH
cheers,
In Windows 7 or 10, the trick that worked for me is deleting the GIT_SSH system variable. It was set before to use Plink, and now was replaced by Putty. This was causing Plink.exe error
There was also an old installation of Git (32-bit version) and updating to Git(e.g. Git-2.20.1-64-bit.exe) since the PC was 64-bit OS.
Anyway the Putty/Plink was not even used by Git since in the Git installation it was default to use Open SSH.
For Windows 10, I needed to add /f option in order to shutdown the pc without any question and wait time.
//This did not work for me
Process.Start("shutdown", "/s /t 0");
//But this worked
Process.Start("shutdown", "/s /f /t 0");
On Chrome and Firefox 32+, navigator.languages contains an array of locales in order of user preference, and is more accurate than navigator.language, however to make it backwards-compatible (Tested Chrome / IE / Firefox / Safari), then use this:
function getLang()
{
if (navigator.languages != undefined)
return navigator.languages[0];
else
return navigator.language;
}
See this: http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax
foo://username:[email protected]:8042/over/there/index.dtb;type=animal?name=ferret#nose
\ / \________________/\_________/ \__/ \___/ \_/ \_________/ \_________/ \__/
| | | | | | | | |
| userinfo hostname port | | parameter query fragment
| \_______________________________/ \_____________|____|____________/
scheme | | | |
| authority |path|
| | |
| path interpretable as filename
| ___________|____________ |
/ \ / \ |
urn:example:animal:ferret:nose interpretable as extension
An absolute URL includes the parts before the "path" part - in other words, it includes the scheme (the http
in http://foo/bar/baz
) and the hostname (the foo
in http://foo/bar/baz
) (and optionally port, userinfo and port).
Relative URLs start with a path.
Absolute URLs are, well, absolute: the location of the resource can be resolved looking only at the URL itself. A relative URL is in a sense incomplete: to resolve it, you need the scheme and hostname, and these are typically taken from the current context. For example, in a web page at
http://myhost/mypath/myresource1.html
you could put a link like so
<a href="pages/page1">click me</a>
In the href
attribute of the link, a relative URLs used, and if it is clicked, it has to be resolved in order to follow it. In this case, the current context is
http://myhost/mypath/myresource1.html
so the schema, hostname, and leading path of these are taken and prepended to pages/page1
, yielding
http://myhost/mypath/pages/page1
If the link would have been:
<a href="/pages/page1">click me</a>
(note the /
appearing at the start of the URL) then it would have been resolved as
http://myhost/pages/page1
because the leading /
indicates the root of the host.
In a webapplication, I would advise to use relative URLs for all resources that belong to your app. That way, if you change the location of the pages, everything will continue to work. Any external resources (could be pages completely outside your application, but also static content that you deliver through a content delivery network) should always be pointed to using absolute URLs: if you don't there simply is no way to locate them, because they reside on a different server.
<script type="text/javascript">
function upperCaseF(a){
setTimeout(function(){
a.value = a.value.toUpperCase();
}, 1);
}
</script>
<input type="text" required="" name="partno" class="form-control" placeholder="Enter a Part No*" onkeydown="upperCaseF(this)">
If you need this solution for only few types of modals just use
style="width:90%"
attribute.
example:
div class="modal-dialog modal-lg" style="width:90%"
note: this will change only this particular modal
It is simple. So follow this code.
decimal d = 10.5;
int roundNumber = (int)Math.Floor(d + 0.5);
Result is 11
docker rmi -f $(docker images -a|awk 'NR > 1 && $2 == "" {print $3}')
Any possible option is to use custom file wrapper for simulating variables as files. You can achieve it by using this:
1) First of all, register your wrapper (only once in file, use it like session_start()):
stream_wrapper_register('var', VarWrapper);
2) Then define your wrapper class (it is really fast written, not completely correct, but it works):
class VarWrapper {
protected $pos = 0;
protected $content;
public function stream_open($path, $mode, $options, &$opened_path) {
$varname = substr($path, 6);
global $$varname;
$this->content = $$varname;
return true;
}
public function stream_read($count) {
$s = substr($this->content, $this->pos, $count);
$this->pos += $count;
return $s;
}
public function stream_stat() {
$f = fopen(__file__, 'rb');
$a = fstat($f);
fclose($f);
if (isset($a[7])) $a[7] = strlen($this->content);
return $a;
}
}
3) Then use any file function with your wrapper on var:// protocol (you can use it for include, require etc. too):
global $__myVar;
$__myVar = 'Enter tags here';
$data = php_strip_whitespace('var://__myVar');
Note: Don't forget to have your variable in global scope (like global $__myVar)
Here's a sample code:
Exec sp_add_schedule
@schedule_name = N'SchedulName'
@freq_type = 1
@active_start_time = 08300
This worked for me but only after forcing the specific verbs to be handled by the default handler.
<system.web>
...
<httpHandlers>
...
<add path="*" verb="OPTIONS" type="System.Web.DefaultHttpHandler" validate="true"/>
<add path="*" verb="TRACE" type="System.Web.DefaultHttpHandler" validate="true"/>
<add path="*" verb="HEAD" type="System.Web.DefaultHttpHandler" validate="true"/>
You still use the same configuration as you have above, but also force the verbs to be handled with the default handler and validated. Source: http://forums.asp.net/t/1311323.aspx
An easy way to test is just to deny GET and see if your site loads.
SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID
@user755806 I do not believe that your question was answered. I took your code but used the 'foo' example string, added a lower function and also found the length of the hash returned. In sqlplus or Oracle's sql developer Java database client you can use this to call the md5sum of a value. The column formats clean up the presentation.
column hash_key format a34;
column hash_key_len format 999999;
select dbms_obfuscation_toolkit.md5(
input => UTL_RAW.cast_to_raw('foo')) as hash_key,
length(dbms_obfuscation_toolkit.md5(
input => UTL_RAW.cast_to_raw('foo'))) as hash_key_len
from dual;
The result set
HASH_KEY HASH_KEY_LEN
---------------------------------- ------------
acbd18db4cc2f85cedef654fccc4a4d8 32
is the same value that is returned from a Linux md5sum command.
echo -n foo | md5sum
acbd18db4cc2f85cedef654fccc4a4d8 -
A combobox is unfortunately something that was left out of the HTML specifications.
The only way to manage it, rather unfortunately, is to roll your own or use a pre-built one. This one looks quite simple. I use this one for an open-source app although unfortunately you have to pay for commercial usage.
This code makes my life simpler.
import os
fnames = ([file for root, dirs, files in os.walk(dir)
for file in files
if file.endswith('.txt') #or file.endswith('.png') or file.endswith('.pdf')
])
for fname in fnames: print(fname)
Yes, it is not required and is usually omitted. It might be required for accessing variables after they have been overridden in the scope though:
Person::Person() {
int age;
this->age = 1;
}
Also, this:
Person::Person(int _age) {
age = _age;
}
It is pretty bad style; if you need an initializer with the same name use this notation:
Person::Person(int age) : age(age) {}
More info here: https://en.cppreference.com/w/cpp/language/initializer_list
I would like to Add to NeilW's answer. To incorporate a method that resembles the orderby. Add this method as an extension:
public static void Sort<T>(this ObservableCollection<T> collection, Func<T,T> keySelector) where T : IComparable
{
List<T> sorted = collection.OrderBy(keySelector).ToList();
for (int i = 0; i < sorted.Count(); i++)
collection.Move(collection.IndexOf(sorted[i]), i);
}
And use like:
myCollection = new ObservableCollection<MyObject>();
//Sorts in place, on a specific Func<T,T>
myCollection.Sort(x => x.ID);
I think below link might help you -
An update of Mogsdad's solution:
var Avals = ss.getRange("A1:A").getValues();
var Alast = Avals.filter(function(r){return r[0].length>0});
is the character entity reference (meant to be easily parseable by humans). 
is the numeric entity reference (meant to be easily parseable by machines).They are the same except for the fact that the latter does not need another lookup table to find its actual value. The lookup table is called a DTD, by the way.
You can read more about character entity references in the offical W3C documents.
You can chain class selectors without a space between them:
.a.b {
color: #666;
}
Note that, if it matters to you, IE6 treats .a.b
as .b
, so in that browser both div.a.b
and div.b
will have gray text. See this answer for a comparison between proper browsers and IE6.
Encoding options for SHA256's 256 bits:
CHAR(44)
including padding characterCHAR(64)
BINARY(32)
You don't need underscore, just use built-in map:
var string = 'Hello World!';_x000D_
_x000D_
document.write(string.split('').map(function(c) { return c.charCodeAt(); }));
_x000D_
I had a similar issue recently while working on recursion and nested lists. I declared:
print(r_sum([1,2,3[1,2,3],]))
instead of
print(r_sum([1,2,3,[1,2,3],]))
Note the comma after the number 3
base64 encoding takes 8-bit binary byte data and encodes it uses only the characters A-Z
, a-z
, 0-9
, +
, /
* so it can be transmitted over channels that do not preserve all 8-bits of data, such as email.
Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b''
syntax.
If you remove the b
, it becomes a string. A string is a sequence of Unicode characters. base64 has no idea what to do with Unicode data, it's not 8-bit. It's not really any bits, in fact. :-)
In your second example:
>>> encoded = base64.b64encode('data to be encoded')
All the characters fit neatly into the ASCII character set, and base64 encoding is therefore actually a bit pointless. You can convert it to ascii instead, with
>>> encoded = 'data to be encoded'.encode('ascii')
Or simpler:
>>> encoded = b'data to be encoded'
Which would be the same thing in this case.
* Most base64 flavours may also include a =
at the end as padding. In addition, some base64 variants may use characters other than +
and /
. See the Variants summary table at Wikipedia for an overview.
Perhps this is what you are looking for.
var pos = 0;
window.onload = function start() {
setTimeout(slide, 3000);
}
function slide() {
pos -= 600;
if (pos === -2400)
pos = 0;
document.getElementById('container').style.marginLeft= pos + "px";
setTimeout(slide, 3000);
}
try this,
String dateStr = "17-April-2011 19:20:23.707000000 ";
Date dateForm = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss").parse(dateStr);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String newDate = format.format(dateForm);
Calendar today = Calendar.getInstance();
Date fromDate = format.parse(newDate);
today.setTime(fromDate);
today.add(Calendar.DAY_OF_YEAR, 1);
Date toDate= new SimpleDateFormat("dd-MM-yyyy").parse(format.format(today.getTime()));
Criteria crit = sessionFactory.getCurrentSession().createCriteria(Model.class);
crit.add(Restrictions.ge("dateFieldName", fromDate));
crit.add(Restrictions.le("dateFieldName", toDate));
return crit.list();
You can get current Fragment from fragmentManager. And if there are non of them in fragment manager you can create Fragment_1
public class MainActivity extends FragmentActivity {
public static Fragment_1 fragment_1;
public static Fragment_2 fragment_2;
public static Fragment_3 fragment_3;
public static FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.main);
fragment_1 = (Fragment_1) fragmentManager.findFragmentByTag("fragment1");
fragment_2 =(Fragment_2) fragmentManager.findFragmentByTag("fragment2");
fragment_3 = (Fragment_3) fragmentManager.findFragmentByTag("fragment3");
if(fragment_1==null && fragment_2==null && fragment_3==null){
fragment_1 = new Fragment_1();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment_1, "fragment1").commit();
}
}
}
also you can use setRetainInstance
to true what it will do it ignore onDestroy()
method in fragment and your application going to back ground and os kill your application to allocate more memory you will need to save all data you need in onSaveInstanceState
bundle
public class Fragment_1 extends Fragment {
private EditText title;
private Button go_next;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true); //Will ignore onDestroy Method (Nested Fragments no need this if parent have it)
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
onRestoreInstanceStae(savedInstanceState);
return super.onCreateView(inflater, container, savedInstanceState);
}
//Here you can restore saved data in onSaveInstanceState Bundle
private void onRestoreInstanceState(Bundle savedInstanceState){
if(savedInstanceState!=null){
String SomeText = savedInstanceState.getString("title");
}
}
//Here you Save your data
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("title", "Some Text");
}
}
If the string is empty, comboBox.getSelectedItem().toString()
will give a NullPointerException
. So better to typecast by (String)
.
I followed below steps to install mcrypt for PHP7.2 using PECL.
apt-get install php-pecl
apt-get install libmcrypt-dev libreadline-dev
pecl install mcrypt-1.0.1
You should add "extension=mcrypt.so" to php.ini
Please comment below if you need any assistance. :-)
IMPORTANT !
According to php.net reference many (all) mcrypt functions have been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.
You can't add an icon and text because you can't apply a different font to part of a placeholder, however, if you are satisfied with just an icon then it can work. The FontAwesome icons are just characters with a custom font (you can look at the FontAwesome Cheatsheet for the escaped Unicode character in the content
rule. In the less source code it's found in variables.less The challenge would be to swap the fonts when the input is not empty. Combine it with jQuery like this.
<form role="form">
<div class="form-group">
<input type="text" class="form-control empty" id="iconified" placeholder=""/>
</div>
</form>
With this CSS:
input.empty {
font-family: FontAwesome;
font-style: normal;
font-weight: normal;
text-decoration: inherit;
}
And this (simple) jQuery
$('#iconified').on('keyup', function() {
var input = $(this);
if(input.val().length === 0) {
input.addClass('empty');
} else {
input.removeClass('empty');
}
});
The transition between fonts will not be smooth, however.
Try this :
string myStr = ...
myStr = myStr.Replace("\n", Environment.NewLine)
You can do like this :
webelement time=driver.findElement(By.id("input_name")).getAttribute("value");
this will give you the time displaying on the webpage.
Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3
NOTE: this component only works in boostrap-4 since version 1.13.0
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
<option>Mustard</option>_x000D_
<option>Ketchup</option>_x000D_
<option>Relish</option>_x000D_
</select>
_x000D_
Adding one of the blocks below works for me to use KDiff3 for my Windows and Linux development environments. It makes for a nice consistent cross-platform diff and merge tool.
[difftool "kdiff3"]
path = /usr/bin/kdiff3
trustExitCode = false
[difftool]
prompt = false
[diff]
tool = kdiff3
[mergetool "kdiff3"]
path = /usr/bin/kdiff3
trustExitCode = false
[mergetool]
keepBackup = false
[merge]
tool = kdiff3
[difftool "kdiff3"]
path = C:/Progra~1/KDiff3/kdiff3.exe
trustExitCode = false
[difftool]
prompt = false
[diff]
tool = kdiff3
[mergetool "kdiff3"]
path = C:/Progra~1/KDiff3/kdiff3.exe
trustExitCode = false
[mergetool]
keepBackup = false
[merge]
tool = kdiff3
Set the java.net.useSystemProxies
property to true
. You can set it, for example, through the JAVA_TOOL_OPTIONS environmental variable. In Ubuntu, you can, for example, add the following line to .bashrc
:
export JAVA_TOOL_OPTIONS+=" -Djava.net.useSystemProxies=true"
Check whether you are scheduling a task to trigger an executable (.exe) or a batch (.bat) file. If you have scheduled any other file to open (for example a .txt or .docx file), the file not open.
In my case following solution worked.
I hope this may help someone.
The Ruby File class will give you the ins and outs of ::new
and ::open
but its parent, the IO class, gets into the depth of #read
and #write
.
I managed to figure it out in the end, so if anyone is looking for the answer:
//Firefox
$('#elem').bind('DOMMouseScroll', function(e){
if(e.originalEvent.detail > 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('#elem').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
Kate, the KDE Advanced Text Editor is quite good. It has syntax highlighting, block selection mode, terminal/console, sessions, window splitting both horizontal and vertical etc.
When you are on a project page, you can press the 'Download ZIP' button which is located under the "Clone or Download" drop down:
This allows you to download the most recent version of the code as a zip archive.
If you aren't seeing that button, it is likely because you aren't on the main project page. To get there, click on the left-most tab labeled "<> Code".
In order to set the value of integer variable we simply assign the value to it.
eg g1val = 0
where as set keyword is used to assign value to object.
Sub test()
Dim g1val, g2val As Integer
g1val = 0
g2val = 0
For i = 3 To 18
If g1val > Cells(33, i).Value Then
g1val = g1val
Else
g1val = Cells(33, i).Value
End If
Next i
For j = 32 To 57
If g2val > Cells(31, j).Value Then
g2val = g2val
Else
g2val = Cells(31, j).Value
End If
Next j
End Sub
You can truncate the date
SELECT *
FROM Table1
WHERE trunc(field1) = to_Date('2012-01-01','YYY-MM-DD')
Look at the SQL Fiddle for more examples.
For MacPython installations, I found an effective solution to fixing the problem with setuptools (easy_install) in this blog post:
http://droidism.com/getting-running-with-django-and-macpython-26-on-leopard
One handy tip includes finding out which version of python is active in the terminal:
which python
x[r,]
where r is the row you're interested in. Try this, for example:
#Add your data
x <- structure(list(A = c(5, 3.5, 3.25, 4.25, 1.5 ),
B = c(4.25, 4, 4, 4.5, 4.5 ),
C = c(4.5, 2.5, 4, 2.25, 3 )
),
.Names = c("A", "B", "C"),
class = "data.frame",
row.names = c(NA, -5L)
)
#The vector your result should match
y<-c(A=5, B=4.25, C=4.5)
#Test that the items in the row match the vector you wanted
x[1,]==y
This page (from this useful site) has good information on indexing like this.
If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.
<script type="text/javascript">
// mini jQuery plugin that formats to two decimal places
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
// apply the currencyFormat behaviour to elements with 'currency' as their class
$( function() {
$('.currency').currencyFormat();
});
</script>
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">
@Jason is correct in a way but not entirely.
update
Update the registered submodules, i.e. clone missing submodules and checkout the commit specified in the index of the containing repository. This will make the submodules HEAD be detached unless --rebase or --merge is specified or the key submodule.$name.update is set to rebase or merge.
So, git submodule update
does checkout, but it is to the commit in the index of the containing repository. It does not yet know of the new commit upstream at all. So go to your submodule, get the commit you want and commit the updated submodule state in the main repository and then do the git submodule update
.
I tried this code to accept files using Ajax and on submit file gets store using my php file. Code modified slightly to work. (Uploaded Files: PDF,JPG)
function verify1() {
jQuery.ajax({
type: 'POST',
url:"functions.php",
data: new FormData($("#infoForm1")[0]),
processData: false,
contentType: false,
success: function(returnval) {
$("#show1").html(returnval);
$('#show1').show();
}
});
}
Just print the file details and check. You will get Output. If error let me know.
You can simply use $pull to remove a sub-document. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
Collection.update({
_id: parentDocumentId
}, {
$pull: {
subDocument: {
_id: SubDocumentId
}
}
});
This will find your parent document against given ID and then will remove the element from subDocument which matched the given criteria.
Read more about pull here.
According SQL Server 2008 Books You can create local and global temporary tables. Local temporary tables are visible only in the current session, and global temporary tables are visible to all sessions.
'#table_temporal
'##table_global
If a local temporary table is created in a stored procedure or application that can be executed at the same time by several users, the Database Engine must be able to distinguish the tables created by the different users. The Database Engine does this by internally appending a numeric suffix to each local temporary table name.
Then there occurs no problem.
I faced with same issue. For python3.6.8 and ubuntu 16.04 none of above did not help me.
sudo apt-get install python3.6-dev
This solved my problem.
Mostly this issue will come when ever you update your SDK, at the time of project creation Gradle build fails. If you add the maven and jcenter repositories to your build.gradle(Module:app) your problem will solved.
repositories {
maven { url 'http://repo1.maven.org/maven2' }
jcenter { url "http://jcenter.bintray.com/" }
}
These are the two line you have to add after
apply plugin: 'com.android.application'
This is how your code look like after adding those two lines
apply plugin: 'com.android.application'
repositories {
maven { url 'http://repo1.maven.org/maven2' }
jcenter { url "http://jcenter.bintray.com/" }
}
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.okedroid.myapplication"
minSdkVersion 17
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
>>> x = "2342.34"
>>> float(x)
2342.3400000000001
There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).
you need to do the process for all individual languages you work on...
I just want to add to Stephen's answer if you want to sort the array from high to low, another way other than in the comments above is just to add this to the line:
reverse = True
and the result will be as follows:
data.sort(key=lambda tup: tup[1], reverse=True)
Change it to:
<div style="background-color:black; overflow:hidden;" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>
Basically the outer div only contains floats. Floats are removed from the normal flow. As such the outer div really contains nothing and thus has no height. It really is black but you just can't see it.
The overflow:hidden property basically makes the outer div enclose the floats. The other way to do this is:
<div style="background-color:black" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
<div style="clear:both></div>
</div>
Oh and just for completeness, you should really prefer classes to direct CSS styles.
Assuming that your combobox isn't databound you would need to find the object's index in the "items" collection on your form and then set the "selectedindex" property to the appropriate index.
comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");
Keep in mind that the IndexOf function may throw an argumentexception if the item isn't found.
You can use the following example.
String date = "2011-08-12T20:17:46.384Z";
String inputPattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
String outputPattern = "yyyy-MM-dd HH:mm:ss";
LocalDateTime inputDate = null;
String outputDate = null;
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);
inputDate = LocalDateTime.parse(date, inputFormatter);
outputDate = outputFormatter.format(inputDate);
System.out.println("inputDate: " + inputDate);
System.out.println("outputDate: " + outputDate);
The shortcuts I use in Visual Studio for multiline (aka box) select are Shift + Alt + up/down/left/right
To create this in Visual Studio Code you can add these keybindings to the keybindings.json file (menu File → Preferences → Keyboard shortcuts).
{ "key": "shift+alt+down", "command": "editor.action.insertCursorBelow",
"when": "editorTextFocus" },
{ "key": "shift+alt+up", "command": "editor.action.insertCursorAbove",
"when": "editorTextFocus" },
{ "key": "shift+alt+right", "command": "cursorRightSelect",
"when": "editorTextFocus" },
{ "key": "shift+alt+left", "command": "cursorLeftSelect",
"when": "editorTextFocus" }
C++
constexpr hash function:
constexpr unsigned int hash(const char *s, int off = 0) {
return !s[off] ? 5381 : (hash(s, off+1)*33) ^ s[off];
}
switch( hash(str) ){
case hash("one") : // do something
case hash("two") : // do something
}
$.each(result, function(key, value) {
console.log(key+ ':' + value);
});
For Swift 3:
extension SystemSoundID {
static func playFileNamed(_ fileName: String, withExtenstion fileExtension: String) {
var sound: SystemSoundID = 0
if let soundURL = Bundle.main.url(forResource: fileName, withExtension: fileExtension) {
AudioServicesCreateSystemSoundID(soundURL as CFURL, &sound)
AudioServicesPlaySystemSound(sound)
}
}
}
You don't have to convert the object to a MyClass object because it already is. Wnat you really want to do is to cast it, but since the class name is not known at compile time, you can't do that, since you can't declare a variable of that class. My guess is that you want/need something like "duck typing", i.e. you don't know the class name but you know the method name at compile time. Interfaces, as proposed by Gregory, are your best bet to do that.
You have your arguments to the remote add
command reversed:
git remote add <NAME> <PATH>
So:
git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git
See git remote --help
for more information.
assertEquals
uses the equals
method for comparison. There is a different assert, assertSame
, which uses the ==
operator.
To understand why ==
shouldn't be used with strings you need to understand what ==
does: it does an identity check. That is, a == b
checks to see if a
and b
refer to the same object. It is built into the language, and its behavior cannot be changed by different classes. The equals
method, on the other hand, can be overridden by classes. While its default behavior (in the Object
class) is to do an identity check using the ==
operator, many classes, including String
, override it to instead do an "equivalence" check. In the case of String
, instead of checking if a
and b
refer to the same object, a.equals(b)
checks to see if the objects they refer to are both strings that contain exactly the same characters.
Analogy time: imagine that each String
object is a piece of paper with something written on it. Let's say I have two pieces of paper with "Foo" written on them, and another with "Bar" written on it. If I take the first two pieces of paper and use ==
to compare them it will return false
because it's essentially asking "are these the same piece of paper?". It doesn't need to even look at what's written on the paper. The fact that I'm giving it two pieces of paper (rather than the same one twice) means it will return false
. If I use equals
, however, the equals
method will read the two pieces of paper and see that they say the same thing ("Foo"), and so it'll return true
.
The bit that gets confusing with Strings is that the Java has a concept of "interning" Strings, and this is (effectively) automatically performed on any string literals in your code. This means that if you have two equivalent string literals in your code (even if they're in different classes) they'll actually both refer to the same String
object. This makes the ==
operator return true
more often than one might expect.
According to the docs, #Rails.env
wraps RAILS_ENV
:
# File vendor/rails/railties/lib/initializer.rb, line 55
def env
@_env ||= ActiveSupport::StringInquirer.new(RAILS_ENV)
end
But, look at specifically how it's wrapped, using ActiveSupport::StringInquirer
:
Wrapping a string in this class gives you a prettier way to test for equality. The value returned by Rails.env is wrapped in a StringInquirer object so instead of calling this:
Rails.env == "production"
you can call this:
Rails.env.production?
So they aren't exactly equivalent, but they're fairly close. I haven't used Rails much yet, but I'd say #Rails.env
is certainly the more visually attractive option due to using StringInquirer
.
You can refer this link for check if a image file exists with JavaScript.
checkImageExist.js:
var image = new Image(); var url_image = './ImageFolder/' + variable + '.jpg'; image.src = url_image; if (image.width == 0) { return `<img src='./ImageFolder/defaultImage.jpg'>`; } else { return `<img src='./ImageFolder/`+variable+`.jpg'`; } } ```
PHP file (for example, my_lengthy_script.php)
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
.htaccess file
<IfModule mod_php5.c>
php_value max_execution_time 300
</IfModule>
More configuration options
<IfModule mod_php5.c>
php_value post_max_size 5M
php_value upload_max_filesize 5M
php_value memory_limit 128M
php_value max_execution_time 300
php_value max_input_time 300
php_value session.gc_maxlifetime 1200
</IfModule>
If wordpress, set this in the config.php file,
define('WP_MEMORY_LIMIT', '128M');
If drupal, sites/default/settings.php
ini_set('memory_limit', '128M');
If you are using other frameworks,
ini_set('memory_limit', '128M');
You can increase memory as gigabyte.
ini_set('memory_limit', '3G'); // 3 Gigabytes
259200 means:-
( 259200/(60x60 minutes) ) / 24 hours ===> 3 Days
I found this to be the shortest working way to refresh with ui-router:
$state.go($state.current, {}, {reload: true}); //second parameter is for $stateParams
Update for newer versions:
$state.reload();
Which is an alias for:
$state.transitionTo($state.current, $stateParams, {
reload: true, inherit: false, notify: true
});
Documentation: https://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state#methods_reload
This related question's answer provided the solution for me... it was just a dumb mistake:
Remember to commit first!
https://stackoverflow.com/a/7572252
If you have not yet committed to your local repo, there is nothing to push, but the Git error message you get back doesn't help you too much.
the cause could be a variety of reasons. It might not show up in the log files. I had the case where the log showed Apache started, then all threads shut down, and absolutely no explanation why. Here's a tip for solving this problem everybody seems to have missed. The log file should show the full command line used to start apache, something like:
httpd -d C:/wamp/bin/apache/apache2.4.9
Do this: open a cmd window, cd to the apache bin directory, and run the command manually:
c:\> cd C:\wamp\bin\apache\apache2.4.9\bin
C:\wamp\bin\apache\apache2.4.9\bin> httpd -d C:/wamp/bin/apache/apache2.4.9
It blurted out the error stright away; problem solved in 5 minutes:
AH00526: Syntax error on line 609 of C:/wamp/bin/apache/apache2.4.9/conf/httpd.conf:
CustomLog takes two or three arguments, a file name, a custom log format string or format name, and an optional "env=" or "expr=" clause (see docs)
this happened due to a syntax error I put in 'httpd.conf' while trying to make my wampserver multi-homed. But why didn't the apache people write this in the log file?
DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).
There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.
CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener
Use the not
boolean operator:
nyval = not myval
not
returns a boolean value (True
or False
):
>>> not 1
False
>>> not 0
True
If you must have an integer, cast it back:
nyval = int(not myval)
However, the python bool
type is a subclass of int
, so this may not be needed:
>>> int(not 0)
1
>>> int(not 1)
0
>>> not 0 == 1
True
>>> not 1 == 0
True
Took DonkeyKong's example.
The issue is I needed to use a declared variable. This allows for stating your left and right-hand side of what you need to compare. This is for supporting an SSRS report where different fields must be linked based on the selection by the user.
The initial case sets the field choice based on the selection and then I can set the field I need to match on for the join.
A second case statement could be added for the right-hand side if the variable is needed to choose from different fields
LEFT OUTER JOIN Dashboard_Group_Level_Matching ON
case
when @Level = 'lvl1' then cw.Lvl1
when @Level = 'lvl2' then cw.Lvl2
when @Level = 'lvl3' then cw.Lvl3
end
= Dashboard_Group_Level_Matching.Dashboard_Level_Name
The code looks strange because the printf are not in any function blocks.
if you are using python3.x and opencv==4.1.0 then use following commands First of all
python -m pip install --user opencv-contrib-python
after that use this in the python script
cv2.face.LBPHFaceRecognizer_create()
You can just use exec
to replace your current shell with a new shell:
Switch to bash
:
exec bash
Switch to zsh
:
exec zsh
This won't affect new terminal windows or anything, but it's convenient.
The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
index.php
<html>
<body>
<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
site2.php
<html>
<body>
Hello <?php echo $_POST["name"]; ?>!<br>
Your mail is <?php echo $_POST["mail"]; ?>.
</body>
</html>
output
Hello "name" !
Your email is "[email protected]" .
A class is a reference type. When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data. A struct is a value type. When a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy. In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.
For Git
Create a new feature
via Terminal/Shell:
git checkout origin/feature/<featurename>
git merge --squash origin/feature/<featurename>
This doesnt commit it, allows you to review it first.
Then commit, and finish feature from this new branch, and delete/ignore the old one (the one you did dev on).
This was the first result on google when I pasted my error message, and it's because my arguments were out of order.
The container name has to be after all of the arguments.
Bad:
docker run <container_name> -v $(pwd):/src -it
Good:
docker run -v $(pwd):/src -it <container_name>
You need to override the color:
a { color:red } /* Globally */
/* Each state */
a:visited { text-decoration: none; color:red; }
a:hover { text-decoration: none; color:blue; }
a:focus { text-decoration: none; color:yellow; }
a:hover, a:active { text-decoration: none; color:black }
Nowadays you can use
try {
String s = CompletableFuture.supplyAsync(() -> br.readLine())
.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
System.out.println("Time out has occurred");
} catch (InterruptedException | ExecutionException e) {
// Handle
}
A connected socket is assigned to a new (dedicated) port
That's a common intuition, but it's incorrect. A connected socket is not assigned to a new/dedicated port. The only actual constraint that the TCP stack must satisfy is that the tuple of (local_address, local_port, remote_address, remote_port) must be unique for each socket connection. Thus the server can have many TCP sockets using the same local port, as long as each of the sockets on the port is connected to a different remote location.
See the "Socket Pair" paragraph at: http://books.google.com/books?id=ptSC4LpwGA0C&lpg=PA52&dq=socket%20pair%20tuple&pg=PA52#v=onepage&q=socket%20pair%20tuple&f=false
I think the wait/notify/notifyAll methods don't belong on the Object class as it pollutes all objects with methods that are rarely used. They make much more sense on a dedicated Lock class. So from this point of view, perhaps it's better to use a tool that is explicitly designed for the job at hand - ie ReentrantLock.
For those who are wondering where to run gradle commands:
gradlew build --refresh-dependencies
Buffer
is just a view for looking into an ArrayBuffer
.A Buffer
, in fact, is a FastBuffer
, which extends
(inherits from) Uint8Array
, which is an octet-unit view (“partial accessor”) of the actual memory, an ArrayBuffer
.
/lib/buffer.js#L65-L73
Node.js 9.4.0
class FastBuffer extends Uint8Array {
constructor(arg1, arg2, arg3) {
super(arg1, arg2, arg3);
}
}
FastBuffer.prototype.constructor = Buffer;
internalBuffer.FastBuffer = FastBuffer;
Buffer.prototype = FastBuffer.prototype;
ArrayBuffer
and the size of its view may vary.Buffer.from(arrayBuffer[, byteOffset[, length]])
.With Buffer.from(arrayBuffer[, byteOffset[, length]])
, you can create a Buffer
with specifying its underlying ArrayBuffer
and the view's position and size.
const test_buffer = Buffer.from(new ArrayBuffer(50), 40, 10);
console.info(test_buffer.buffer.byteLength); // 50; the size of the memory.
console.info(test_buffer.length); // 10; the size of the view.
FastBuffer
's memory allocation.It allocates the memory in two different ways depending on the size.
ArrayBuffer
that exactly fits the required memory./lib/buffer.js#L306-L320
Node.js 9.4.0
function allocate(size) {
if (size <= 0) {
return new FastBuffer();
}
if (size < (Buffer.poolSize >>> 1)) {
if (size > (poolSize - poolOffset))
createPool();
var b = new FastBuffer(allocPool, poolOffset, size);
poolOffset += size;
alignPool();
return b;
} else {
return createUnsafeBuffer(size);
}
}
/lib/buffer.js#L98-L100
Node.js 9.4.0
function createUnsafeBuffer(size) {
return new FastBuffer(createUnsafeArrayBuffer(size));
}
A memory pool is a fixed-size pre-allocated memory block for keeping small-size memory chunks for Buffer
s. Using it keeps the small-size memory chunks tightly together, so prevents fragmentation caused by separate management (allocation and deallocation) of small-size memory chunks.
In this case, the memory pools are ArrayBuffer
s whose size is 8 KiB by default, which is specified in Buffer.poolSize
. When it is to provide a small-size memory chunk for a Buffer
, it checks if the last memory pool has enough available memory to handle this; if so, it creates a Buffer
that “views” the given partial chunk of the memory pool, otherwise, it creates a new memory pool and so on.
You can access the underlying ArrayBuffer
of a Buffer
. The Buffer
's buffer
property (that is, inherited from Uint8Array
) holds it. A “small” Buffer
's buffer
property is an ArrayBuffer
that represents the entire memory pool. So in this case, the ArrayBuffer
and the Buffer
varies in size.
const zero_sized_buffer = Buffer.allocUnsafe(0);
const small_buffer = Buffer.from([0xC0, 0xFF, 0xEE]);
const big_buffer = Buffer.allocUnsafe(Buffer.poolSize >>> 1);
// A `Buffer`'s `length` property holds the size, in octets, of the view.
// An `ArrayBuffer`'s `byteLength` property holds the size, in octets, of its data.
console.info(zero_sized_buffer.length); /// 0; the view's size.
console.info(zero_sized_buffer.buffer.byteLength); /// 0; the memory..'s size.
console.info(Buffer.poolSize); /// 8192; a memory pool's size.
console.info(small_buffer.length); /// 3; the view's size.
console.info(small_buffer.buffer.byteLength); /// 8192; the memory pool's size.
console.info(Buffer.poolSize); /// 8192; a memory pool's size.
console.info(big_buffer.length); /// 4096; the view's size.
console.info(big_buffer.buffer.byteLength); /// 4096; the memory's size.
console.info(Buffer.poolSize); /// 8192; a memory pool's size.
An ArrayBuffer
is fixed in size, so we need to extract it out by making a copy of the part. To do this, we use Buffer
's byteOffset
property and length
property, which are inherited from Uint8Array
, and the ArrayBuffer.prototype.slice
method, which makes a copy of a part of an ArrayBuffer
. The slice()
-ing method herein was inspired by @ZachB.
const test_buffer = Buffer.from(new ArrayBuffer(10));
const zero_sized_buffer = Buffer.allocUnsafe(0);
const small_buffer = Buffer.from([0xC0, 0xFF, 0xEE]);
const big_buffer = Buffer.allocUnsafe(Buffer.poolSize >>> 1);
function extract_arraybuffer(buf)
{
// You may use the `byteLength` property instead of the `length` one.
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
}
// A copy -
const test_arraybuffer = extract_arraybuffer(test_buffer); // of the memory.
const zero_sized_arraybuffer = extract_arraybuffer(zero_sized_buffer); // of the... void.
const small_arraybuffer = extract_arraybuffer(small_buffer); // of the part of the memory.
const big_arraybuffer = extract_arraybuffer(big_buffer); // of the memory.
console.info(test_arraybuffer.byteLength); // 10
console.info(zero_sized_arraybuffer.byteLength); // 0
console.info(small_arraybuffer.byteLength); // 3
console.info(big_arraybuffer.byteLength); // 4096
If you're to use the results as read-only, or it is okay to modify the input Buffer
s' contents, you can avoid unnecessary memory copying.
const test_buffer = Buffer.from(new ArrayBuffer(10));
const zero_sized_buffer = Buffer.allocUnsafe(0);
const small_buffer = Buffer.from([0xC0, 0xFF, 0xEE]);
const big_buffer = Buffer.allocUnsafe(Buffer.poolSize >>> 1);
function obtain_arraybuffer(buf)
{
if(buf.length === buf.buffer.byteLength)
{
return buf.buffer;
} // else:
// You may use the `byteLength` property instead of the `length` one.
return buf.subarray(0, buf.length);
}
// Its underlying `ArrayBuffer`.
const test_arraybuffer = obtain_arraybuffer(test_buffer);
// Just a zero-sized `ArrayBuffer`.
const zero_sized_arraybuffer = obtain_arraybuffer(zero_sized_buffer);
// A copy of the part of the memory.
const small_arraybuffer = obtain_arraybuffer(small_buffer);
// Its underlying `ArrayBuffer`.
const big_arraybuffer = obtain_arraybuffer(big_buffer);
console.info(test_arraybuffer.byteLength); // 10
console.info(zero_sized_arraybuffer.byteLength); // 0
console.info(small_arraybuffer.byteLength); // 3
console.info(big_arraybuffer.byteLength); // 4096
it's easy
every folder of those you downloaded has a different kind of roboto font, means they are different fonts
example: "roboto_regular_macroman"
to use any of them:
1- extract the folder of the font you want to use
2- upload it near the css file
3- now include it in the css file
example for including the font which called "roboto_regular_macroman":
@font-face {
font-family: 'Roboto';
src: url('roboto_regular_macroman/Roboto-Regular-webfont.eot');
src: url('roboto_regular_macroman/Roboto-Regular-webfont.eot?#iefix') format('embedded-opentype'),
url('roboto_regular_macroman/Roboto-Regular-webfont.woff') format('woff'),
url('roboto_regular_macroman/Roboto-Regular-webfont.ttf') format('truetype'),
url('roboto_regular_macroman/Roboto-Regular-webfont.svg#RobotoRegular') format('svg');
font-weight: normal;
font-style: normal;
}
watch for the path of the files, here i uploaded the folder called "roboto_regular_macroman" in the same folder where the css is
then you can now simply use the font by typing font-family: 'Roboto';
If you need to work with DTOs rather than entities directly then you should retrieve the existing Customer instance and map the updated fields from the DTO to that.
Customer entity = //load from DB
//map fields from DTO to entity
Not tested but should work
products.sort((a,b)=>a.title.rendered > b.title.rendered)
For me the easiest way to go is to use range.
import csv
with open('files/filename.csv') as I:
reader = csv.reader(I)
fulllist = list(reader)
# Starting with data skipping header
for item in range(1, len(fulllist)):
# Print each row using "item" as the index value
print (fulllist[item])
You can customize material styles by setting different color properties. For example custom application theme
<style name="CustomAppTheme" parent="Theme.AppCompat">
<item name="android:textColorPrimaryDisableOnly">#00838f</item>
<item name="colorAccent">#e91e63</item>
</style>
Custom switch theme
<style name="MySwitch" parent="@style/Widget.AppCompat.CompoundButton.Switch">
<item name="android:textColorPrimaryDisableOnly">#b71c1c</item>
<item name="android:colorControlActivated">#1b5e20</item>
<item name="android:colorForeground">#f57f17</item>
<item name="android:textAppearance">@style/TextAppearance.AppCompat</item>
</style>
You can customize switch track and switch thumb like below image by defining xml drawables. For more information http://www.zoftino.com/android-switch-button-and-custom-switch-examples
if you are using Conda environment, you should set up config file again. And file location will be something like this. I did not setup config file after I created env in Conda and that was my connection problem.
C:\Users\syurt\AppData\Local\Continuum\anaconda3\envs\myenv\share\jupyter\jupyter_notebook_config.py
Short answer, yes, sort of. You can use Objective-C++, which you can read about at Apple Developer Connection.
If you know C++ already, learning Objective-C would be pretty simple, if you decided to give that a try. More info on that topic is at the ADC as well.
{{ }}
tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %}
template tag and then assign the value the same way you would in normal python code.
{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}
Result:
it worked
ALTER USER myuser WITH SUPERUSER;
You can read more at the Documentation
Step-by-step answer similar to the one you refer to, using the new cv2 Python bindings:
1. Read a grayscale image
import cv2
im_gray = cv2.imread('grayscale_image.png', cv2.IMREAD_GRAYSCALE)
2. Convert grayscale image to binary
(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
which determines the threshold automatically from the image using Otsu's method, or if you already know the threshold you can use:
thresh = 127
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]
3. Save to disk
cv2.imwrite('bw_image.png', im_bw)
When using guava (See doc) there is Iterators.forEnumeration
. Given an Enumeration x
you can do the following:
to get a immutable Set:
ImmutableSet.copyOf(Iterators.forEnumeration(x));
to get a immutable List:
ImmutableList.copyOf(Iterators.forEnumeration(x));
to get a hashSet:
Sets.newHashSet(Iterators.forEnumeration(x));
enctype="multipart/form-data"
Check your enctype in the form before submitting
This is what worked for me perfectly:-
// slide the view from its current position to below itself
public void slideUp(final View view, final View llDomestic){
ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationY",0f);
animation.setDuration(100);
llDomestic.setVisibility(View.GONE);
animation.start();
}
// slide the view from below itself to the current position
public void slideDown(View view,View llDomestic){
llDomestic.setVisibility(View.VISIBLE);
ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationY", 0f);
animation.setDuration(100);
animation.start();
}
llDomestic : The view which you want to hide. view: The view which you want to move down or up.
Reset all sequence from public
CREATE OR REPLACE FUNCTION "reset_sequence" (tablename text) RETURNS "pg_catalog"."void" AS
$body$
DECLARE
BEGIN
EXECUTE 'SELECT setval( '''
|| tablename
|| '_id_seq'', '
|| '(SELECT id + 1 FROM "'
|| tablename
|| '" ORDER BY id DESC LIMIT 1), false)';
END;
$body$ LANGUAGE 'plpgsql';
select sequence_name, reset_sequence(split_part(sequence_name, '_id_seq',1)) from information_schema.sequences
where sequence_schema='public';
This can also happen if the interpreter on your IDE is pointing to the wrong virtual environment. In VSCODE I've set it manually to the correct interpreter and my problem was solved.
Python 3:
import urllib.request
wp = urllib.request.urlopen("http://google.com")
pw = wp.read()
print(pw)
Python 2:
import urllib
import sys
wp = urllib.urlopen("http://google.com")
for line in wp:
sys.stdout.write(line)
While I have tested both the Codes in respective versions.
$("#startdate").data().datepicker.getFormattedDate('yyyy-mm-dd');
"use strict";
Basically it enables the strict mode.
Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.
As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.
So, there will be no major difference how "use strict";
is interpreted by the Chrome browser and Node.js.
Please read what is strict mode in JavaScript.
For more information:
ECMAScript 6 Code & strict mode. Following is brief from the specification:
10.2.1 Strict Mode Code
An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:
- Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
- Module code is always strict mode code.
- All parts of a ClassDeclaration or a ClassExpression are strict mode code.
- Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
- Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
- Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.
Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).
In addition to @Elltz answer, we can use both fill and image for background:
someNode.setBackground(
new Background(
Collections.singletonList(new BackgroundFill(
Color.WHITE,
new CornerRadii(500),
new Insets(10))),
Collections.singletonList(new BackgroundImage(
new Image("image/logo.png", 100, 100, false, true),
BackgroundRepeat.NO_REPEAT,
BackgroundRepeat.NO_REPEAT,
BackgroundPosition.CENTER,
BackgroundSize.DEFAULT))));
Use
setBackground(
new Background(
Collections.singletonList(new BackgroundFill(
Color.WHITE,
new CornerRadii(0),
new Insets(0))),
Collections.singletonList(new BackgroundImage(
new Image("file:clouds.jpg", 100, 100, false, true),
BackgroundRepeat.NO_REPEAT,
BackgroundRepeat.NO_REPEAT,
BackgroundPosition.DEFAULT,
new BackgroundSize(1.0, 1.0, true, true, false, false)
))));
(different last argument) to make the image full-window size.
So, after I created my question, I got this related list on the right with a similar issue: Organize routes in Node.js.
The answer in that post linked to the Express repo on GitHub and suggests to look at the 'route-separation' example.
This helped me change my code, and I now have it working. - Thanks for your comments.
My implementation ended up looking like this;
I require my routes in the app.js:
var express = require('express')
, site = require('./site')
, wiki = require('./wiki');
And I add my routes like this:
app.get('/', site.index);
app.get('/wiki/:id', wiki.show);
app.get('/wiki/:id/edit', wiki.edit);
I have two files called wiki.js and site.js in the root of my app, containing this:
exports.edit = function(req, res) {
var wiki_entry = req.params.id;
res.render('wiki/edit', {
title: 'Editing Wiki',
wiki: wiki_entry
})
}
var query = source.GroupBy(x => new { x.Column1, x.Column2 });
Additional comment. Yes this works:
sed 's/\"//g' infile.txt > outfile.txt
(however with batch gnu sed, will just print to screen)
In batch scripting (GNU SED), this was needed:
sed 's/\x22//g' infile.txt > outfile.txt
Typically enterprise applications in large organizations run with reduced privileges.
Database username may not have DDL
privilege for adding columns which hbm2ddl.auto=update
requires.
Here's a method that works by transforming the querystring into JSON...
var link = $('a').attr('href');
if (link.indexOf("?") != -1) {
var query = link.split("?")[1];
eval("query = {" + query.replace(/&/ig, "\",").replace(/=/ig, ":\"") + "\"};");
if (query.page)
alert(unescape(query.page));
else
alert('No page parameter');
} else {
alert('No querystring');
}
I'd go with a library like the others suggest though... =)
Even though you may have a head appending it may not work in all browsers. This was the only method I found to work consistently.
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"><\/script>');
}
</script>
If you have too much watchers and you need to clear all of them, you can push them into an array and destroy every $watch
in a loop.
var watchers = [];
watchers.push( $scope.$watch('watch-xxx', function(newVal){
//do something
}));
for(var i = 0; i < watchers.length; ++i){
if(typeof watchers[i] === 'function'){
watchers[i]();
}
}
watchers = [];
"no suitable driver" usually means that the syntax for the connection URL is incorrect.
Since you are not allowed to put more than two conditions in one condition group (And | Or) you have to create an extra nested group (MSDN). The expression A AND B AND C
looks like this:
<And>
A
<And>
B
C
</And>
</And>
Your SQL like sample translated to CAML (hopefully with matching XML tags ;) ):
<Where>
<And>
<Or>
<Eq>
<FieldRef Name='FirstName' />
<Value Type='Text'>John</Value>
</Eq>
<Or>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>John</Value>
</Eq>
<Eq>
<FieldRef Name='Profile' />
<Value Type='Text'>John</Value>
</Eq>
</Or>
</Or>
<And>
<Or>
<Eq>
<FieldRef Name='FirstName' />
<Value Type='Text'>Doe</Value>
</Eq>
<Or>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>Doe</Value>
</Eq>
<Eq>
<FieldRef Name='Profile' />
<Value Type='Text'>Doe</Value>
</Eq>
</Or>
</Or>
<Or>
<Eq>
<FieldRef Name='FirstName' />
<Value Type='Text'>123</Value>
</Eq>
<Or>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>123</Value>
</Eq>
<Eq>
<FieldRef Name='Profile' />
<Value Type='Text'>123</Value>
</Eq>
</Or>
</Or>
</And>
</And>
</Where>
Try this , its working and simple
HTML
?????????????????????<html>
<head></head>
<body>
<div class="forum">
test
</div>
</body>
</html>?????????????????????????????????????????????
Javascript
$(document).ready(function() {
var colorOrig=$(".forum").css('background-color');
$(".forum").hover(
function() {
//mouse over
$(this).css('background', '#ff0')
}, function() {
//mouse out
$(this).css('background', colorOrig)
});
});?
css ?
.forum{
background:#f0f;
}?
live demo
You need an HTML page to load a JS file.
You can use the tool APIC available here https://chrome.google.com/webstore/detail/apic-complete-api-solutio/ggnhohnkfcpcanfekomdkjffnfcjnjam. This tool allows you to test websocket which use either StompJS or native Websocket. More info here at www.apic.app
None of the solutions here solves my problem - only when I install Windows Update for universal C runtime.
Now CMake is working and no more link hangs from Visual Studio.
(void*) 0 is NULL, and '\0' represents the end of a string.
Weston Ruther built a similar thing using the WebKit proposal for css transitions:
http://weston.ruter.net/projects/jquery-css-transitions/
This implementation might be useful for you.
1) If you are using (PHP 5 >= 5.3.6) you can use SplFileInfo::getExtension — Gets the file extension
Example code
<?php
$info = new SplFileInfo('test.png');
var_dump($info->getExtension());
$info = new SplFileInfo('test.tar.gz');
var_dump($info->getExtension());
?>
This will output
string(3) "png"
string(2) "gz"
2) Another way of getting the extension if you are using (PHP 4 >= 4.0.3, PHP 5) is pathinfo
Example code
<?php
$ext = pathinfo('test.png', PATHINFO_EXTENSION);
var_dump($ext);
$ext = pathinfo('test.tar.gz', PATHINFO_EXTENSION);
var_dump($ext);
?>
This will output
string(3) "png"
string(2) "gz"
// EDIT: removed a bracket
You can do this thing:
Go to http://localhost/magento/downloader url. Here I am running the magento store on my localhost. Now you can login to magento connect manager and uninstall the extension which you installed previously.
Hope this works !!!!!
Thanks.
To change the default setting to display line numbers in vi/vim:
vi ~/.vimrc
then add the following line to the file:
set number
Either we can source ~/.vimrc
or save and quit by :wq
, now future vi/vim sessions will have numbering :)
Try this-
CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
insert into student (name,user_name,branch) values (name ,user_name,branch);
END
You may want to try window.focus() - but it may be annoying if the screen switches around
In AngularJS you can redirect your form (on submit) to other page by using window.location.href='';
like below:
postData(email){
if (email=='undefined') {
this.Utils.showToast('Invalid Email');
} else {
var origin = 'Dubai';
this.download.postEmail(email, origin).then(data => {
...
});
window.location.href = "https://www.thesoftdesign.com/";
}
}
Simply try this:
window.location.href = "https://www.thesoftdesign.com/";
I couldn't get any of the above solutions to work. However, I found a hack:
body {_x000D_
background-color: #ccc;_x000D_
}_x000D_
_x000D_
.container {_x000D_
width: 300px;_x000D_
background-color: white;_x000D_
}_x000D_
_x000D_
table {_x000D_
width: 100%;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td {_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
/* try removing the "hack" below to see how the table overflows the .body */_x000D_
.hack1 {_x000D_
display: table;_x000D_
table-layout: fixed;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.hack2 {_x000D_
display: table-cell;_x000D_
overflow-x: auto;_x000D_
width: 100%;_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
<div class="hack1">_x000D_
<div class="hack2">_x000D_
_x000D_
<table>_x000D_
<tr>_x000D_
<td>table or other arbitrary content</td>_x000D_
<td>that will cause your page to stretch</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>uncontrollably</td>_x000D_
<td>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
I use this little PowerShell snippet:
function Get-SystemUptime {
$operatingSystem = Get-WmiObject Win32_OperatingSystem
"$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}
which then yields something like the following:
PS> Get-SystemUptime
6.20:40:40.2625526
Assuming your my.jar has a class1 and class2 with a main defined in each, you can just call java like this:
java my.jar class1
java my.jar class2
If you need to specify other options to java just make sure they are before the my.jar
java -classpath my.jar class1
Oracle 10g has functions that allow the use of POSIX-compliant regular expressions in SQL:
See the Oracle Database SQL Reference for syntax details on this functions.
Take a look at Regular expressions in Perl with examples.
Code :
select * from tbl where regexp_like(col, '^(ABC|XYZ|PQR)');
CREATE PROCEDURE GetTaskEvents
@TaskName varchar(50),
@Id INT
AS
BEGIN
-- SP Logic
END
Procedure Calling
DECLARE @return_value nvarchar(50)
EXEC @return_value = GetTaskEvents
@TaskName = 'TaskName',
@Id =2
SELECT 'Return Value' = @return_value
Polymorphism is the ability for an object to appear in multiple forms. This involves using inheritance and virtual functions to build a family of objects which can be interchanged. The base class contains the prototypes of the virtual functions, possibly unimplemented or with default implementations as the application dictates, and the various derived classes each implements them differently to affect different behaviors.