I wrote this a while ago to remind myself of what a closure is and how it works in JS.
A closure is a function that, when called, uses the scope in which it was declared, not the scope in which it was called. In javaScript, all functions behave like this. Variable values in a scope persist as long as there is a function that still points to them. The exception to the rule is 'this', which refers to the object that the function is inside when it is called.
var z = 1;
function x(){
var z = 2;
y(function(){
alert(z);
});
}
function y(f){
var z = 3;
f();
}
x(); //alerts '2'
To create an empty multidimensional array in NumPy (e.g. a 2D array m*n
to store your matrix), in case you don't know m
how many rows you will append and don't care about the computational cost Stephen Simmons mentioned (namely re-buildinging the array at each append), you can squeeze to 0 the dimension to which you want to append to: X = np.empty(shape=[0, n])
.
This way you can use for example (here m = 5
which we assume we didn't know when creating the empty matrix, and n = 2
):
import numpy as np
n = 2
X = np.empty(shape=[0, n])
for i in range(5):
for j in range(2):
X = np.append(X, [[i, j]], axis=0)
print X
which will give you:
[[ 0. 0.]
[ 0. 1.]
[ 1. 0.]
[ 1. 1.]
[ 2. 0.]
[ 2. 1.]
[ 3. 0.]
[ 3. 1.]
[ 4. 0.]
[ 4. 1.]]
Looks like you use %p: Print Pointers
Embedded C is generally an extension of the C language, they are more or less similar. However, some differences do exist, such as:
C is generally used for desktop computers, while embedded C is for microcontroller based applications.
C can use the resources of a desktop PC like memory, OS, etc. While, embedded C has to use with the limited resources, such as RAM, ROM, I/Os on an embedded processor.
Embedded C includes extra features over C, such as fixed point types, multiple memory areas, and I/O register mapping.
Compilers for C (ANSI C) typically generate OS dependant executables. Embedded C requires compilers to create files to be downloaded to the microcontrollers/microprocessors where it needs to run.
If (UserID, Date) is unique, i.e. no date appears twice for the same user then:
select TheTable.UserID, TheTable.Value
from TheTable inner join (select UserID, max([Date]) MaxDate
from TheTable
group by UserID) UserMaxDate
on TheTable.UserID = UserMaxDate.UserID
TheTable.[Date] = UserMaxDate.MaxDate;
do a dir /s /b > out.txt
and then add a guide at position 260
In powershell cmd /c dir /s /b |? {$_.length -gt 260}
Use a memory stream
using(MemoryStream ms = new MemoryStream())
{
image.Save(ms, ...);
return ms.ToArray();
}
Note: If your issue is, "innodb index is marked as corrupted"! Then, the simple solution can be, just remove the indexes and add them again. That can solve pretty quickly without losing any records nor restarting or moving table contents into a temporary table and back.
First register a receiver in your manifest.xml file:
<receiver android:name="com.mileagelog.service.Broadcast_PowerUp" >
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
and then write a broadcast for this receiver like:
public class Broadcast_PowerUp extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
Toast.makeText(context, "Service_PowerUp Started",
Toast.LENGTH_LONG).show();
} else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
Toast.makeText(context, "Service_PowerUp Stoped", Toast.LENGTH_LONG)
.show();
}
}
}
It is possible to return a string with many values and variables using the template literals `${}`
like:
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return `${dCodes}, ${dCodes2}`;
};
It's short and simple.
It's an abstract reference value to a resource, often memory or an open file, or a pipe.
Properly, in Windows, (and generally in computing) a handle is an abstraction which hides a real memory address from the API user, allowing the system to reorganize physical memory transparently to the program. Resolving a handle into a pointer locks the memory, and releasing the handle invalidates the pointer. In this case think of it as an index into a table of pointers... you use the index for the system API calls, and the system can change the pointer in the table at will.
Alternatively a real pointer may be given as the handle when the API writer intends that the user of the API be insulated from the specifics of what the address returned points to; in this case it must be considered that what the handle points to may change at any time (from API version to version or even from call to call of the API that returns the handle) - the handle should therefore be treated as simply an opaque value meaningful only to the API.
I should add that in any modern operating system, even the so-called "real pointers" are still opaque handles into the virtual memory space of the process, which enables the O/S to manage and rearrange memory without invalidating the pointers within the process.
Even-though there have been a lot of great answers here, I just feel like pointing out, that nobody have put emphasis on..
It depends on the application
If you application is light on writes, as in you are reading a lot more data from the DB than you are writing. Then scaling django should be fairly trivial, heck, it comes with some fairly decent output/view caching straight out of the box. Make use of that, and say, redis as a cache provider, put a load balancer in front of it, spin up n-instances and you should be able to deal with a VERY large amount of traffic.
Now, if you have to do thousands of complex writes a second? Different story. Is Django going to be a bad choice? Well, not necessarily, depends on how you architect your solution really, and also, what your requirements are.
Just my two cents :-)
Extract Day, Month and Year
The highest voted function and the accepted one do NOT work locale-independently since the DATE command is subject to localization too. For example (the accepted one): In English you have YYYY for year and in Holland it is JJJJ. So this is a no-go. The following script takes the users' localization from the registry, which is locale-independent.
@echo off
::: Begin set date
setlocal EnableExtensions EnableDelayedExpansion
:: Determine short date format (independent from localization) from registry
for /f "skip=1 tokens=3-5 delims=- " %%L in ( '2^>nul reg query "HKCU\Control Panel\International" /v "sShortDate"' ) do (
:: Since we can have multiple (short) date formats we only use the first char from the format in a new variable
set "_L=%%L" && set "_L=!_L:~0,1!" && set "_M=%%M" && set "_M=!_M:~0,1!" && set "_N=%%N" && set "_N=!_N:~0,1!"
:: Now assign the date values to the new vars
for /f "tokens=2-4 delims=/-. " %%D in ( "%date%" ) do ( set "!_L!=%%D" && set "!_M!=%%E" && set "!_N!=%%F" )
)
:: Print the values as is
echo.
echo This is the original date string --^> %date%
echo These are the splitted values --^> Day: %d%, Month:%m%, Year: %y%.
echo.
endlocal
Extract only the Year
For a script I wrote I wanted only to extract the year (locale-independent) so I came up with this oneliner as I couldn't find any solution. It uses the 'DATE' var, multiple delimiters and checks for a number greater than 31. That then will be the current year. It's low on resources in contrast to some of the other solutions.
@echo off
setlocal EnableExtensions
for /f " tokens=2-4 delims=-./ " %%D in ( "%date%" ) do ( if %%D gtr 31 ( set "_YEAR=%%D" ) else ( if %%E gtr 31 ( set "_YEAR=%%E" ) else ( if %%F gtr 31 ( set "_YEAR=%%F" ) ) ) )
echo And the year is... %_YEAR%.
echo.
endlocal
It's worth refreshing this question, as newer versions of Matplotlib have made it much easier to position the legend outside the plot. I produced this example with Matplotlib version 3.1.1
.
Users can pass a 2-tuple of coordinates to the loc
parameter to position the legend anywhere in the bounding box. The only gotcha is you need to run plt.tight_layout()
to get matplotlib to recompute the plot dimensions so the legend is visible:
import matplotlib.pyplot as plt
plt.plot([0, 1], [0, 1], label="Label 1")
plt.plot([0, 1], [0, 2], label='Label 2')
plt.legend(loc=(1.05, 0.5))
plt.tight_layout()
This leads to the following plot:
References:
javac
(or java
during runtime) looks for the classes
being imported in the classpath
. If they are not there in the classpath
then classnotfound
exceptions are thrown.
classpath
is just like the path
variable in a shell, which is used by the shell to find a command or executable.
Entire directories or individual jar files can be put in the classpath
. Also, yes a classpath
can perhaps include a path which is not local but is somewhere on the internet. Please read more about classpath to resolve your doubts.
Take the number 123.456789
Floating point lets you represent most every number with a great deal of precision. Fixed is less precise, but simpler for the computer..
The only thing I know that has limited space is the BlockingQueue interface (which is e.g. implemented by the ArrayBlockingQueue class) - but they do not remove the first element if filled, but instead block the put operation until space is free (removed by other thread).
To my knowledge your trivial implementation is the easiest way to get such an behaviour.
// aspx.cs
// Load CheckBoxList selected items into ListBox
int status = 1;
foreach (ListItem s in chklstStates.Items )
{
if (s.Selected == true)
{
if (ListBox1.Items.Count == 0)
{
ListBox1.Items.Add(s.Text);
}
else
{
foreach (ListItem list in ListBox1.Items)
{
if (list.Text == s.Text)
{
status = status * 0;
}
else
{
status = status * 1;
}
}
if (status == 0)
{ }
else
{
ListBox1.Items.Add(s.Text);
}
status = 1;
}
}
}
}
Only from code:
namespace xxx.DsXxxTableAdapters {_x000D_
partial class ZzzTableAdapter_x000D_
{_x000D_
public void SetTimeout(int timeout)_x000D_
{_x000D_
if (this.Adapter.DeleteCommand != null) { this.Adapter.DeleteCommand.CommandTimeout = timeout; }_x000D_
if (this.Adapter.InsertCommand != null) { this.Adapter.InsertCommand.CommandTimeout = timeout; }_x000D_
if (this.Adapter.UpdateCommand != null) { this.Adapter.UpdateCommand.CommandTimeout = timeout; }_x000D_
if (this._commandCollection == null) { this.InitCommandCollection(); }_x000D_
if (this._commandCollection != null)_x000D_
{_x000D_
foreach (System.Data.SqlClient.SqlCommand item in this._commandCollection)_x000D_
{_x000D_
if (item != null)_x000D_
{ item.CommandTimeout = timeout; }_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
//...._x000D_
_x000D_
}
_x000D_
A very common cause of this error could be that the host API had mapped the request to a http method (e.g. PUT) and the API client is calling the API using a different http method (e.g. POST or GET)
Doesn't seem to be possible I'm afraid, its listed as a bug in workbench: http://bugs.mysql.com/bug.php?id=50692 It would be very useful though!
This is simple solution for get a list of dates
import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;
public class DateList
{
public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static void main (String[] args) throws java.lang.Exception
{
Date dt = new Date();
System.out.println(dt);
List<Date> dates = getDates("2017-01-01",dateFormat.format(new Date()));
//IF you don't want to reverse then remove Collections.reverse(dates);
Collections.reverse(dates);
System.out.println(dates.size());
for(Date date:dates)
{
System.out.println(date);
}
}
public static List<Date> getDates(String fromDate, String toDate)
{
ArrayList<Date> dates = new ArrayList<Date>();
try {
Calendar fromCal = Calendar.getInstance();
fromCal.setTime(dateFormat .parse(fromDate));
Calendar toCal = Calendar.getInstance();
toCal.setTime(dateFormat .parse(toDate));
while(!fromCal.after(toCal))
{
dates.add(fromCal.getTime());
fromCal.add(Calendar.DATE, 1);
}
} catch (Exception e) {
System.out.println(e);
}
return dates;
}
}
We can do with by using few lines of JS code:
if(typeof window.LIT !== 'undefined') {
clearTimeout(window.LIT);
}
window.LIT = setTimeout(() => this.updateTable(), 1000);
Simple solution! Work Perfect! Hope, will be helpful for you guys.
Use a loop
for(var i = 0; i < obj.length; ++i){
//do something with obj[i]
for(var ind in obj[i]) {
console.log(ind);
for(var vals in obj[i][ind]){
console.log(vals, obj[i][ind][vals]);
}
}
}
It might be appropriate to catch error within unit tests that check an assertion is made. If someone disables assertions or otherwise deletes the assertion you would want to know
In Servlet do:
String selectedRole = "rat"; // Or "cat" or whatever you'd like.
request.setAttribute("selectedRole", selectedRole);
Then in JSP do:
<select name="roleName">
<c:forEach items="${roleNames}" var="role">
<option value="${role}" ${role == selectedRole ? 'selected' : ''}>${role}</option>
</c:forEach>
</select>
It will print the selected
attribute of the HTML <option>
element so that you end up like:
<select name="roleName">
<option value="cat">cat</option>
<option value="rat" selected>rat</option>
<option value="unicorn">unicorn</option>
</select>
Apart from the problem: this is not a combo box. This is a dropdown. A combo box is an editable dropdown.
Log4j entry
#- File to log to and log format
log4j.appender.file.File=${LOG_PATH}/mylogfile.log
Java program
String log4jConfPath = "path/log4j.properties";
File log4jFile = new File(log4jConfPath);
if (log4jFile.exists()) {
System.setProperty("LOG_PATH", "c:/temp/");
PropertyConfigurator.configure(log4jFile.getAbsolutePath());
logger.trace("test123");
}
All answers were just a suggested solutions or workarounds. But still don't get answer to the question: why margin:auto works with position:relative but does not with position:absolute.
Following explanation was helpful for me:
"Margins make little sense on absolutely positioned elements since such elements are removed from the normal flow, thus they cannot push away any other elements on the page. Using margins like this can only affect the placement of the element to which the margin is applied, not any other element." http://www.justskins.com/forums/css-margins-and-absolute-82168.html
Why not just use substring... string.substring(0, 7);
The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.
var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);
KEY
is normally a synonym for INDEX
. The key attribute PRIMARY KEY
can also be specified as just KEY
when given in a column definition. This was implemented for compatibility with other database systems.
column_definition:
data_type [NOT NULL | NULL] [DEFAULT default_value]
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
...
Ref: http://dev.mysql.com/doc/refman/5.1/en/create-table.html
MySQL has 4 levels of collation: server, database, table, column. If you change the collation of the server, database or table, you don't change the setting for each column, but you change the default collations.
E.g if you change the default collation of a database, each new table you create in that database will use that collation, and if you change the default collation of a table, each column you create in that table will get that collation.
If you used the data-role collapsible e.g.
<div id="selector" data-role="collapsible" data-collapsed="true">
html......
</div>
then it will close the the expanded div
$("#selector").collapsible().collapsible("collapse");
Why not...
bool isEmpty = !list.Any();
if(isEmpty)
{
// error message
}
else
{
// show grid
}
The GridView
has also an EmptyDataTemplate
which is shown if the datasource is empty. This is an approach in ASP.NET:
<emptydatarowstyle backcolor="LightBlue" forecolor="Red"/>
<emptydatatemplate>
<asp:image id="NoDataErrorImg"
imageurl="~/images/NoDataError.jpg" runat="server"/>
No Data Found!
</emptydatatemplate>
If you're in a method bound to an event, simply return false:
@Component({
(...)
template: `
<a href="/test.html" (click)="doSomething()">Test</a>
`
})
export class MyComp {
doSomething() {
(...)
return false;
}
}
g++ -o foo foo.cpp
g++ --> Driver for cc1plus compiler
-o --> Indicates the output file (foo is the name of output file here. Can be any name)
foo.cpp --> Source file to be compiled
To execute the compiled file simply type
./foo
Use the parseJSON
method:
var json = '["City1","City2","City3"]';
var arr = $.parseJSON(json);
Then you have an array with the city names.
Because I will not admit the YUI/Crockford factory plan and because I like to keep things self contained and extensible this is my variation:
function Person(params)
{
this.name = params.name || defaultnamevalue;
this.role = params.role || defaultrolevalue;
if(typeof(this.speak)=='undefined') //guarantees one time prototyping
{
Person.prototype.speak = function() {/* do whatever */};
}
}
var Robert = new Person({name:'Bob'});
where ideally the typeof test is on something like the first method prototyped
If you don't want to use the libraries and want simple answer then the code is given below:
def swap_alpha(test_string):
new_string = ""
for i in test_string:
if i.upper() in test_string:
new_string += i.lower()
elif i.lower():
new_string += i.upper()
else:
return "invalid "
return new_string
user_string = input("enter the string:")
updated = swap_alpha(user_string)
print(updated)
Technically, you can too put image data in an img tag, using data URIs.
<img src="data:image/jpeg;base64,<?php echo base64_encode( $image_data ); ?>" />
There are some special circumstances where this could even be useful, although in most cases you're better off serving the image through a separate script like daiscog suggests.
After several hours of troubleshooting, I found this issue to be caused by having Oracle.DataAccess.dll (v4.0) in my projects bin directory, but the runtime also loading Oracle.DataAccess.dll (v2.x) from the GAC. Removing and readding the Oracle.DataAccess entry in the project references solved the problem for me.
The other files mentioned here did not appear to be necessary in my situation.
The root cause of the "The provider is not compatible with the version of Oracle client" error is (generally) that the managed assembly is attempting to load unmanaged libraries which do not match versions. It appears you can force the Oracle driver to use the correct libraries by specifying the library path in the web.config1
<configuration>
<oracle.dataaccess.client>
<settings>
<add name="DllPath" value="C:\oracle\bin"/>
<!-- ... -->
</settings>
</oracle.dataaccess.client>
</configuration>
Note that since git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1 and release note, June 2012) mentions:
"
git push --recurse-submodules
" learned to optionally look into the histories of submodules bound to the superproject and push them out.
Probably done after this patch and the --on-demand
option:
recurse-submodules=<check|on-demand>::
Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.
- If
check
is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
Otherwise the push will be aborted and exit with non-zero status.- If
on-demand
is used, all submodules that changed in the revisions to be pushed will be pushed.
If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.
So you could push everything in one go with (from the parent repo) a:
git push --recurse-submodules=on-demand
This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.
With git 2.7 (January 2016), a simple git push will be enough to push the parent repo... and all its submodules.
See commit d34141c, commit f5c7cd9 (03 Dec 2015), commit f5c7cd9 (03 Dec 2015), and commit b33a15b (17 Nov 2015) by Mike Crowe (mikecrowe
).
(Merged by Junio C Hamano -- gitster
-- in commit 5d35d72, 21 Dec 2015)
push
: addrecurseSubmodules
config optionThe
--recurse-submodules
command line parameter has existed for some time but it has no config file equivalent.Following the style of the corresponding parameter for
git fetch
, let's inventpush.recurseSubmodules
to provide a default for this parameter.
This also requires the addition of--recurse-submodules=no
to allow the configuration to be overridden on the command line when required.The most straightforward way to implement this appears to be to make
push
use code insubmodule-config
in a similar way tofetch
.
The git config
doc now include:
push.recurseSubmodules
:Make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch.
- If the value is '
check
', then Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing, the push will be aborted and exit with non-zero status.- If the value is '
on-demand
' then all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. -- If the value is '
no
' then default behavior of ignoring submodules when pushing is retained.You may override this configuration at time of push by specifying '
--recurse-submodules=check|on-demand|no
'.
So:
git config push.recurseSubmodules on-demand
git push
Git 2.12 (Q1 2017)
git push --dry-run --recurse-submodules=on-demand
will actually work.
See commit 0301c82, commit 1aa7365 (17 Nov 2016) by Brandon Williams (mbrandonw
).
(Merged by Junio C Hamano -- gitster
-- in commit 12cf113, 16 Dec 2016)
push run with --dry-run
doesn't actually (Git 2.11 Dec. 2016 and lower/before) perform a dry-run when push is configured to push submodules on-demand.
Instead all submodules which need to be pushed are actually pushed to their remotes while any updates for the superproject are performed as a dry-run.
This is a bug and not the intended behaviour of a dry-run.Teach
push
to respect the--dry-run
option when configured to recursively push submodules 'on-demand'.
This is done by passing the--dry-run
flag to the child process which performs a push for a submodules when performing a dry-run.
And still in Git 2.12, you now havea "--recurse-submodules=only
" option to push submodules out without pushing the top-level superproject.
See commit 225e8bf, commit 6c656c3, commit 14c01bd (19 Dec 2016) by Brandon Williams (mbrandonw
).
(Merged by Junio C Hamano -- gitster
-- in commit 792e22e, 31 Jan 2017)
This answer has a code example, which implements the algorithm described in the paper Practical In-Place Merging by Bing-Chao Huang and Michael A. Langston. I have to admit that I do not understand the details, but the given complexity of the merge step is O(n).
From a practical perspective, there is evidence that pure in-place implementations are not performing better in real world scenarios. For example, the C++ standard defines std::inplace_merge, which is as the name implies an in-place merge operation.
Assuming that C++ libraries are typically very well optimized, it is interesting to see how it is implemented:
The implementation delegates to __inplace_merge, which dodges the problem by trying to allocate a temporary buffer:
typedef _Temporary_buffer<_BidirectionalIterator, _ValueType> _TmpBuf;
_TmpBuf __buf(__first, __len1 + __len2);
if (__buf.begin() == 0)
std::__merge_without_buffer
(__first, __middle, __last, __len1, __len2, __comp);
else
std::__merge_adaptive
(__first, __middle, __last, __len1, __len2, __buf.begin(),
_DistanceType(__buf.size()), __comp);
Otherwise, it falls back to an implementation (__merge_without_buffer), which requires no extra memory, but no longer runs in O(n) time.
Looks similar. It delegates to a function, which also tries to allocate a buffer. Depending on whether it got enough elements, it will choose the implementation. The constant-memory fallback function is called __buffered_inplace_merge.
Maybe even the fallback is still O(n) time, but the point is that they do not use the implementation if temporary memory is available.
Note that the C++ standard explicitly gives implementations the freedom to choose this approach by lowering the required complexity from O(n) to O(N log N):
Complexity: Exactly N-1 comparisons if enough additional memory is available. If the memory is insufficient, O(N log N) comparisons.
Of course, this cannot be taken as a proof that constant space in-place merges in O(n) time should never be used. On the other hand, if it would be faster, the optimized C++ libraries would probably switch to that type of implementation.
The instance in which you're using a single character (i.e. | or &) is a bitwise comparison of the results. As long as your language evaluates these expressions to a binary value they should return the same results. As a best practice, however, you should use the logical operator as that's what you mean (I think).
You can use the CssClass property of the hyperlink:
LiteralControl ltr = new LiteralControl();
ltr.Text = "<style type=\"text/css\" rel=\"stylesheet\">" +
@".d
{
background-color:Red;
}
.d:hover
{
background-color:Yellow;
}
</style>
";
this.Page.Header.Controls.Add(ltr);
this.HyperLink1.CssClass = "d";
Well in JavaScript you can check two strings for values same as integers so yo can do this:
"A" < "B"
"A" == "B"
"A" > "B"
And therefore you can make your own function that checks strings the same way as the strcmp()
.
So this would be the function that does the same:
function strcmp(a, b)
{
return (a<b?-1:(a>b?1:0));
}
I've solved the problem by add attribute 'defer' to the 'script' element.
BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
You can also watch the video about this new featue
UPDATE as of angularjs 1.2, the way animations work has changed drastically, most of it is now controlled with CSS, without having to setup javascript callbacks, etc.. You can check the updated tutorial on Year Of Moo. @dfsq pointed out in the comments a nice set of examples.
It's (Get-NetTCPConnection -LocalPort "port no.").OwningProcess
if &
is used in html then you should escape it
If &
is used in javascript strings e.g. an alert('This & that');
or document.href you don't need to use it.
If you're using document.write then you should use it e.g. document.write(<p>this & that</p>)
I also encountered the same problem. I solve the problem by executing the following sql:
ALTER ${table} ROW_FORMAT=COMPRESSED;
But, I think u should know about the Row Storage.
There are two kinds of columns: variable-length column(such as VARCHAR, VARBINARY, and BLOB and TEXT types) and fixed-length column. They are stored in different types of pages.
Variable-length columns are an exception to this rule. Columns such as BLOB and VARCHAR that are too long to fit on a B-tree page are stored on separately allocated disk pages called overflow pages. We call such columns off-page columns. The values of these columns are stored in singly-linked lists of overflow pages, and each such column has its own list of one or more overflow pages. In some cases, all or a prefix of the long column value is stored in the B-tree, to avoid wasting storage and eliminating the need to read a separate page.
and when purpose of setting ROW_FORMAT is
When a table is created with ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED, InnoDB can store long variable-length column values (for VARCHAR, VARBINARY, and BLOB and TEXT types) fully off-page, with the clustered index record containing only a 20-byte pointer to the overflow page.
Wanna know more about DYNAMIC and COMPRESSED Row Formats
Check this out as well: using xml path
and pivot
| ACCOUNT | 2000 | 2001 | 2002 |
--------------------------------
| Asset | 205 | 142 | 421 |
| Equity | 365 | 214 | 163 |
| Profit | 524 | 421 | 325 |
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.period)
FROM demo c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT account, ' + @cols + ' from
(
select account
, value
, period
from demo
) x
pivot
(
max(value)
for period in (' + @cols + ')
) p '
execute(@query)
$product=Mage::getModel('catalog/product')->load($product_id);
above code not working for me. its throw exception;
This is working for me for get product details.
$obj = Mage::getModel('catalog/product');
$_product = $obj->load($product_id);
So use for for product type.
$productType = $_product->getTypeId();
Add in numberOfRowsInSection your code [self.tableView setContentInset:UIEdgeInsetsMake(108, 0, 0, 0)];
. So you will set your contentInset always you reload data in your table
I used .eslintrc.js and I have added following code.
module.exports = {
"parserOptions": {
"ecmaVersion": 6
}
};
To understand the various transactional settings and behaviours adopted for Transaction management, such as REQUIRED
, ISOLATION
etc. you'll have to understand the basics of transaction management itself.
Read Trasaction management for more on explanation.
#include<stdio.h>
void main()
{
char a;
scanf("%c",&a);
printf("%d",a);
}
It happens to me sometimes, I always fixed that with "mvn eclipse:clean" command to clean old properties and then run mvn eclipse:eclipse -Dwtpversion=2.0 (for web project of course). There are some old properties saved so eclipse is confused sometimes.
The other case involving print >>obj, "Hello World"
is the "print chevron" syntax for the print
statement in Python 2 (removed in Python 3, replaced by the file
argument of the print()
function). Instead of writing to standard output, the output is passed to the obj.write()
method. A typical example would be file objects having a write()
method. See the answer to a more recent question: Double greater-than sign in Python.
I came across the same question a few weeks ago and this is the result from what I found. This method does a quick dump of HTML to a PDF. The document will most likely need some format tweaking.
private MemoryStream createPDF(string html)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(html);
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
// step 2:
// we create a writer that listens to the document
// and directs a XML-stream to a file
PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
// step 3: we create a worker parse the document
HTMLWorker worker = new HTMLWorker(document);
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(reader);
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
return msOutput;
}
Please be careful not to overwrite the ";secure" cookie flag in https-sessions. This flag prevents the browser from sending the cookie over an unencrypted http connection, basically rendering the use of https for legit requests pointless.
private void rewriteCookieToHeader(HttpServletRequest request, HttpServletResponse response) {
if (response.containsHeader("SET-COOKIE")) {
String sessionid = request.getSession().getId();
String contextPath = request.getContextPath();
String secure = "";
if (request.isSecure()) {
secure = "; Secure";
}
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid
+ "; Path=" + contextPath + "; HttpOnly" + secure);
}
}
This happened after the homebrew install and occurs due to permission issues. The following commands fixed the issue.
sudo chown -R _mysql:mysql /usr/local/var/mysql
sudo mysql.server start
You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-
(untested code)
Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")
' now you can manipulate the data in the workbook anyway you want, e.g. '
Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value
Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False
' etc '
Call wbk.Close(False)
Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.
This tree is not a binary tree, so you need an array of the children elements, like List.
public Node(Object data, List<Node> children) {
this.data = data;
this.children = children;
}
Then create the instances.
This is a ready to use code, merging four pdf files with itext.jar from http://central.maven.org/maven2/com/itextpdf/itextpdf/5.5.0/itextpdf-5.5.0.jar, more on http://tutorialspointexamples.com/
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
/**
* This class is used to merge two or more
* existing pdf file using iText jar.
*/
public class PDFMerger {
static void mergePdfFiles(List<InputStream> inputPdfList,
OutputStream outputStream) throws Exception{
//Create document and pdfReader objects.
Document document = new Document();
List<PdfReader> readers =
new ArrayList<PdfReader>();
int totalPages = 0;
//Create pdf Iterator object using inputPdfList.
Iterator<InputStream> pdfIterator =
inputPdfList.iterator();
// Create reader list for the input pdf files.
while (pdfIterator.hasNext()) {
InputStream pdf = pdfIterator.next();
PdfReader pdfReader = new PdfReader(pdf);
readers.add(pdfReader);
totalPages = totalPages + pdfReader.getNumberOfPages();
}
// Create writer for the outputStream
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
//Open document.
document.open();
//Contain the pdf data.
PdfContentByte pageContentByte = writer.getDirectContent();
PdfImportedPage pdfImportedPage;
int currentPdfReaderPage = 1;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
// Iterate and process the reader list.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
//Create page and add content.
while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) {
document.newPage();
pdfImportedPage = writer.getImportedPage(
pdfReader,currentPdfReaderPage);
pageContentByte.addTemplate(pdfImportedPage, 0, 0);
currentPdfReaderPage++;
}
currentPdfReaderPage = 1;
}
//Close document and outputStream.
outputStream.flush();
document.close();
outputStream.close();
System.out.println("Pdf files merged successfully.");
}
public static void main(String args[]){
try {
//Prepare input pdf file list as list of input stream.
List<InputStream> inputPdfList = new ArrayList<InputStream>();
inputPdfList.add(new FileInputStream("..\\pdf\\pdf_1.pdf"));
inputPdfList.add(new FileInputStream("..\\pdf\\pdf_2.pdf"));
inputPdfList.add(new FileInputStream("..\\pdf\\pdf_3.pdf"));
inputPdfList.add(new FileInputStream("..\\pdf\\pdf_4.pdf"));
//Prepare output stream for merged pdf file.
OutputStream outputStream =
new FileOutputStream("..\\pdf\\MergeFile_1234.pdf");
//call method to merge pdf files.
mergePdfFiles(inputPdfList, outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
}
A simple comparison against string works:
<c:when test="${someModel.status == 'OLD'}">
Error is coming in your code from this statement as you said
Intent intent = new Intent(context, SendMessage.class);
This is due to you are providing context of OnItemClickListener anonymous class into the Intent constructor but according to constructor of Intent
android.content.Intent.Intent(Context packageContext, Class<?> cls)
You have to provide context of you activity in which you are using intent that is the MainActivity class context. so your statement which is giving error will be converted to
Intent intent = new Intent(MainActivity.this, SendMessage.class);
Also for sending your message from this MainActivity to SendMessage class please see below code
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
Intent intent = new Intent(MainActivity.this, SendMessage.class);
intent.putExtra(EXTRA_MESSAGE, entry.getMessage());
startActivity(intent);
}
});
Please let me know if this helps you
EDIT:- If you are finding some issue to get the value of list do one thing declear your array list
ArrayList<ListEntry> members = new ArrayList<ListEntry>();
globally i.e. before oncreate and change your listener as below
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(MainActivity.this, SendMessage.class);
intent.putExtra(EXTRA_MESSAGE, members.get(position));
startActivity(intent);
}
});
So your whole code will look as
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.ListViewTest.MESSAGE";
ArrayList<ListEntry> members = new ArrayList<ListEntry>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
members.add(new ListEntry("BBB","AAA",R.drawable.tab1_hdpi));
members.add(new ListEntry("ccc","ddd",R.drawable.tab2_hdpi));
members.add(new ListEntry("assa","cxv",R.drawable.tab3_hdpi));
members.add(new ListEntry("BcxsadvBB","AcxdxvAA"));
members.add(new ListEntry("BcxvadsBB","AcxzvAA"));
members.add(new ListEntry("BcxvBB","AcxvAA"));
members.add(new ListEntry("BvBB","AcxsvAA"));
members.add(new ListEntry("BcxvBB","AcxsvzAA"));
members.add(new ListEntry("Bcxadv","AcsxvAA"));
members.add(new ListEntry("BcxcxB","AcxsvAA"));
ListView lv = (ListView)findViewById(R.id.listView1);
Log.i("testTag","before start adapter");
StringArrayAdapter ad = new StringArrayAdapter (members,this);
Log.i("testTag","after start adapter");
Log.i("testTag","set adapter");
lv.setAdapter(ad);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(MainActivity.this, SendMessage.class);
intent.putExtra(EXTRA_MESSAGE, members.get(position).getMessage());
startActivity(intent);
}
});
}
Where getMessage() will be a getter method specified in your ListEntry class which you are using to get message which was previously set.
C# doesn't have an explicit line break character. You statements end with a semicolon so you can span your statements over many lines. These are both the same:
public string GenerateString()
{
return "abc" + "def";
}
public string GenerateString()
{
return
"abc" +
"def";
}
I agree with Leac. I actually play with Scratch sometimes if I'm bored. It's a pretty fun visual way of looking at code.
How it works is, they give you a bunch of "blocks" (these look like legos) which you can stack. And by stacking these blocks, and interacting with the canvas (where you put your sprites, graphics), you can create games, movies, slideshows... it's really interesting.
When it's complete you can upload it right to the Scratch websites, which is a youtube-ish portal for Scratch applications. Not only that, but you can download any submission on the website, and learn from or extend other Scratch applications.
A somewhat different approach using ggplot2:
dat <- read.table(text = "A B C D E F G
1 480 780 431 295 670 360 190
2 720 350 377 255 340 615 345
3 460 480 179 560 60 735 1260
4 220 240 876 789 820 100 75", header = TRUE)
library(reshape2)
dat$row <- seq_len(nrow(dat))
dat2 <- melt(dat, id.vars = "row")
library(ggplot2)
ggplot(dat2, aes(x = variable, y = value, fill = row)) +
geom_bar(stat = "identity") +
xlab("\nType") +
ylab("Time\n") +
guides(fill = FALSE) +
theme_bw()
this gives:
When you want to include a legend, delete the guides(fill = FALSE)
line.
I think this answers your question, because it is like a "for each" loop.
The script below is valid in python (version 3.8):
a=[1,7,77,7777,77777,777777,7777777,765,456,345,2342,4]
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
I suppose you're getting this JSON from a server or a file, and you want to create a JSONArray object out of it.
String strJSON = ""; // your string goes here
JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue();
// once you get the array, you may check items like
JSONOBject jObject = jArray.getJSONObject(0);
Hope this helps :)
Microsoft Visual Studio Express
It's a full IDE, with powerful debugging tools, syntax highlighting, etc.
DELETE
p1
FROM posts AS p1
CROSS JOIN (
SELECT ID FROM posts GROUP BY id HAVING COUNT(id) > 1
) AS p2
USING (id)
The error happens because of you are trying to map a numeric vector to data
in geom_errorbar
: GVW[1:64,3]
. ggplot
only works with data.frame
.
In general, you shouldn't subset inside ggplot
calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame
and you will be able to plot everything in one call.
Here with a dplyr
solution to summarise the data and compute the standard error beforehand.
library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
summarise(mean = mean(value),se = sd(value) / sqrt(n()))
ggplot(d, aes(x = variable, y = mean, fill = Genotype)) +
geom_bar(position = position_dodge(), stat = "identity",
colour="black", size=.3) +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
size=.3, width=.2, position=position_dodge(.9)) +
xlab("Time") +
ylab("Weight [g]") +
scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"),
labels = c("Knock-out", "Wild type")) +
ggtitle("Effect of genotype on weight-gain") +
scale_y_continuous(breaks = 0:20*4) +
theme_bw()
Actually, that does not delete the variable/property. All it will do is set its value to None
, therefore the variable will still take up space in memory. If you want to completely wipe all existence of the variable from memory, you can just type:
del self.left
I am also behind firewall, this worked for me!!
System.setProperty("http.proxyHost", "proxy host addr");
System.setProperty("http.proxyPort", "808");
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("domain\\user","password".toCharArray());
}
});
URL url = new URL("http://www.google.com/");
URLConnection con = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
// Read it ...
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
To reset or change the password enter sudo dpkg-reconfigure mysql-server-X.X
(X.X is mysql version you have installed i.e. 5.6, 5.7) and then you will prompt a screen where you have to set the new password and then in next step confirm the password and just wait for a moment. That's it.
If you use Java and spring MVC you just need to add the following annotation to your method returning your page :
@CrossOrigin(origins = "*")
"*" is to allow your page to be accessible from anywhere. See https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Access-Control-Allow-Origin for more details about that.
Use -regex
:
From the man page:
-regex pattern
File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named './fubar3', you can use the
regular expression '.*bar.' or '.*b.*3', but not 'b.*r3'.
Also, I don't believe find
supports regex extensions such as \d
. You need to use [0-9]
.
find . -regex '.*test\.log\.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\.zip'
For me, there was a mistake in the settings.xml. I was using http:// in the url due to which it wasn't working. Once i removed it the plugins were downloaded successfully.
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<host>www-proxy.xxxx.com</host>
<port>80</port>
<!-- <nonProxyHosts>local.net</nonProxyHosts>-->
</proxy>
<!-- Proxy for HTTPS -->
<proxy>
<id>optional1</id>
<active>true</active>
<protocol>https</protocol>
<host>www-proxy.xxxx.com</host>
<port>80</port>
<!--<nonProxyHosts>local.net</nonProxyHosts>-->
</proxy>
Install
If you use homebrew (which I recommend), you can install selenium using:
brew install selenium-server-standalone
Running
updated -port port_number
To run selenium, do: selenium-server -port 4444
For more options: selenium-server -help
I had a similar problem and was able to solve it by following the below approach (similar to other answers but needed credentials too),
1- add Microsoft.SharePointOnline.CSOM by tools->NuGet Package Manager->Manage NuGet Packages for solution->Browse-> select and install
2- Add "using Microsoft.SharePoint.Client; "
then the below code
string siteUrl = "https://yourcompany.sharepoint.com/sites/Yoursite";
SecureString passWord = new SecureString();
var password = "Your password here";
var securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
ClientContext clientContext = new ClientContext(siteUrl);
clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", securePassword);/*passWord*/
List oList = clientContext.Web.Lists.GetByTitle("The name of your list here");
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem oListItem = oList.AddItem(itemCreateInfo);
oListItem["PK"] = "1";
oListItem["Precinct"] = "Mangere";
oListItem["Title"] = "Innovation";
oListItem["Project_x005F_x0020_Name"] = "test from C#";
oListItem["Project_x005F_x0020_ID"] = "ID_123_from C#";
oListItem["Project_x005F_x0020_start_x005F_x0020_date"] = "2020-05-01 01:01:01";
oListItem.Update();
clientContext.ExecuteQuery();
Remember that your fields may be different with what you see, for example in my list I see "Project Name", while the actual value is "Project_x005F_x0020_ID". How to get these values (i.e. internal filed values)?
A few approaches:
1- Use MS flow and see them
2- https://mstechtalk.com/check-column-internal-name-sharepoint-list/ or https://sharepoint.stackexchange.com/questions/787/finding-the-internal-name-and-display-name-for-a-list-column
3- Use a C# reader and read your sharepoint list
The rest of operations (update/delete): https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ee539976(v%3Doffice.14)
I just had the same problem and literally nothing worked for me. The error was showing kerberos
is causing the problem and it was one of the mongoose
dependencies. Since I'm on Ubuntu, I thought there might be permission issues somewhere between the globally installed packages -- in /usr/lib/node_modules
via sudo
, and those which are on the user space.
I installed mongoose
globally -- with sudo
of course, and everything began working as expected.
P.S. The kerberos
package now also is installed globally next to mongoose
, however I can't remember if I did it deliberately -- while I was trying to solve the problem, or if it was there from the beginning.
On some systems (Windows with VC springs to mind, currently), RAND_MAX
is ridiculously small, i. e. only 15 bit. When dividing by RAND_MAX
you are only generating a mantissa of 15 bit instead of the 23 possible bits. This may or may not be a problem for you, but you're missing out some values in that case.
Oh, just noticed that there was already a comment for that problem. Anyway, here's some code that might solve this for you:
float r = (float)((rand() << 15 + rand()) & ((1 << 24) - 1)) / (1 << 24);
Untested, but might work :-)
With Spring it's easy. Be it a file, or folder, or even multiple files, there are chances, you can do it via injection.
This example demonstrates the injection of multiple files located in x/y/z
folder.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
@Service
public class StackoverflowService {
@Value("classpath:x/y/z/*")
private Resource[] resources;
public List<String> getResourceNames() {
return Arrays.stream(resources)
.map(Resource::getFilename)
.collect(Collectors.toList());
}
}
It does work for resources in the filesystem as well as in JARs.
please check this code
String pass = EditText.getText().toString();
if(TextUtils.isEmpty(pass) || pass.length < [YOUR MIN LENGTH])
{
EditText.setError("You must have x characters in your txt");
return;
}
//continue processing
edittext.setOnFocusChangeListener( new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
// USE your code here
}
USe the below link for more details about edittext and the edittextfilteres with text watcher..
Out of the following two:
(1) List<?> myList = new ArrayList<?>();
(2) ArrayList<?> myList = new ArrayList<?>();
First is generally preferred. As you will be using methods from List
interface only, it provides you the freedom to use some other implementation of List
e.g. LinkedList
in future. So it decouples you from specific implementation. Now there are two points worth mentioning:
ArrayList
over LinkedList
. More here.I am wondering if anyone uses (2)
Yes sometimes (read rarely). When we need methods that are part of implementation of ArrayList
but not part of the interface List
. For example ensureCapacity
.
Also, how often (and can I please get an example) does the situation actually require using (1) over (2)
Almost always you prefer option (1). This is a classical design pattern in OOP where you always try to decouple your code from specific implementation and program to the interface.
var inValid = new RegExp('^[_A-z0-9]{1,}$');
var value = "test string";
var k = inValid.test(value);
alert(k);
Use:
MessageBoxResult m = MessageBox.Show("The file will be saved here.", "File Save", MessageBoxButton.OKCancel);
if(m == m.Yes)
{
// Do something
}
else if (m == m.No)
{
// Do something else
}
MessageBoxResult is used on Windows Phone instead of DialogResult...
Works for every browser.
<button type="button" onClick="Refresh()">Close</button>
<script>
function Refresh() {
window.parent.location = window.parent.location.href;
}
</script>
in mongodb2.0
you should type
rs.slaveOk()
in secondary mongod node
For the least lines of code and the simplest case
if(s.equals(new StringBuilder(s).reverse().toString())) // is a palindrome.
A char
is an integral type. When you write
char ch = 'A';
you're setting the value of ch
to whatever number your compiler uses to represent the character 'A'
. That's usually the ASCII code for 'A'
these days, but that's not required. You're almost certainly using a system that uses ASCII.
Like any numeric type, you can initialize it with an ordinary number:
char ch = 13;
If you want do do arithmetic on a char
value, just do it: ch = ch + 1;
etc.
However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char
values as characters rather than numbers. There are a couple of ways to do that.
std::cout << +ch << '\n';
std::cout << int(ch) << '\n'
NSAttributedString *attributedText =[[[NSAttributedString alloc]
initWithString:joyMeComment.content
attributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:TextFont]}] autorelease];
CGRect paragraphRect =
[attributedText boundingRectWithSize:CGSizeMake(kWith, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil];
contentSize = paragraphRect.size;
contentSize.size.height+=10;
label.frame=contentSize;
if label's frame not add 10 this method will never work! hope this can help you! goog luck.
Quickest way to convert .ui to .py is from terminal:
pyuic4 -x input.ui -o output.py
Make sure you have pyqt4-dev-tools installed.
You can access the fields by indexing the object array:
foreach (object[] item in selectedValues)
{
idTextBox.Text = item[0];
titleTextBox.Text = item[1];
contentTextBox.Text = item[2];
}
That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:
public class MyObject
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
Then you can do:
foreach (MyObject item in selectedValues)
{
idTextBox.Text = item.Id;
titleTextBox.Text = item.Title;
contentTextBox.Text = item.Content;
}
In addition to the excellent answer by Chris Morris above, I found a very interesting way you can receive this same fault if you are calling to a virtual method that hasn't been set to pure but doesn't its own implementation. It is the exact same reason (the compiler can't find an implementation of the method and therefore crooks), but my IDE did not catch this fault in the least bit.
for example, the following code would get a compilation error with the same error message:
//code testing an interface
class test
{
void myFunc();
}
//define an interface
class IamInterface
{
virtual void myFunc();
}
//implementation of the interface
class IamConcreteImpl
{
void myFunc()
{
1+1=2;
}
}
However, changing IamInterface myFunc() to be a pure virtual method (a method that "must" be implemented, that than a virtual method which is a method the "can" be overridden) will eliminate the compilation error.
//define an interface
class IamInterface
{
virtual void myFunc() = 0;
}
Hopes this helps the next StackOverFlow person stepping through code!
Perl 5.10+ contains the 'smart-match' operator ~~
, which returns true if a certain element is contained in an array or hash, and false if it doesn't (see perlfaq4):
The nice thing is that it also supports regexes, meaning that your case-insensitive requirement can easily be taken care of:
use strict;
use warnings;
use 5.010;
my @array = qw/aaa bbb/;
my $wanted = 'aAa';
say "'$wanted' matches!" if /$wanted/i ~~ @array; # Prints "'aAa' matches!"
I'm not sure if this is what you want but:
Directory.GetFiles(@"c:\mydir", "*.flv");
Or:
Path.GetExtension(@"c:\test.flv")
See:
'Quattro TT'
is a string.
Since string is a list of characters, this is the same as
['Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T']
Now...
['Quattro TT']
is a list with a string in the first position.
Also...
a = 'Quattro TT'
list(a)
is a string converted into a list.
Again, since string is a list of characters, there is not much change.
Another information...
tuple(something)
This convert something into tuple.
Understanding all of this, I think you can conclude that nothing fails.
For people just stumbling upon this now, I resolved an error of this type that was thrown with all the references and using statements placed properly. There's evidently some confusion with substituting in a function that returns DataTable instead of calling it on a declared DataTable. For example:
This worked for me:
DataTable dt = SomeObject.ReturnsDataTable();
List<string> ls = dt.AsEnumerable().Select(dr => dr["name"].ToString()).ToList<string>();
But this didn't:
List<string> ls = SomeObject.ReturnsDataTable().AsEnumerable().Select(dr => dr["name"].ToString()).ToList<string>();
I'm still not 100% sure why, but if anyone is frustrated by an error of this type, give this a try.
Universal way of loading view from xib:
Example:
let myView = Bundle.loadView(fromNib: "MyView", withType: MyView.self)
Implementation:
extension Bundle {
static func loadView<T>(fromNib name: String, withType type: T.Type) -> T {
if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T {
return view
}
fatalError("Could not load view with type " + String(describing: type))
}
}
Using only print:
>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b
Initially my repo said "Already up to date."
MINGW64 (feature/Issue_123)
$ git merge develop
Output:
Already up to date.
But the code is not up to date & it is showing some differences in some files.
MINGW64 (feature/Issue_123)
$ git diff develop
Output:
diff --git
a/src/main/database/sql/additional/pkg_etl.sql
b/src/main/database/sql/additional/pkg_etl.sql
index ba2a257..1c219bb 100644
--- a/src/main/database/sql/additional/pkg_etl.sql
+++ b/src/main/database/sql/additional/pkg_etl.sql
However, merging fixes it.
MINGW64 (feature/Issue_123)
$ git merge origin/develop
Output:
Updating c7c0ac9..09959e3
Fast-forward
3 files changed, 157 insertions(+), 92 deletions(-)
Again I have confirmed this by using diff
command.
MINGW64 (feature/Issue_123)
$ git diff develop
No differences in the code now!
I would strongly suggest you to read through the docs, for similar methods. If you are interested in context path, have a look here, ServletContext.getContextPath().
coalesce
is supported in both Oracle and SQL Server and serves essentially the same function as nvl
and isnull
. (There are some important differences, coalesce
can take an arbitrary number of arguments, and returns the first non-null one. The return type for isnull
matches the type of the first argument, that is not true for coalesce
, at least on SQL Server.)
I encounter this problem often, and the easiest way to do this is to use the apply()
function within a mutate
command.
library(tidyverse)
df=data.frame(
x1=c(1,0,0,NA,0,1,1,NA,0,1),
x2=c(1,1,NA,1,1,0,NA,NA,0,1),
x3=c(0,1,0,1,1,0,NA,NA,0,1),
x4=c(1,0,NA,1,0,0,NA,0,0,1),
x5=c(1,1,NA,1,1,1,NA,1,0,1))
df %>%
mutate(sum = select(., x1:x5) %>% apply(1, sum, na.rm=TRUE))
Here you could use whatever you want to select the columns using the standard dplyr
tricks (e.g. starts_with()
or contains()
). By doing all the work within a single mutate
command, this action can occur anywhere within a dplyr
stream of processing steps. Finally, by using the apply()
function, you have the flexibility to use whatever summary you need, including your own purpose built summarization function.
Alternatively, if the idea of using a non-tidyverse function is unappealing, then you could gather up the columns, summarize them and finally join the result back to the original data frame.
df <- df %>% mutate( id = 1:n() ) # Need some ID column for this to work
df <- df %>%
group_by(id) %>%
gather('Key', 'value', starts_with('x')) %>%
summarise( Key.Sum = sum(value) ) %>%
left_join( df, . )
Here I used the starts_with()
function to select the columns and calculated the sum and you can do whatever you want with NA
values. The downside to this approach is that while it is pretty flexible, it doesn't really fit into a dplyr
stream of data cleaning steps.
You should use jquery validation because if you use type="number"
then you can also enter "E" character in input type, which is not correct.
Solution:
HTML
<input class="form-control floatNumber" name="energy1_total_power_generated" type="text" required="" >
JQuery
//integer value validation
$('input.floatNumber').on('input', function() {
this.value = this.value.replace(/[^0-9.]/g,'').replace(/(\..*)\./g, '$1');
});
EDIT: Okay, so you don't want your local time (which isn't Australia) to contribute to the result, but instead the Australian time zone. Your existing code should be absolutely fine then, although Sydney is currently UTC+11, not UTC+10.. Short but complete test app:
import java.util.*;
import java.text.*;
public class Test {
public static void main(String[] args) throws InterruptedException {
Date date = new Date(1318386508000L);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
System.out.println(formatted);
format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
formatted = format.format(date);
System.out.println(formatted);
}
}
Output:
12/10/2011 02:28:28
12/10/2011 13:28:28
I would also suggest you start using Joda Time which is simply a much nicer date/time API...
EDIT: Note that if your system doesn't know about the Australia/Sydney
time zone, it would show UTC. For example, if I change the code about to use TimeZone.getTimeZone("blah/blah")
it will show the UTC value twice. I suggest you print TimeZone.getTimeZone("Australia/Sydney").getDisplayName()
and see what it says... and check your code for typos too :)
This page lists some simple hash functions that tend to decently in general, but any simple hash has pathological cases where it doesn't work well.
For Kotlin use KTX extension function:
(It uses TextWatcher
as previous answers)
yourEditText.doOnTextChanged { text, start, count, after ->
// action which will be invoked when the text is changing
}
import core-KTX
:
implementation "androidx.core:core-ktx:1.2.0"
If you want to round, 8.84 is the incorrect answer. 8.833333333333 rounded is 8.83 not 8.84. If you want to always round up, then you can use math.ceil. Do both in a combination with string formatting, because rounding a float number itself doesn't make sense.
"%.2f" % (math.ceil(x * 100) / 100)
I am using red hat linux on a VPS server (and via SSH - putty), for me the following worked:
First, you list all the running processes:
ps -ef
Then in the first column you find your user name; I found it the following three times:
Then in the second column you can find the PID of the nohup process and you only type:
kill PID
(replacing the PID with the nohup process's PID of course)
And that is it!
I hope this answer will be useful for someone I'm also very new to bash and SSH, but found 95% of the knowledge I need here :)
From my perspective you can do this, its one to one update of two tables in SQL SERVER:
BEGIN TRANSACTION
DECLARE @CNSREQ VARCHAR(30)
DECLARE @ID INT
DECLARE @CNSRQDT VARCHAR(30)
DECLARE @ID2 INT
DECLARE @IDCNSREQ INT
DECLARE @FINALCNSREQ VARCHAR(30)
DECLARE @FINALCNSRQDT VARCHAR(30)
DECLARE @IDCNSRQDT INT
SET @CNSREQ=(SELECT MIN(REQUISICIONESDT.CNSREQ) FROM REQUISICIONESDT
INNER JOIN
REQUISICIONES
ON REQUISICIONESDT.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID
AND REQUISICIONES.CNSREQ = REQUISICIONESDT.CNSREQ AND REQUISICIONESDT.IDREQ = REQUISICIONES.ID
WHERE REQUISICIONES.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID)
SELECT REQUISICIONES.CNSREQ, REQUISICIONES.ID, REQUISICIONES.CNSRQDT FROM REQUISICIONES
INNER JOIN
REQUISICIONESDT
ON REQUISICIONESDT.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID
AND REQUISICIONES.CNSREQ = REQUISICIONESDT.CNSREQ AND REQUISICIONESDT.IDREQ = REQUISICIONES.ID
WHERE REQUISICIONES.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID
AND REQUISICIONES.CNSREQ = @CNSREQ
UPDATE REQUISICIONESDT SET REQUISICIONESDT.CNSREQ=NULL, REQUISICIONESDT.IDREQ=NULL
FROM REQUISICIONES INNER JOIN REQUISICIONESDT
ON REQUISICIONESDT.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID
WHERE REQUISICIONES.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID
AND REQUISICIONES.CNSREQ = @CNSREQ
UPDATE REQUISICIONES SET REQUISICIONES.CNSRQDT=NULL, REQUISICIONES.IDRQDT=NULL
FROM REQUISICIONES INNER JOIN REQUISICIONESDT
ON REQUISICIONESDT.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID
WHERE REQUISICIONES.CNSRQDT = REQUISICIONES.CNSRQDT AND REQUISICIONES.IDRQDT = REQUISICIONESDT.ID
AND REQUISICIONES.CNSREQ = @CNSREQ
SET @ID2=(SELECT MIN(REQUISICIONESDT.ID) FROM REQUISICIONESDT
WHERE ISNULL(REQUISICIONESDT.IDREQ,0)<>0)
DELETE FROM REQUISICIONESDT WHERE REQUISICIONESDT.ID=@ID2
SET @IDCNSREQ=(SELECT MIN (REQUISICIONES.ID)FROM REQUISICIONES
INNER JOIN REQUISICIONESDT ON
REQUISICIONESDT.CEDULA = REQUISICIONES.CEDULA AND REQUISICIONES.FECHA_SOLICITUD = REQUISICIONESDT.FECHA_SOLICITUD
WHERE REQUISICIONES.CNSRQDT IS NULL AND REQUISICIONES.IDRQDT IS NULL)
SET @FINALCNSREQ=(SELECT MIN (REQUISICIONES.CNSREQ)FROM REQUISICIONES
INNER JOIN REQUISICIONESDT ON
REQUISICIONESDT.CEDULA = REQUISICIONES.CEDULA AND REQUISICIONES.FECHA_SOLICITUD = REQUISICIONESDT.FECHA_SOLICITUD
WHERE REQUISICIONES.CNSRQDT IS NULL AND REQUISICIONES.IDRQDT IS NULL)
SET @FINALCNSRQDT=(SELECT MIN(REQUISICIONESDT.CNSRQDT) FROM REQUISICIONES
INNER JOIN REQUISICIONESDT ON
REQUISICIONESDT.CEDULA = REQUISICIONES.CEDULA AND REQUISICIONES.FECHA_SOLICITUD = REQUISICIONESDT.FECHA_SOLICITUD
WHERE REQUISICIONES.CNSRQDT IS NULL AND REQUISICIONES.IDRQDT IS NULL)
SET @IDCNSRQDT=(SELECT MIN (REQUISICIONESDT.ID)FROM REQUISICIONES
INNER JOIN REQUISICIONESDT ON
REQUISICIONESDT.CEDULA = REQUISICIONES.CEDULA AND REQUISICIONES.FECHA_SOLICITUD = REQUISICIONESDT.FECHA_SOLICITUD
WHERE REQUISICIONES.CNSRQDT IS NULL AND REQUISICIONES.IDRQDT IS NULL)
UPDATE REQUISICIONES SET REQUISICIONES.CNSRQDT = @FINALCNSRQDT, REQUISICIONES.IDRQDT=@IDCNSRQDT FROM REQUISICIONES
INNER JOIN REQUISICIONESDT ON
REQUISICIONESDT.CEDULA = REQUISICIONES.CEDULA AND REQUISICIONES.FECHA_SOLICITUD = REQUISICIONESDT.FECHA_SOLICITUD
WHERE REQUISICIONESDT.CNSRQDT = @FINALCNSRQDT AND REQUISICIONESDT.ID = @IDCNSRQDT
ROLLBACK TRANSACTION
React Router v4
There's a couple of things that I needed to get this working smoothly.
The doc page on auth workflow has quite a lot of what is required.
However I had three issues
props.history
come from?Route
componentprops
?I ended up using:
<Route render>
which gets you props.history
which can then be passed down to the children.render={routeProps => <MyComponent {...props} {routeProps} />}
to combine other props
from this answer on 'react-router - pass props to handler component'N.B. With the render
method you have to pass through the props from the Route
component explicitly. You also want to use render
and not component
for performance reasons (component
forces a reload every time).
const App = (props) => (
<Route
path="/home"
render={routeProps => <MyComponent {...props} {...routeProps}>}
/>
)
const MyComponent = (props) => (
/**
* @link https://reacttraining.com/react-router/web/example/auth-workflow
* N.B. I use `props.history` instead of `history`
*/
<button onClick={() => {
fakeAuth.signout(() => props.history.push('/foo'))
}}>Sign out</button>
)
One of the confusing things I found is that in quite a few of the React Router v4 docs they use MyComponent = ({ match })
i.e. Object destructuring, which meant initially I didn't realise that Route
passes down three props, match
, location
and history
I think some of the other answers here are assuming that everything is done via JavaScript classes.
Here's an example, plus if you don't need to pass any props
through you can just use component
class App extends React.Component {
render () {
<Route
path="/home"
component={MyComponent}
/>
}
}
class MyComponent extends React.Component {
render () {
/**
* @link https://reacttraining.com/react-router/web/example/auth-workflow
* N.B. I use `props.history` instead of `history`
*/
<button onClick={() => {
this.fakeAuth.signout(() => this.props.history.push('/foo'))
}}>Sign out</button>
}
}
Increasing SQL-Wait-Timeout worked for me in this case, try this:
mysql_query("SET @@session.wait_timeout=900", $link);
before you first "normal" SQL queries.
a couple years down the road, I'd vote for three.js because
ie 11 supports webgl (to what extent I can't assure you since i'm usually in chrome)
and, as far as importing external models into three.js, here's a link to mrdoob's updated loaders (so many!)
UPDATE nov 2019: the THREE.js loaders are now far more and it makes little sense to post them all: just go to this link
http://threejs.org/examples and review the loaders - at least 20 of them
Calling p.plot
after setting the limits is why it is rescaling. You are correct in that turning autoscaling off will get the right answer, but so will calling xlim()
or ylim()
after your plot
command.
I use this quite a lot to invert the x axis, I work in astronomy and we use a magnitude system which is backwards (ie. brighter stars have a smaller magnitude) so I usually swap the limits with
lims = xlim()
xlim([lims[1], lims[0]])
**get id from dic value. I got the result.try the below code**
get_abstracts = s.get_abstracts(session_id)
sessions = get_abstracts['sessions']
abs = {}
for a in get_abstracts['abstracts']:
a_session_id = a['session_id']
abs.setdefault(a_session_id,[]).append(a)
authors = {}
# print('authors')
# print(get_abstracts['authors'])
for au in get_abstracts['authors']:
# print(au)
au_abs_id = au['abs_id']
authors.setdefault(au_abs_id,[]).append(au)
**In jinja template**
{% for s in sessions %}
<h4><u>Session : {{ s.session_title}} - Hall : {{ s.session_hall}}</u></h4>
{% for a in abs[s.session_id] %}
<hr>
<p><b>Chief Author :</b> Dr. {{ a.full_name }}</p>
{% for au in authors[a.abs_id] %}
<p><b> {{ au.role }} :</b> Dr.{{ au.full_name }}</p>
{% endfor %}
{% endfor %}
{% endfor %}
lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name. Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question. you can write your javascript like so:
<script type="text/javascript">
var ratings = document.getElementsByClassName('ratings'); // we access all our radio buttons elements by class name
var radios="";
var i;
for(i=0;i<ratings.length;i++){
ratings[i].onclick=function(){
var result = 0;
radios = document.querySelectorAll("input[class=ratings]:checked");
for(j=0;j<radios.length;j++){
result = result + + radios[j].value;
}
console.log(result);
document.getElementById('overall-average-rating').innerHTML = result; // this row displays your total rating
}
}
</script>
I would also insert the final output into a hidden form element to be submitted together with the form.
mongoimport --jsonArray -d DatabaseN -c collectionName /filePath/filename.json
Both answers are wrong. You can. You need to call
$.ajaxSetup({
async: false
});
before your json ajax call. And you can set it to true after call retuns ( if there are other usages of ajax on page if you want them async )
In Entity Framework 6.1+ you can use this attribute on your model:
[Index(IsUnique=true)]
You can find it in this namespace:
using System.ComponentModel.DataAnnotations.Schema;
If your model field is a string, make sure it is not set to nvarchar(MAX) in SQL Server or you will see this error with Entity Framework Code First:
Column 'x' in table 'dbo.y' is of a type that is invalid for use as a key column in an index.
The reason is because of this:
SQL Server retains the 900-byte limit for the maximum total size of all index key columns."
(from: http://msdn.microsoft.com/en-us/library/ms191241.aspx )
You can solve this by setting a maximum string length on your model:
[StringLength(450)]
Your model will look like this now in EF CF 6.1+:
public class User
{
public int UserId{get;set;}
[StringLength(450)]
[Index(IsUnique=true)]
public string UserName{get;set;}
}
Update:
if you use Fluent:
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
// ....
Property(x => x.Name).IsRequired().HasMaxLength(450).HasColumnAnnotation("Index", new IndexAnnotation(new[] { new IndexAttribute("Index") { IsUnique = true } }));
}
}
and use in your modelBuilder:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// ...
modelBuilder.Configurations.Add(new UserMap());
// ...
}
Update 2
for EntityFrameworkCore see also this topic: https://github.com/aspnet/EntityFrameworkCore/issues/1698
Update 3
for EF6.2 see: https://github.com/aspnet/EntityFramework6/issues/274
Update 4
ASP.NET Core Mvc 2.2 with EF Core:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Unique { get; set; }
data-src attribute is part of the data-* attributes collection introduced in HTML5. data-src allow us to store extra data that have no meaning to the browser but that can be use by Javascript Code or CSS rules.
The Statistic plugin worked for me.
To install it from Intellij:
File - Settings - Plugins - Browse repositories... Find it on the list and double-click on it.
Access the 'statistic' toolbar via tabs in bottom left of project
OLDER VERSIONS: Open statistics window from:
View -> Tool Windows -> Statistic
It is whatever it is configured to be on that particular web server. A web server could be configured to run .pl files with the php module and .aspx files with perl, although that would be silly. There are no scripts involved with most web servers, instead you'd have to look in your apache configuration files (or equivalent, if using different server software). If you have permission to edit the server config file, then you could make files ending in .do run as php, if that's what you're after.
Client Side Validation Checking:-
HTML:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClientClick = "return ValidateFile()" OnClick="btnUpload_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="" />
Javascript:
<script type ="text/javascript">
var validFilesTypes=["bmp","gif","png","jpg","jpeg","doc","xls"];
function ValidateFile()
{
var file = document.getElementById("<%=FileUpload1.ClientID%>");
var label = document.getElementById("<%=Label1.ClientID%>");
var path = file.value;
var ext=path.substring(path.lastIndexOf(".")+1,path.length).toLowerCase();
var isValidFile = false;
for (var i=0; i<validFilesTypes.length; i++)
{
if (ext==validFilesTypes[i])
{
isValidFile=true;
break;
}
}
if (!isValidFile)
{
label.style.color="red";
label.innerHTML="Invalid File. Please upload a File with" +
" extension:\n\n"+validFilesTypes.join(", ");
}
return isValidFile;
}
</script>
parseInt(Math.random().toString().slice(2,Math.min(length+2, 18)), 10); // 18 -> due to max digits in Math.random
Update: This method has few flaws: - Sometimes the number of digits might be lesser if its left padded with zeroes.
You may use event handler serverclick as below
//cmdAction is the id of HTML button as below
<body>
<form id="form1" runat="server">
<button type="submit" id="cmdAction" text="Button1" runat="server">
Button1
</button>
</form>
</body>
//cs code
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
cmdAction.ServerClick += new EventHandler(submit_click);
}
protected void submit_click(object sender, EventArgs e)
{
Response.Write("HTML Server Button Control");
}
}
If you are taking a 'fill in the blank' approach, you can precisely position text anywhere you want on the page. So it's relatively easy (if not a bit tedious) to add the missing text to the document. For example with Zend Framework:
<?php
require_once 'Zend/Pdf.php';
$pdf = Zend_Pdf::load('blank.pdf');
$page = $pdf->pages[0];
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font, 12);
$page->drawText('Hello world!', 72, 720);
$pdf->save('zend.pdf');
If you're trying to replace inline content, such as a "[placeholder string]," it gets much more complicated. While it's technically possible to do, you're likely to mess up the layout of the page.
A PDF document is comprised of a set of primitive drawing operations: line here, image here, text chunk there, etc. It does not contain any information about the layout intent of those primitives.
From here: http://forums.oracle.com/forums/thread.jspa?messageID=2354075
alter session set skip_unusable_indexes = true;
alter index your_index unusable;
do import...
alter index your_index rebuild [online];
The problem is clearly not with the javascript. Here's a quick snippet to show you the working of the code.
document.getElementById('points').value = 100;
As you can see, the javascript perfectly assigns the new value to the input element. It would be helpful if you could elaborate more on the issue.
It is already a list
type(my_set)
>>> <type 'list'>
Do you want something like
my_set = set([1,2,3,4])
my_list = list(my_set)
print my_list
>> [1, 2, 3, 4]
EDIT : Output of your last comment
>>> my_list = [1,2,3,4]
>>> my_set = set(my_list)
>>> my_new_list = list(my_set)
>>> print my_new_list
[1, 2, 3, 4]
I'm wondering if you did something like this :
>>> set=set()
>>> set([1,2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable
his example will tell you how to pass input value to parent on submit button.
First define eventBus as new Vue.
//main.js
import Vue from 'vue';
export const eventBus = new Vue();
Pass your input value via Emit.
//Sender Page
import { eventBus } from "../main";
methods: {
//passing data via eventbus
resetSegmentbtn: function(InputValue) {
eventBus.$emit("resetAllSegment", InputValue);
}
}
//Receiver Page
import { eventBus } from "../main";
created() {
eventBus.$on("resetAllSegment", data => {
console.log(data);//fetching data
});
}
Update October 2019
The following should work "stand-alone" on all modern browsers without any dependencies or transpilation.
<!-- display a pop-up with the selected values from the <select> element -->
<script>
const showSelectedOptions = options => alert(
[...options].filter(o => o.selected).map(o => o.value)
)
</script>
<select multiple onchange="showSelectedOptions(this.options)">
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
<option value='4'>four</option>
</select>
Here's my take on Carpetsmoker's answer (which I liked due to it being dynamic), cleaned up and updated for select2 v4:
$('#selectField').on('select2:open', function (e) {
var container = $(this).select('select2-container');
var position = container.offset().top;
var availableHeight = $(window).height() - position - container.outerHeight();
var bottomPadding = 50; // Set as needed
$('ul.select2-results__options').css('max-height', (availableHeight - bottomPadding) + 'px');
});
Having used both, Twitter's Bootstrap is a superior technology set. Here are some differences,
Other notes,
This works great for me:
function listenForShiftKey(e){
var evt = e || window.event;
if (evt.shiftKey) {
shiftKeyDown = true;
} else {
shiftKeyDown = false;
}
}
Truncate drops the decimal point.
This problem take with me more than 3 hours finally , I just tried the problem was in removing dot from the end just .
problem was
docker run -p 3000:80 --rm --name test-con test-app .
/usr/local/bin/docker-entrypoint.sh: 8: exec: .: Permission denied
just remove dot from the end of your command line :
docker run -p 3000:80 --rm --name test-con test-app
I encountered this issue, but the solutions provided didn't directly help me, so I'm sharing how I got myself into a similar situation and temporarily resolved it.
I created a new project within an existing solution and copy & pasted the Header and CPP file from another project within that solution that I needed to include in my new project through the IDE. Intellisense displayed an error suggesting it could not resolve the reference to the header file and compiling the code failed with the same error too.
After reading the posts here, I checked the project folder with Windows File Explorer and only the main.cpp file was found. For some reason, my copy and paste of the header file and CPP file were just a reference? (I assume) and did not physically copy the file into the new project file.
I deleted the files from the Project view within Visual Studio and I used File Explorer to copy the files that I needed to the project folder/directory. I then referenced the other solutions posted here to "include files in project" by showing all files and this resolved the problem.
It boiled down to the files not being physically in the Project folder/directory even though they were shown correctly within the IDE.
Please Note I understand duplicating code is not best practice and my situation is purely a learning/hobby project. It's probably in my best interest and anyone else who ended up in a similar situation to use the IDE/project/Solution setup correctly when reusing code from other projects - I'm still learning and I'll figure this out one day!
The following example using the iris dataset works fine:
dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
id.vars = "Species")
ggplot(aes(x = 1:nrow(iris), y = value, color = variable), data = dat) +
geom_point() + geom_line()
You start a thread which runs the static method SumData
. However, SumData
calls SetTextboxText
which isn't static. Thus you need an instance of your form to call SetTextboxText
.
Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.
Any one can try this command to truncate any file in linux system
This will surely work in any format :
truncate -s 0 file.txt
All what you need is simple. Create function:
function getFuncName() {
return getFuncName.caller.name
}
After that whenever you need, you simply use:
function foo() {
console.log(getFuncName())
}
foo()
// Logs: "foo"
Yeah. Try this.. lazy evaluation should prohibit the second part of the condition from evaluating when the first part is false/null:
var someval = document.getElementById('something')
if (someval && someval.value <> '') {
curl will encode the data for you, just drop your raw field data into the fields array and tell it to "go".
The with
keywork is introduced in C# version 9!
you can use it to create copy of object like follows
Person brother = person with { FirstName = "Paul" };
"The above line creates a new Person record where the LastName property is a copy of person, and the FirstName is "Paul". You can set any number of properties in a with-expression. Any of the synthesized members except the "clone" method may be written by you. If a record type has a method that matches the signature of any synthesized method, the compiler doesn't synthesize that method."
UPDATE:
At the time this answer is written, C#9 is not officially released but in preview only. However, it is planned to be shipped along with .NET 5.0 in November 2020
for more information, check the record types.
Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?
def hex2bin(s):
hex_table = ['0000', '0001', '0010', '0011',
'0100', '0101', '0110', '0111',
'1000', '1001', '1010', '1011',
'1100', '1101', '1110', '1111']
bits = ''
for i in range(len(s)):
bits += hex_table[int(s[i], base=16)]
return bits
Steps to downgrade to node8
brew install node@8
brew link node@8 --force
if warning remove the folder and files as indicated in the warning then again the command :
brew link node@8 --force
If you're thinking about manually removing Apple's default Python 2.7, I'd suggest you hang-fire and do-noting: Looks like Apple will very shortly do it for you:
Python 2.7- as well as Ruby & Perl- are deprecated in Catalina: (skip to section "Scripting Language Runtimes" > "Deprecations")
https://developer.apple.com/documentation/macos_release_notes/macos_catalina_10_15_release_notes
Indeed, if you do nothing at all, according to The Mac Observer, by OSX version 10.16, Python 2.7 will disappear from your system:
https://www.macobserver.com/analysis/macos-catalina-deprecates-unix-scripting-languages/
Given this revelation, I'd suggest the best course of action is do nothing and wait for Apple to wipe it for you. As Apple is imminently about to remove it for you, doesn't seem worth the risk of tinkering with your Python environment.
NOTE: I see the question relates specifically to OSX v 10.6.4, but it appears this question has become a pivot-point for all OSX folks interested in removing Python 2.7 from their systems, whatever version they're running.
May be you will not do it explicitly but it will happen.
Now, there are several ways we can try to get precise double
value (where num
and denom
are int
type, and of-course with casting)-
double d = (double) num / denom;
double d = ((double) num) / denom;
double d = num / (double) denom;
double d = (double) num / (double) denom;
but not double d = (double) (num / denom);
double d = num * 1.0 / denom;
double d = num / 1d / denom;
double d = ( num + 0.0 ) / denom;
double d = num; d /= denom;
but not double d = num / denom * 1.0;
and not double d = 0.0 + ( num / denom );
Now if you are asking- Which one is better? explicit? or implicit?
Well, lets not follow a straight answer here. Simply remember- We programmers don't like surprises or magics in a source. And we really hate Easter Eggs.
Also, an extra operation will definitely not make your code more efficient. Right?
Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML after some user interaction, you can make much more interactive pages.
However, using innerHTML requires some preparation if you want to be able to use it easily and reliably. First, you must give the element you wish to change an id. With that id in place you will be able to use the getElementById function, which works on all browsers.
Open the output stream and store properties after you have closed the input stream.
FileInputStream in = new FileInputStream("First.properties");
Properties props = new Properties();
props.load(in);
in.close();
FileOutputStream out = new FileOutputStream("First.properties");
props.setProperty("country", "america");
props.store(out, null);
out.close();
Yes, this way:
im = Image.open('image.gif')
rgb_im = im.convert('RGB')
r, g, b = rgb_im.getpixel((1, 1))
print(r, g, b)
(65, 100, 137)
The reason you were getting a single value before with pix[1, 1]
is because GIF pixels refer to one of the 256 values in the GIF color palette.
See also this SO post: Python and PIL pixel values different for GIF and JPEG and this PIL Reference page contains more information on the convert()
function.
By the way, your code would work just fine for .jpg
images.
select table_name
from information_schema.columns
where COLUMN_NAME = 'MyColumn'
The following steps will help you to sort your problem out.
Steps: developer_identity.cer <= download from Apple mykey.p12 <= Your private key
Commands to follow:
openssl x509 -in developer_identity.cer -inform DER -out developer_identity.pem -outform PEM
openssl pkcs12 -nocerts -in mykey.p12 -out mykey.pem
openssl pkcs12 -export -inkey mykey.pem -in developer_identity.pem -out iphone_dev.p12
Final p12 that we will require is iphone_dev.p12 file and the passphrase.
use this file as your p12 and then try. This indeed is the solution.:)
If you get this error on an .MDF
file in the APP_DATA
folder (or where ever you put it) for a Visual Studio project, the way I did it was to simply copy permissions from the existing DATA
folder here (I'm using SQL Express 2014 to support an older app):
C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS2014\MSSQL\DATA
(note: your actual install path my vary - especially if your instance name is different)
Double click on theDATA
folder first as administrator to make sure you have access, then open the properties on the folder and mimic the same for the APP_DATA
folder. In my case the missing user was MSSQL$SQLEXPRESS2014
(because I named the instance SQLEXPRESS2014
- yours may be different). That also happens to be the SQL Server service username.
Some supplementary info. Both flag and interrupt are suggested in the Java doc.
https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
private volatile Thread blinker;
public void stop() {
blinker = null;
}
public void run() {
Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
Thread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
For a thread that waits for long periods (e.g., for input), use Thread.interrupt
public void stop() {
Thread moribund = waiter;
waiter = null;
moribund.interrupt();
}
Redirecting the stream is asynchronous and will potentially continue after the process has terminated. It is mentioned by Umar to cancel after process termination process.CancelOutputRead()
. However that has data loss potential.
This is working reliably for me:
process.WaitForExit(...);
...
while (process.StandardOutput.EndOfStream == false)
{
Thread.Sleep(100);
}
I didn't try this approach but I like the suggestion from Sly:
if (process.WaitForExit(timeout))
{
process.WaitForExit();
}
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.GeomagneticField;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;
public class LocationService extends Service {
private static final int MINUTES = 1000 * 60 * 2;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
Context mContext;
private boolean isGpsEnabled = false;
private boolean isNetworkEnabled = false;
private GeomagneticField geoField;
private double latitude = 0.0;
private double longitude = 0.0;
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
if (locationManager == null) {
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
}
getCurrentLocation();
}
private void getCurrentLocation() {
try {
assert locationManager != null;
isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
if (!isGpsEnabled && !isNetworkEnabled) {
showSettingsAlert();
}
listener = new MyLocationListener();
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, listener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, listener);
} catch (SecurityException e) {
e.printStackTrace();
}
}
private void showSettingsAlert() {
Toast.makeText(mContext, "GPS is disabled in your device. Please Enable it ?", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
return true;
}
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > MINUTES;
boolean isSignificantlyOlder = timeDelta < -MINUTES;
boolean isNewer = timeDelta > 0;
if (isSignificantlyNewer) {
return true;
} else if (isSignificantlyOlder) {
return false;
}
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider());
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
@Override
public void onDestroy() {
super.onDestroy();
locationManager.removeUpdates(listener);
}
private void setupFinalLocationData(Location mLocation) {
if (mLocation != null) {
geoField = new GeomagneticField(
Double.valueOf(mLocation.getLatitude()).floatValue(),
Double.valueOf(mLocation.getLongitude()).floatValue(),
Double.valueOf(mLocation.getAltitude()).floatValue(),
System.currentTimeMillis()
);
latitude = mLocation.getLatitude();
longitude = mLocation.getLongitude();
//Update latitude and longtitude in SharedPreference...
}
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(final Location loc) {
if (isBetterLocation(loc, previousBestLocation)) {
setupFinalLocationData(loc);
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
Just go to cmd and install pip install pywin32
pythoncom is part of pywin32 for API window extension.... good luck
Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" />
</p>
</form>
</body>
Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page
If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.
Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.
The button is a web control Button Add a Click event to the button call it Button1Click:
void Button1Click(Object sender,EventArgs e) { }
Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.
So if for example you want to access the text in TextBox1
you just need to call that object in the C# code:
String firstBox = TextBox1.Text;
In the same way you can populate the objects when event occur.
Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.
I think the str_getcsv() syntax is much cleaner, it also doesn't require the CSV to be stored in the file system.
$csv = str_getcsv(file_get_contents('myCSVFile.csv'));
echo '<pre>';
print_r($csv);
echo '</pre>';
Or for a line by line solution:
$csv = array();
$lines = file('myCSVFile.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $key => $value)
{
$csv[$key] = str_getcsv($value);
}
echo '<pre>';
print_r($csv);
echo '</pre>';
Or for a line by line solution with no str_getcsv():
$csv = array();
$file = fopen('myCSVFile.csv', 'r');
while (($result = fgetcsv($file)) !== false)
{
$csv[] = $result;
}
fclose($file);
echo '<pre>';
print_r($csv);
echo '</pre>';
After struggling myself with this I found a solution that works just replace the $ with jQueryjQuery.fancybox.close()
and I made it an inline script on an onClick. Going to check if i can call it from the parent
At its core, Git is a set of command line utility programs that are designed to execute on a Unix style command-line environment. Modern operating systems like Linux and macOS both include built-in Unix command line terminals. This makes Linux and macOS complementary operating systems when working with Git. Microsoft Windows instead uses Windows command prompt, a non-Unix terminal environment.
What is Git Bash?
Git Bash is an application for Microsoft Windows environments which provides an emulation layer for a Git command line experience. Bash is an acronym for Bourne Again Shell. A shell is a terminal application used to interface with an operating system through written commands. Bash is a popular default shell on Linux and macOS. Git Bash is a package that installs Bash, some common bash utilities, and Git on a Windows operating system.
Qiqi Abaziz's answer is ok, but I still struggled for a long time getting it to work with the compatibility pack and to apply the style to the correct elements. Also, the transparency-hack is unneccessary. So here is a complete example working for v8 and up:
values\styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyActivityTheme" parent="@style/Theme.AppCompat">
<item name="actionBarStyle">@style/NoLogoActionBar</item> <!-- pre-v11-compatibility -->
<item name="android:actionBarStyle">@style/NoLogoActionBar</item>
</style>
<style name="NoLogoActionBar" parent="@style/Widget.AppCompat.ActionBar">
<item name="displayOptions">showHome</item> <!-- pre-v11-compatibility -->
<item name="android:displayOptions">showHome</item>
</style>
</resources>
AndroidManifest.xml (shell)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19"/>
<application android:theme="@android:style/Theme.Light.NoTitleBar">
<activity android:theme="@style/PentActivityTheme"/>
</application>
</manifest>
net stop <your service> && net start <your service>
No net restart
, unfortunately.
For anything with requests to URLs you might want to check out requests. For JSON in particular:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
The getTime() method returns the number of milliseconds since midnight of January 1, 1970.
ex.
var start = new Date().getTime();
for (i = 0; i < 50000; ++i) {
// do something
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
The problem is your query returned false
meaning there was an error in your query. After your query you could do the following:
if (!$result) {
die(mysqli_error($link));
}
Or you could combine it with your query:
$results = mysqli_query($link, $query) or die(mysqli_error($link));
That will print out your error.
Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:
$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";
In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist
Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.
There is a much simpler way. This does not care if it is binary or text file.
Use noskipws.
char buf[SZ];
ifstream f("file");
int i;
for(i=0; f >> noskipws >> buffer[i]; i++);
ofstream f2("writeto");
for(int j=0; j < i; j++) f2 << noskipws << buffer[j];
Or you can just use string instead of the buffer.
string s; char c;
ifstream f("image.jpg");
while(f >> noskipws >> c) s += c;
ofstream f2("copy.jpg");
f2 << s;
normally stream skips white space characters like space or new line, tab and all other control characters. But noskipws makes all the characters transferred. So this will not only copy a text file but also a binary file. And stream uses buffer internally, I assume the speed won't be slow.
python
x = "http://xxxxxx"
y = "text title"
text_link = '<{}|{}>'.format(x,y)
post text_link in using python slack client
If you are working in Windows you have to change the permissions of the directory putting full permissions or just write to let github clone the repository. The steps are:
If the requirement is to copy all files in "\Publish\Appfolder" into the parent "\Publish\" folder (inclusive of any subfolders, following works for me) The switch '/s' allows copying of all subfolders, recursively.
xcopy src\main\Publish\Appfolder\*.* /s src\main\Publish\
The compiler only knows that the code is or isn't reachable if you use "return". Think of Environment.Exit() as a function that you call, and the compiler don't know that it will close the application.
You could try something like XLLoop. This lets you implement excel functions (UDFs) on an external server (server implementations in many different languages are provided).
For example you could use a MySQL database and Apache web server and then write the functions in PHP to serve up the data to your users.
BTW, I work on the project so let me know if you have any questions.
I don't have enough reputation to comment on jka.ne so:
I had to amend jka.ne's line for it to work:
df.apply(lambda r : pd.datetime.combine(r['date_column_name'],r['time_column_name']).time(),1)
This might help others.
Also, I have tested a different approach, using replace
instead of combine
:
def combine_date_time(df, datecol, timecol):
return df.apply(lambda row: row[datecol].replace(
hour=row[timecol].hour,
minute=row[timecol].minute),
axis=1)
which in the OP's case would be:
combine_date_time(df, 'Date', 'Time')
I have timed both approaches for a relatively large dataset (>500.000 rows), and they both have similar runtimes, but using combine
is faster (59s for replace
vs 50s for combine
).
If you use jQuery built-in after()
with empty value it will create a dynamic object that will match your :after
CSS selector.
$('.active').after().click(function () {
alert('clickable!');
});
See the jQuery documentation.
It was requested that I add this functionality to the stackoverflow R package. Given that it is a tinyverse package (and can't depend on third party packages), here is what I came up with:
#' Bulk import data files
#'
#' Read in each file at a path and then unnest them. Defaults to csv format.
#'
#' @param path a character vector of full path names
#' @param pattern an optional \link[=regex]{regular expression}. Only file names which match the regular expression will be returned.
#' @param reader a function that can read data from a file name.
#' @param ... optional arguments to pass to the reader function (eg \code{stringsAsFactors}).
#' @param reducer a function to unnest the individual data files. Use I to retain the nested structure.
#' @param recursive logical. Should the listing recurse into directories?
#'
#' @author Neal Fultz
#' @references \url{https://stackoverflow.com/questions/11433432/how-to-import-multiple-csv-files-at-once}
#'
#' @importFrom utils read.csv
#' @export
read.directory <- function(path='.', pattern=NULL, reader=read.csv, ...,
reducer=function(dfs) do.call(rbind.data.frame, dfs), recursive=FALSE) {
files <- list.files(path, pattern, full.names = TRUE, recursive = recursive)
reducer(lapply(files, reader, ...))
}
By parameterizing the reader and reducer function, people can use data.table or dplyr if they so choose, or just use the base R functions that are fine for smaller data sets.
you can always use new stdClass()
. Example code:
$object = new stdClass();
$object->property = 'Here we go';
var_dump($object);
/*
outputs:
object(stdClass)#2 (1) {
["property"]=>
string(10) "Here we go"
}
*/
Also as of PHP 5.4 you can get same output with:
$object = (object) ['property' => 'Here we go'];
Override onFormResubmission
in WebViewClient
@Override
public void onFormResubmission(WebView view, Message dontResend, Message resend){
resend.sendToTarget();
}
On Linux, you can use ldconfig
, which maintains the ld.so configuration and cache, to print out the directories search by ld.so
with
ldconfig -v 2>/dev/null | grep -v ^$'\t'
ldconfig -v
prints out the directories search by the linker (without a leading tab) and the shared libraries found in those directories (with a leading tab); the grep
gets the directories. On my machine, this line prints out
/usr/lib64/atlas:
/usr/lib/llvm:
/usr/lib64/llvm:
/usr/lib64/mysql:
/usr/lib64/nvidia:
/usr/lib64/tracker-0.12:
/usr/lib/wine:
/usr/lib64/wine:
/usr/lib64/xulrunner-2:
/lib:
/lib64:
/usr/lib:
/usr/lib64:
/usr/lib64/nvidia/tls: (hwcap: 0x8000000000000000)
/lib/i686: (hwcap: 0x0008000000000000)
/lib64/tls: (hwcap: 0x8000000000000000)
/usr/lib/sse2: (hwcap: 0x0000000004000000)
/usr/lib64/tls: (hwcap: 0x8000000000000000)
/usr/lib64/sse2: (hwcap: 0x0000000004000000)
The first paths, without hwcap
in the line, are either built-in or read from /etc/ld.so.conf.
The linker can then search additional directories under the basic library search path, with names like sse2
corresponding to additional CPU capabilities.
These paths, with hwcap
in the line, can contain additional libraries tailored for these CPU capabilities.
One final note: using -p
instead of -v
above searches the ld.so
cache instead.
Yes Definitely. As far as i remember From kernel version 3.9 (Not sure on the version) onwards support for the SO_REUSEPORT
was introduced. SO_RESUEPORT
allows binding to the exact same port and address, As long as the first server sets this option before binding its socket.
It works for both TCP and UDP. Refer to the link for more details: SO_REUSEPORT
Note: Accepted answer no longer holds true as per my opinion.
As Sagiv b.g. pointed out, the npm start
command is a shortcut for npm run start
. I just wanted to add a real-life example to clarify it a bit more.
The setup below comes from the create-react-app
github repo. The package.json
defines a bunch of scripts which define the actual flow.
"scripts": {
"start": "npm-run-all -p watch-css start-js",
"build": "npm run build-css && react-scripts build",
"watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
"build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
"start-js": "react-scripts start"
},
For clarity, I added a diagram.
The blue boxes are references to scripts, all of which you could executed directly with an npm run <script-name>
command. But as you can see, actually there are only 2 practical flows:
npm run start
npm run build
The grey boxes are commands which can be executed from the command line.
So, for instance, if you run npm start
(or npm run start
) that actually translate to the npm-run-all -p watch-css start-js
command, which is executed from the commandline.
In my case, I have this special npm-run-all
command, which is a popular plugin that searches for scripts that start with "build:", and executes all of those. I actually don't have any that match that pattern. But it can also be used to run multiple commands in parallel, which it does here, using the -p <command1> <command2>
switch. So, here it executes 2 scripts, i.e. watch-css
and start-js
. (Those last mentioned scripts are watchers which monitor file changes, and will only finish when killed.)
The watch-css
makes sure that the *.scss
files are translated to *.css
files, and looks for future updates.
The start-js
points to the react-scripts start
which hosts the website in a development mode.
In conclusion, the npm start
command is configurable. If you want to know what it does, then you have to check the package.json
file. (and you may want to make a little diagram when things get complicated).
try to play around with mix-blend-mode: multiply;
color: white;
background: black;
mix-blend-mode: multiply;
Support, unfortunately, is brutal at best. Here's a post on the topic:
https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/
And the post content:
Assembly is short descriptive terms humans can understand that can be directly translated into the machine code that a CPU actually uses.
While somewhat understandable by humans, Assembler is still low level. It takes a lot of code to do anything useful.
So instead we use higher level languages such as C, BASIC, FORTAN (OK I know I've dated myself). When compiled these produce object code. Early languages had machine language as their object code.
Many languages today such a JAVA and C# usually compile into a bytecode that is not machine code, but one that easily be interpreted at run time to produce machine code.
Although I've tried all the previous answers, only the following one worked out:
1 - Open Powershell (as Admin)
2 - Run:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
3 - Run:
Install-PackageProvider -Name NuGet
The author is Niels Weistra: Microsoft Forum
# reassign depth values under 10 to zero
df$depth[df$depth<10] <- 0
(For the columns that are factors, you can only assign values that are factor levels. If you wanted to assign a value that wasn't currently a factor level, you would need to create the additional level first:
levels(df$species) <- c(levels(df$species), "unknown")
df$species[df$depth<10] <- "unknown"
in my case it was just to put return ; at the end of function where i have set session
For my scenario, I found that there was a identity node in the web.config file.
<identity impersonate="true" userName="blah" password="blah">
When I removed the userName and password parameters from node, it started working.
Another option might be that you need to make sure that the specified userName has access to work with those "Temporary ASP.NET Files" folders found in the various C:\Windows\Microsoft.NET\Framework{version} folders.
Hoping this helps someone else out!
Procedure :
Code snippet:
String input = "world";
char[] arr = input.toCharArray();
Arrays.sort(arr);
String sorted = new String(arr);
System.out.println(sorted);