Complete step-by-step instructions for running the accelerated emulator can be found on the official Android developers website:
Caution: As of SDK Tools Revision 17, the virtual machine acceleration feature for the emulator is experimental; be alert for incompatibilities and errors when using this feature.
In the visual studio community edition 2017, sometimes the selection of Supported ABIs from Android Options wont work.
In that case please verify that the .csproj has the following line and no duplicate lines in the same build configurations.
<AndroidSupportedAbis>armeabi;armeabi-v7a;x86;x86_64;arm64-v8a</AndroidSupportedAbis>
In order to edit,
Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used
watch -n 5 -d "ps -eL <java_pid> | wc -l"
to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.
I've figured out. Try to disable Security Boot Control in BIOS options: http://remontka.pro/secure-boot-disable/ (sorry for russian examples) Or try to start system without Digital signature (only for one loading). I had had many unlucky attempts with 'HAXM installer, before I disabled this line. At the beginning I thought that's because Windows 10 Home was installed, and there're many limits.
In many cases some antivirus also start HyperV with window start and does not allow HAXM to install. I faced this issue because of AVAST antivirus. So I uninstalled AVAST, then HAXM installed properly after restart. Then I re-installed AVAST.
So its just a check while installing as now even with AVAST installed back, HAXM works properly with virtual box and android emulators.
This answer works for latest update on Windows 10 version 1709. Not tried with other version. But i hope it'll work.
I also ran into similar issue in my windows 10 system. I disabled Hyper-V and I tried all the answers posted here. But after that also i faced the same issue. So after lot of try, made it work using an documentation available in haxm manual. The document menntioned to use a tool named Device Guard and Credential Guard hardware readiness tool provided by Microsoft to disable Hyper-V along with some other features(Remember not only Hyper-V. So little cautios) completely. Follow the below steps to do that.
@powershell -ExecutionPolicy RemoteSigned -Command "X:\path\to\dgreadiness_v3.6\DG_Readiness_Tool_v3.6.ps1 -Disable"
Then if you try to install intel haxm, it'll work.
In case of latest update check the docs available in official intel haxm development link.
Hope it helps someone.
If you're running Mac, as @pedro mentions ensure you have the HAXM installer dowloaded via the Android SDK Manager.
Next install it! In finder navigate to /YOUR_SDK_PATH/extras/intel/Hardware_Accelerated_Execution_Manager/
Run and install the .mpgk in the following .dmg
IntelHAXM_1.1.0_for_10.10.dmg
IntelHAXM_1.1.0_below_10.10.dmg
Example:
$cd /YOUR_SDK_PATH/extras/intel/Hardware_Accelerated_Execution_Manager/ $open IntelHAXM_1.1.0_below_10.10.dmg
Although this isn't using the np array format, (to lazy to modify my code) this should do what you want... If, you truly want a column vector you will want to transpose the vector result. It all depends on how you are planning to use this.
def getVector(data_array,col):
vector = []
imax = len(data_array)
for i in range(imax):
vector.append(data_array[i][col])
return ( vector )
a = ([1,2,3], [4,5,6])
b = getVector(a,1)
print(b)
Out>[2,5]
So if you need to transpose, you can do something like this:
def transposeArray(data_array):
# need to test if this is a 1D array
# can't do a len(data_array[0]) if it's 1D
two_d = True
if isinstance(data_array[0], list):
dimx = len(data_array[0])
else:
dimx = 1
two_d = False
dimy = len(data_array)
# init output transposed array
data_array_t = [[0 for row in range(dimx)] for col in range(dimy)]
# fill output transposed array
for i in range(dimx):
for j in range(dimy):
if two_d:
data_array_t[j][i] = data_array[i][j]
else:
data_array_t[j][i] = data_array[j]
return data_array_t
For read-only controls they are the same. For 2 way databinding, using a datasource in which you want to update, insert, etc with declarative databinding, you'll need to use Bind
.
Imagine for example a GridView with a ItemTemplate
and EditItemTemplate
. If you use Bind
or Eval
in the ItemTemplate
, there will be no difference. If you use Eval
in the EditItemTemplate
, the value will not be able to be passed to the Update
method of the DataSource
that the grid is bound to.
UPDATE: I've come up with this example:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Data binding demo</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView
ID="grdTest"
runat="server"
AutoGenerateEditButton="true"
AutoGenerateColumns="false"
DataSourceID="mySource">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="edtName"
runat="server"
Text='<%# Bind("Name") %>'
/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
<asp:ObjectDataSource
ID="mySource"
runat="server"
SelectMethod="Select"
UpdateMethod="Update"
TypeName="MyCompany.CustomDataSource" />
</body>
</html>
And here's the definition of a custom class that serves as object data source:
public class CustomDataSource
{
public class Model
{
public string Name { get; set; }
}
public IEnumerable<Model> Select()
{
return new[]
{
new Model { Name = "some value" }
};
}
public void Update(string Name)
{
// This method will be called if you used Bind for the TextBox
// and you will be able to get the new name and update the
// data source accordingly
}
public void Update()
{
// This method will be called if you used Eval for the TextBox
// and you will not be able to get the new name that the user
// entered
}
}
You use the String.format() method.
For this specific error, I installed version 20 of Crystal Report and it solved my problem: https://www.tektutorialshub.com/crystal-reports/crystal-reports-download-for-visual-studio/#Service-Pack-16
You can also download the file alone using the following link https://www.nuget.org/api/v2/package/log4net/1.2.10 rename the file to .zip and extract it.
Easiest way to set permissions to 777 is to connect to Your server through FTP Application like FileZilla, right click on folder, module_installation, and click Change Permissions - then write 777 or check all permissions.
Stack Smashing here is actually caused due to a protection mechanism used by gcc to detect buffer overflow errors. For example in the following snippet:
#include <stdio.h>
void func()
{
char array[10];
gets(array);
}
int main(int argc, char **argv)
{
func();
}
The compiler, (in this case gcc) adds protection variables (called canaries) which have known values. An input string of size greater than 10 causes corruption of this variable resulting in SIGABRT to terminate the program.
To get some insight, you can try disabling this protection of gcc using option -fno-stack-protector
while compiling. In that case you will get a different error, most likely a segmentation fault as you are trying to access an illegal memory location. Note that -fstack-protector
should always be turned on for release builds as it is a security feature.
You can get some information about the point of overflow by running the program with a debugger. Valgrind doesn't work well with stack-related errors, but like a debugger, it may help you pin-point the location and reason for the crash.
You can also do something like this...
<input @input="myHandler('foo', 'bar', ...arguments)">
Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textD_Author"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Author : "
android:textColor="#0404B4"
android:textSize="20sp" />
<TextView
android:id="@+id/textD_Tag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Edition : "
android:textColor="#0404B4"
android:textSize="20sp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:weightSum="1" >
<Button
android:id="@+id/btbEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Edit" />
<Button
android:id="@+id/btnDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Delete" />
</LinearLayout>
</LinearLayout>
After return forward method you can simply do this:
return null;
It will break the current scope.
That functionality is already built into Notepad++. From the "Edit" menu, select "EOL Conversion" -> "UNIX/OSX Format".
screenshot of the option for even quicker finding (or different language versions)
You can also set the default EOL in notepad++ via "Settings" -> "Preferences" -> "New Document/Default Directory" then select "Unix/OSX" under the Format box.
This should work, at least according to the Search Filter Syntax article on MSDN network.
The "hang-up" you have noticed is probably just a delay. Try running the same query with narrower scope (for example the specific OU where the test object is located), as it may take very long time for processing if you run it against all AD objects.
You may also try separating the filter into two parts:
(|(displayName=*searchstring)(displayName=searchstring*))
if you don't want to create a UDF in VBA or you can't, this could be an alternative.
=Cell("Filename",A1)
this will give you the full file name, and from this you could get the user name with something like this:
=Mid(A1,Find("\",A1,4)+1;Find("\";A1;Find("\";A1;4))-2)
This Formula runs only from a workbook saved earlier.
You must start from 4th position because of the first slash from the drive.
KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any restraints on your data so they are used only for access - for quickly reaching certain ranges of records without scanning all records.
UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to quickly reach certain record ranges, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow the distinct values rule to be broken when inserting or updating data.
Your database system may allow a UNIQUE index to be applied to columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (the rationale here is that NULL is considered not equal to itself). Depending on your application, however, you may find this undesirable: if you wish to prevent this, you should disallow NULL values in the relevant columns.
PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a primary means to uniquely identify any row in the table, so unlike UNIQUE it should not be used on any columns which allow NULL values. Your PRIMARY index should be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.
Some database systems (such as MySQL's InnoDB) will store a table's records on disk in the order in which they appear in the PRIMARY index.
FULLTEXT indexes are different from all of the above, and their behaviour differs significantly between database systems. FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause, unlike the above three - which are typically implemented internally using b-trees (allowing for selecting, sorting or ranges starting from left most column) or hash tables (allowing for selection starting from left most column).
Where the other index types are general-purpose, a FULLTEXT index is specialised, in that it serves a narrow purpose: it's only used for a "full text search" feature.
All of these indexes may have more than one column in them.
With the exception of FULLTEXT, the column order is significant: for the index to be useful in a query, the query must use columns from the index starting from the left - it can't use just the second, third or fourth part of an index, unless it is also using the previous columns in the index to match static values. (For a FULLTEXT index to be useful to a query, the query must use all columns of the index.)
I'd personally make use of the table.insert
function:
table.insert(a,"b");
This saves you from having to iterate over the whole table therefore saving valuable resources such as memory and time.
do not place *jsp or *html in root folder of webapp and images you want to display in same root folder browser cannot acess the image in WEB-INF folder
Include the facebook button on the page which you want to share
<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://trial.com/news.php?newsid=<?php echo $content; ?>">
<img src="http://trial/new_img/facebook_link.png" style=" border: 1px solid #d9d9d9; box-shadow: 0 4px 7px 0 #a5a5a5; padding: 5px;" title="facebook_link" alt="facebook_link" />
</a>
This does happened also when you are cloning a repo without selecting any working directory. just make sure you did cd
into your working directory and i believe it will work just fine.
I faced this issue on GCP while deploying wordpress in the App Engine Standard environment. This solved it :
sudo apt-get install php7.2-zip
Example 1:
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson message converter
restTemplate.getMessageConverters()
.add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Basic XXXXXXXXXXXXXXXX=");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
restTemplate.getInterceptors()
.add(new BasicAuthorizationInterceptor(USERID, PWORD));
String requestJson = getRequetJson(Code, emailAddr, firstName, lastName);
response = restTemplate.postForObject(URL, requestJson, MYObject.class);
Example 2:
RestTemplate restTemplate = new RestTemplate();
String requestJson = getRequetJson(code, emil, name, lastName);
HttpHeaders headers = new HttpHeaders();
String userPass = USERID + ":" + PWORD;
String authHeader =
"Basic " + Base64.getEncoder().encodeToString(userPass.getBytes());
headers.set(HttpHeaders.AUTHORIZATION, authHeader);
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> request = new HttpEntity<String>(requestJson, headers);
ResponseEntity<MyObject> responseEntity;
responseEntity =
this.restTemplate.exchange(URI, HttpMethod.POST, request, Object.class);
responseEntity.getBody()
The getRequestJson
method creates a JSON Object:
private String getRequetJson(String Code, String emailAddr, String name) {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.createObjectNode();
((ObjectNode) rootNode).put("code", Code);
((ObjectNode) rootNode).put("email", emailAdd);
((ObjectNode) rootNode).put("firstName", name);
String jsonString = null;
try {
jsonString = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(rootNode);
}
catch (JsonProcessingException e) {
e.printStackTrace();
}
return jsonString;
}
My navigation bar was not showing, so I have used the following method in Swift 2 iOS 9
let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as! Dashboard
// Creating a navigation controller with viewController at the root of the navigation stack.
let navController = UINavigationController(rootViewController: viewController)
self.presentViewController(navController, animated:true, completion: nil)
You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession); CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);
I had to do this. this is a bit of hackery. not suggested.
but i found this very helpful
I made extension and struct
ViewController Extension + Struct
import UIKit
struct viewGlobal{
static var bottomConstraint : NSLayoutConstraint = NSLayoutConstraint()
}
extension UIViewController{ //keyboardHandler
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
func listenerKeyboard(bottomConstraint: NSLayoutConstraint) {
viewGlobal.bottomConstraint = bottomConstraint
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
// Register your Notification, To know When Key Board Hides.
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
//Dismiss Keyboard
@objc func dismissKeyboard() {
view.endEditing(true)
}
@objc func keyboardWillShow(notification:NSNotification) {
let userInfo:NSDictionary = notification.userInfo! as NSDictionary
let keyboardFrame:NSValue = userInfo.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
UIView.animate(withDuration: 0.5){
viewGlobal.bottomConstraint.constant = keyboardHeight
}
}
@objc func keyboardWillHide(notification:NSNotification) {
UIView.animate(withDuration: 0.5){
viewGlobal.bottomConstraint.constant = 0
}
}
}
Usage:
get most bottom constraint
@IBOutlet weak var bottomConstraint: NSLayoutConstraint! // default 0
call the function inside viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardWhenTappedAround()
listenerKeyboard(bottomConstraint: bottomConstraint)
// Do any additional setup after loading the view.
}
Hope this help.
-you keyboard will now auto close when user tap outside of textfield and
-it will push all view to above keyboard when keyboard appear.
-you could also used dismissKeyboard() when ever you need it
You can change the labels' text by adorning the property with the DisplayName
attribute.
[DisplayName("Someking Status")]
public string SomekingStatus { get; set; }
Or, you could write the raw HTML explicitly:
<label for="SomekingStatus" class="control-label">Someking Status</label>
Slight improvement on @arun-p-johny answer:
In html,
<pre id="log"></pre>
In js,
(function () {
var old = console.log;
var logger = document.getElementById('log');
console.log = function () {
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == 'object') {
logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(arguments[i], undefined, 2) : arguments[i]) + '<br />';
} else {
logger.innerHTML += arguments[i] + '<br />';
}
}
}
})();
Start using:
console.log('How', true, new Date());
Yes, you can.
From cplusplus.com:
Because these functions are operator overloading functions, the usual way in which they are called is:
strm >> variable;
Where
strm
is the identifier of a istream object andvariable
is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:strm >> variable1 >> variable2 >> variable3; //...
which is the same as performing successive extractions from the same object
strm
.
Just replace strm
with cin
.
SomeProperty.HasValue I think it's what you're looking for.
EDIT : btw, you can write System.Guid?
instead of Nullable<System.Guid>
;)
Matthew's answer awoke many emotions, because of the fact that it still lacks a minor detail. The general command would be:
# yum --nogpgcheck localinstall <package1_file_name> ... <packageN_file_name>
The package_file_name
above can include local absolute or relative path, or be a URL (possibly even an URI).
Yum would search for dependencies among all package files given on the command line AND IF IT FAILS to find the dependencies there, it will also use any configured and enabled yum repositories.
Neither the current working directory, nor the paths of any of package_file_name
will be searched, except when any of these directories has been previously configured as an enabled yum
repository.
So in the OP's case the yum
command:
# cd <path with pkg files>; yum --nogpgcheck localinstall ./proj1-1.0-1.x86_64.rpm ./libtest1-1.0-1.x86_64.rpm
would do, as would do the rpm
:
# cd <path with pkg files>; rpm -i proj1-1.0-1.x86_64.rpm libtest1-1.0-1.x86_64.rpm
The differencve between these yum
and rpm
invocations would only be visible if one of the packages listed to be installed had further dependencies on packages NOT listed on the command line.
In such a case rpm
will just refuse to continue, while yum
would use any configured and enabled yum repositories to search for dependencies, and may possibly succeed.
The current working directory will NOT be searched in any case, except when it has been previously configured as an enabled yum
repository.
per your advice, i am using handle and runnables to switch/change the content of the TextView using a "timer". for some reason, when running, the app always skips the second step ("Step Two: fry egg"), and only show the last (third) step ("Step three: serve egg").
TextView t;
private String sText;
private Handler mHandler = new Handler();
private Runnable mWaitRunnable = new Runnable() {
public void run() {
t.setText(sText);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMonster = BitmapFactory.decodeResource(getResources(),
R.drawable.monster1);
t=new TextView(this);
t=(TextView)findViewById(R.id.TextView01);
sText = "Step One: unpack egg";
t.setText(sText);
sText = "Step Two: fry egg";
mHandler.postDelayed(mWaitRunnable, 3000);
sText = "Step three: serve egg";
mHandler.postDelayed(mWaitRunnable, 4000);
...
}
You can also type "top" and look at the list of running processes.
In addition to grants, you can try creating synonyms. It will avoid the need for specifying the table owner schema every time.
From the connecting schema:
CREATE SYNONYM pi_int FOR pct.pi_int;
Then you can query pi_int
as:
SELECT * FROM pi_int;
Try doing it this way, it worked for me:
$this->validate($request, [
'name' => 'required|min:3|max:50',
'email' => 'email',
'vat_number' => 'max:13',
'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
'password_confirmation' => 'min:6'
]);`
Seems like the rule always has the validation on the first input among the pair...
And if you want to add a row, you can use a dictionary:
df = pd.DataFrame()
df = df.append({'name': 'Zed', 'age': 9, 'height': 2}, ignore_index=True)
which gives you:
age height name
0 9 2 Zed
You are trying to call DeckOfCards::shuffle
with a deckOfCards
parameter:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck
But the method takes a vector<Card>&
:
void deckOfCards::shuffle(vector<Card>& deck)
The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.
Error:
[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'
Paraphrased:
Hey, pal. You're trying to call a function called
shuffle
which apparently takes a single parameter of type reference-to-deckOfCards
, but there is no such function.
Error:
[Note] candidate is:
In file included from main.cpp
[Note] void deckOfCards::shuffle(std::vector&)
Paraphrased:
I mean, maybe you meant this other function called
shuffle
, but that one takes a reference-tovector<something>
.
Error:
[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'
Which I'd be happy to call if I knew how to convert from a
deckOfCards
to avector
; but I don't. So I won't.
On Linux:
java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'
On Mac OSX:
java -XX:+PrintFlagsFinal -version | grep -iE 'heapsize|permsize|threadstacksize'
On Windows:
C:\>java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"
Source: https://www.mkyong.com/java/find-out-your-java-heap-memory-size/
I understand that this is fairly old question and has some pretty good answers. But, here is my two cents for the sake of completeness.
As per the official documentation, there are four ways, you can allow complete access for robots to access your site.
Specify a global matcher with a disallow segment as mentioned by @unor. So your /robots.txt
looks like this.
User-agent: *
Disallow:
Create a /robots.txt
file with no content in it. Which will default to allow all for all type of Bots
.
Do not create a /robots.txt
altogether. Which should yield the exact same results as the above two.
From the robots documentation for meta tags, You can use the following meta tag on all your pages on your site to let the Bots
know that these pages are not supposed to be indexed.
<META NAME="ROBOTS" CONTENT="NOINDEX">
In order for this to be applied to your entire site, You will have to add this meta tag for all of your pages. And this tag should strictly be placed under your HEAD
tag of the page. More about this meta tag here.
here is my solution
void mkpath(char *p) {
char *path = strdup(p);
char *save_path = path;
char *sep1;
char *sep2=0;
do {
int idx = (sep2-path)<0 ? 0 : sep2-path;
sep1 = strchr(path + idx , '/');
sep2 = strchr(sep1+1, '/');
if (sep2) {
path[sep2-path]=0;
}
if(mkdir(path, 0777) && errno != EEXIST)
break;
if (sep2) {
path[sep2-path]='/';
}
} while (sep2);
free(save_path);
}
.
.
.
mkpath ("./the/new/path")
The above one with JQuery is the easiest and mostly used way. However you can use pure javascript but try to define this script in the head so that it is read at the beginning. What you are looking for is window.onload
event.
Below is a simple script that I created to run a counter. The counter then stops after 10 iterations
window.onload=function()
{
var counter = 0;
var interval1 = setInterval(function()
{
document.getElementById("div1").textContent=counter;
counter++;
if(counter==10)
{
clearInterval(interval1);
}
},1000);
}
Firefox doesn't seem to support the clear search field functionality... I found this pure CSS solution that works nicely: Textbox with a clear button completely in CSS | Codepen | 2013. The magic happens at
.search-box:not(:valid) ~ .close-icon {
display: none;
}
body {
background-color: #f1f1f1;
font-family: Helvetica,Arial,Verdana;
}
h2 {
color: green;
text-align: center;
}
.redfamily {
color: red;
}
.search-box,.close-icon,.search-wrapper {
position: relative;
padding: 10px;
}
.search-wrapper {
width: 500px;
margin: auto;
}
.search-box {
width: 80%;
border: 1px solid #ccc;
outline: 0;
border-radius: 15px;
}
.search-box:focus {
box-shadow: 0 0 15px 5px #b0e0ee;
border: 2px solid #bebede;
}
.close-icon {
border:1px solid transparent;
background-color: transparent;
display: inline-block;
vertical-align: middle;
outline: 0;
cursor: pointer;
}
.close-icon:after {
content: "X";
display: block;
width: 15px;
height: 15px;
position: absolute;
background-color: #FA9595;
z-index:1;
right: 35px;
top: 0;
bottom: 0;
margin: auto;
padding: 2px;
border-radius: 50%;
text-align: center;
color: white;
font-weight: normal;
font-size: 12px;
box-shadow: 0 0 2px #E50F0F;
cursor: pointer;
}
.search-box:not(:valid) ~ .close-icon {
display: none;
}
_x000D_
<h2>
Textbox with a clear button completely in CSS <br> <span class="redfamily">< 0 lines of JavaScript ></span>
</h2>
<div class="search-wrapper">
<form>
<input type="text" name="focus" required class="search-box" placeholder="Enter search term" />
<button class="close-icon" type="reset"></button>
</form>
</div>
_x000D_
I needed more functionality and added this jQuery in my code:
$('.close-icon').click(function(){ /* my code */ });
Source: https://github.com/webcaetano/mongo-mysql
10 rows
mysql insert: 1702ms
mysql select: 11ms
mongo insert: 47ms
mongo select: 12ms
100 rows
mysql insert: 8171ms
mysql select: 10ms
mongo insert: 167ms
mongo select: 60ms
1000 rows
mysql insert: 94813ms (1.58 minutes)
mysql select: 13ms
mongo insert: 1013ms
mongo select: 677ms
10.000 rows
mysql insert: 924695ms (15.41 minutes)
mysql select: 144ms
mongo insert: 9956ms (9.95 seconds)
mongo select: 4539ms (4.539 seconds)
Tags <%= %>
not works into a tag with runat="server"
. Move your code with <%= %>
into runat="server"
to an other tag (body
, head
, ...), or remove runat="server"
from container.
This one is working for me.
func stringByAddingPercentEncodingForFormData(plusForSpace: Bool=false) -> String? {
let unreserved = "*-._"
let allowed = NSMutableCharacterSet.alphanumericCharacterSet()
allowed.addCharactersInString(unreserved)
if plusForSpace {
allowed.addCharactersInString(" ")
}
var encoded = stringByAddingPercentEncodingWithAllowedCharacters(allowed)
if plusForSpace {
encoded = encoded?.stringByReplacingOccurrencesOfString(" ", withString: "+")
}
return encoded
}
I found above function from this link: http://useyourloaf.com/blog/how-to-percent-encode-a-url-string/.
If you are using ajax, it is possible to add the options xhrFields: { responseType: 'blob' }
:
$.ajax({
url: 'yourURL',
type: 'POST',
data: yourData,
xhrFields: { responseType: 'blob' },
success: function (data, textStatus, jqXHR) {
let src = window.URL.createObjectURL(data);
}
});
first make sure u enter the path environmental variable
C:\ path %path%;C:\Python27 press Enter
C:\Python27>python file_name press Enter
Change clean to
rm -f .lambda .lambda_t .activity .activity_t_lambda
I.e. don't prompt for remove; don't complain if file doesn't exist.
Please check the following file
%SystemRoot%\system32\drivers\etc\host
The line which bind the host name with ip is probably missing a line which bind them togather
127.0.0.1 localhost
If the given line is missing. Add the line in the file
Could you also check your MySQL database's user table and tell us the host column value for the user which you are using. You should have user privilege for both the host "127.0.0.1" and "localhost" and use % as it is a wild char for generic host name.
@bryc - yes, you could do it like this:
Element.prototype.setAttribute.apply(document.body,["foo","bar"])
But that seems like a lot of work and obfuscation compared to:
document.body.setAttribute("foo","bar")
It must be noted that there is also a considerable interest in Wicket and Scala. Wicket fits Scala suprisingly well. If you want to take advantage of the very mature Wicket project and its ecosystem (extensions) plus the concise syntax and productivity advantage of Scala, this one may be for you!
See also:
Look at easiest example to create popup using css and javascript.
See the full example at this link http://makecodeeasy.blogspot.in/2012/07/popup-in-java-script-and-css.html
Try:
git format-patch -1 <sha>
or
git format-patch -1 HEAD
According to the documentation link above, the -1
flag tells git how many commits should be included in the patch;
-<n>
Prepare patches from the topmost commits.
Apply the patch with the command:
git am < file.patch
Also check out the attr() function of the CSS content attribute. It outputs a given attribute of the element as a text node. Use it like so:
<div class="Owner Joe" />
div:before {
content: attr(class);
}
Or even with the new HTML5 custom data attributes:
<div data-employeename="Owner Joe" />
div:before {
content: attr(data-employeename);
}
You need to store all of the extra rows in the files in your dictionary, not just one of them:
dict1 = {row[0]: row[1:] for row in r}
...
dict2 = {row[0]: row[1:] for row in r}
Then, since the values in the dictionaries are lists, you need to just concatenate the lists together:
w.writerows([[key] + dict1.get(key, []) + dict2.get(key, []) for key in keys])
This may be the easiest method
This is an improved version of @schuttek's answer. It is improved because it correctly return false for primitives (e.g. isSubclassOf(int.class, Object.class) => false) and also correctly handles interfaces (e.g. isSubclassOf(HashMap.class, Map.class) => true).
static public boolean isSubclassOf(final Class<?> clazz, final Class<?> possibleSuperClass)
{
if (clazz == null || possibleSuperClass == null)
{
return false;
}
else if (clazz.equals(possibleSuperClass))
{
return true;
}
else
{
final boolean isSubclass = isSubclassOf(clazz.getSuperclass(), possibleSuperClass);
if (!isSubclass && clazz.getInterfaces() != null)
{
for (final Class<?> inter : clazz.getInterfaces())
{
if (isSubclassOf(inter, possibleSuperClass))
{
return true;
}
}
}
return isSubclass;
}
}
I'd like to add this simple example when you have to use Object.assign.
class SomeClass {
constructor() {
this.someValue = 'some value';
}
someMethod() {
console.log('some action');
}
}
const objectAssign = Object.assign(new SomeClass(), {});
objectAssign.someValue; // ok
objectAssign.someMethod(); // ok
const spread = {...new SomeClass()};
spread.someValue; // ok
spread.someMethod(); // there is no methods of SomeClass!
It can be not clear when you use JavaScript. But with TypeScript it is easier if you want to create instance of some class
const spread: SomeClass = {...new SomeClass()} // Error
import pickle
f=open("filename.dat","rb")
try:
while True:
x=pickle.load(f)
print x
except EOFError:
pass
f.close()
To switch to another branch, discarding all uncommitted changes (e.g. resulting from Git's strange handling of line endings):
git checkout -f <branchname>
I had a working copy with hundreds of changed files (but empty git diff --ignore-space-at-eol
) which I couldn't get rid off with any of the commands I read here, and git checkout <branchname>
won't work, either - unless given the -f
(or --force
) option.
For page object model -
@FindBy(xpath="//foo")
public WebElement textBox;
now in your function
public void clearExistingText(String newText){
textBox.clear();
textBox.sendKeys(newText);
}
for general selenium architecture -
driver.findElement(By.xpath("//yourxpath")).clear();
driver.findElement(By.xpath("//yourxpath")).sendKeys("newText");
I improved Niels's solution
class Array
def except(*values)
self - values
end
end
Now you can use
[1, 2, 3, 4].except(3, 4) # return [1, 2]
[1, 2, 3, 4].except(4) # return [1, 2, 3]
type : BOOL DATA (YES/NO) OR(1/0)
BOOL dtBool = 0;
OR
BOOL dtBool = NO;
NSLog(dtBool ? @"Yes" : @"No");
OUTPUT : NO
type : Long
long aLong = 2015;
NSLog(@"Display Long: %ld”, aLong);
OUTPUT : Display Long: 2015
long long veryLong = 20152015;
NSLog(@"Display very Long: %lld", veryLong);
OUTPUT : Display very Long: 20152015
type : String
NSString *aString = @"A string";
NSLog(@"Display string: %@", aString);
OUTPUT : Display String: a String
type : Float
float aFloat = 5.34245;
NSLog(@"Display Float: %F", aFloat);
OUTPUT : isplay Float: 5.342450
type : Integer
int aInteger = 3;
NSLog(@"Display Integer: %i", aInteger);
OUTPUT : Display Integer: 3
NSLog(@"\nDisplay String: %@ \n\n Display Float: %f \n\n Display Integer: %i", aString, aFloat, aInteger);
OUTPUT : String: a String
Display Float: 5.342450
Display Integer: 3
http://luterr.blogspot.sg/2015/04/example-code-nslog-console-commands-to.html
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()
Basically doing String.intern() on a series of strings will ensure that all strings having same contents share same memory. So if you have list of names where 'john' appears 1000 times, by interning you ensure only one 'john' is actually allocated memory.
This can be useful to reduce memory requirements of your program. But be aware that the cache is maintained by JVM in permanent memory pool which is usually limited in size compared to heap so you should not use intern if you don't have too many duplicate values.
More on memory constraints of using intern()
On one hand, it is true that you can remove String duplicates by internalizing them. The problem is that the internalized strings go to the Permanent Generation, which is an area of the JVM that is reserved for non-user objects, like Classes, Methods and other internal JVM objects. The size of this area is limited, and is usually much smaller than the heap. Calling intern() on a String has the effect of moving it out from the heap into the permanent generation, and you risk running out of PermGen space.
-- From: http://www.codeinstructions.com/2009/01/busting-javalangstringintern-myths.html
From JDK 7 (I mean in HotSpot), something has changed.
In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.
-- From Java SE 7 Features and Enhancements
Update: Interned strings are stored in main heap from Java 7 onwards. http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html#jdk7changes
I like this way:
ActiveSheet.UsedRange.Rows.Count
The same can be done with columns count. For me, always work. But, if you have data in another column, the code above will consider them too, because the code is looking for all cell range in the sheet.
You need to set the binding context of the ToolStripComboBox.ComboBox.
Here is a slightly modified version of the code that I have just recreated using Visual Studio. The menu item combo box is called toolStripComboBox1 in my case. Note the last line of code to set the binding context.
I noticed that if the combo is in the visible are of the toolstrip, the binding works without this but not when it is in a drop-down. Do you get the same problem?
If you can't get this working, drop me a line via my contact page and I will send you the project. You won't be able to load it using SharpDevelop but will with C# Express.
var languages = new string[2];
languages[0] = "English";
languages[1] = "German";
DataSet myDataSet = new DataSet();
// --- Preparation
DataTable lTable = new DataTable("Lang");
DataColumn lName = new DataColumn("Language", typeof(string));
lTable.Columns.Add(lName);
for (int i = 0; i < languages.Length; i++)
{
DataRow lLang = lTable.NewRow();
lLang["Language"] = languages[i];
lTable.Rows.Add(lLang);
}
myDataSet.Tables.Add(lTable);
toolStripComboBox1.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView;
toolStripComboBox1.ComboBox.DisplayMember = "Language";
toolStripComboBox1.ComboBox.BindingContext = this.BindingContext;
I had the same problem (exception 'Could not load NIB in bundle: ..') after upgrading my xcode from 3.2 to 4.02. Whereas deploying of my app with Xcode 3.2 worked fine it crashes with xcode 4 raising the exception mentioned above - but only when I tried to deploy to the IOS Simulator (v.4.2). Targeting the IOS device (v.4.1) acted also with Xcode 4.
It turned out (after hours of desperately scrabbling around) that the reason was an almost "hidden" setting in the .xib-file:
Visit the properties of the .xib files in the file inspector: The property 'Location' was set to 'Relative to Group' for all .xib files. I changed it to 'Relative to project' and voila: all .xib files now are correctly loaded in IOS simulator !
I have no clue what's the reason behind that for this odd Xcode4 behavior but maybe it's worth to make an attempt ?
You've got a number of answers already, and I broadly agree with J.F. Sebastian, but you might find this useful as a shortcut:
Any time you see varname =
, you're creating a new name binding within the function's scope. Whatever value varname
was bound to before is lost within this scope.
Any time you see varname.foo()
you're calling a method on varname
. The method may alter varname (e.g. list.append
). varname
(or, rather, the object that varname
names) may exist in more than one scope, and since it's the same object, any changes will be visible in all scopes.
[note that the global
keyword creates an exception to the first case]
For the less specific case (not just the code in the question - since this is one of the first results in Google for this generic error message. This error also occurs when running certain os command with None argument.
For example:
os.path.exists(arg)
os.stat(arg)
Will raise this exception when arg is None.
As mentioned in @davidcondrey's reply, there is not just the ZWSP, but also the SHY ­ ­
that can be used in very long, constructed words (think German or Dutch) that have to be broken on the spot you want it to be.
Invisible, but it gives a hyphen the moment it's needed, thus keeping both word connected and line filled to the utmost.
That way the word luchthavenpolitieagent might be noted as lucht­haven­politie­agent
which gives longer parts than the syllables of the word.
Though I never read anything official about it, these soft hyphens manage to get higher priority in browsers than the official hyphens in the single words of the construct (if they have some extension for it at all).
In practice, no browser is capable of breaking such a long, constructed word by itself; on smaller screens resulting in a new line for it, or in some cases even a one-word-line (like when two of those constructed words follow up).
FYI: it's Dutch for airport police officer
Simply call list
on the generator.
lst = list(gen)
lst
Be aware that this affects the generator which will not return any further items.
You also cannot directly call list
in IPython, as it conflicts with a command for listing lines of code.
Tested on this file:
def gen():
yield 1
yield 2
yield 3
yield 4
yield 5
import ipdb
ipdb.set_trace()
g1 = gen()
text = "aha" + "bebe"
mylst = range(10, 20)
which when run:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.
There are debugger commands p
and pp
that will print
and prettyprint
any expression following them.
So you could use it as follows:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c
There is also an exec
command, called by prefixing your expression with !
, which forces debugger to take your expression as Python one.
ipdb> !list(g1)
[]
For more details see help p
, help pp
and help exec
when in debugger.
ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
The for loop is getting one extra run. Change
for (x=0;x<=InvForm.SelBranch.length;x++)
to
for (x=0; x < InvForm.SelBranch.length; x++)
Performance wise there is no point to keep non clustered indexes during this as they will get re-updated on drop and create. If it is a big data set you should consider renaming the table (if possible , any security settings on it?), re-creating an empty table with the correct keys migrate all data there. You have to make sure you have enough space for this.
let str = "Hello World"
console.log(str.substring(1, 3)) // el -> Excludes the last index
console.log(str.substr(1, 3)) // ell -> Includes the last index
at -l
to list jobs, which gives return like this:
age2%> at -l
11 2014-10-21 10:11 a hoppent
10 2014-10-19 13:28 a hoppent
atrm 10
kills job 10
Or so my sysadmin told me, and it
f = lambda A, n=3: [A[i:i+n] for i in range(0, len(A), n)]
f(A)
n
- the predefined length of result arrays
I think they updated the html5 video and deprecated some codecs. It worked for me after removing the codecs.
In the below example:
<video>_x000D_
<source src="sample-clip.mp4" type="video/mp4; codecs='avc1.42E01E, mp4a.40.2'">_x000D_
<source src="sample-clip.webm" type="video/webm; codecs='vp8, vorbis'"> _x000D_
</video>_x000D_
_x000D_
must be changed to_x000D_
_x000D_
<video>_x000D_
<source src="sample-clip.mp4" type="video/mp4">_x000D_
<source src="sample-clip.webm" type="video/webm">_x000D_
</video>
_x000D_
Change the <a>
tag like this:
<a href="newsletter_01.pdf" target="_blank">
You can find more about the target
attribute here.
If you are using Maven, add the below config in your pom.xml:
<build>
<testResources>
<testResource>
<directory>src/main/webapp</directory>
</testResource>
</testResources>
</build>
With this config, you will be able to access xml files in WEB-INF folder. From Maven POM Reference: The testResources element block contains testResource elements. Their definitions are similar to resource elements, but are naturally used during test phases.
Although I am very late to this but after seeing some legitimate questions for those who wanted to use INSERT-SELECT
query with GROUP BY
clause, I came up with the work around for this.
Taking further the answer of Marcus Adams and accounting GROUP BY
in it, this is how I would solve the problem by using Subqueries in the FROM Clause
INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct,
inact, inadur, inadist,
smlct, smldur, smldist,
larct, lardur, lardist,
emptyct, emptydur)
SELECT sb.id, uid, sb.location, sb.animal, sb.starttime, sb.endtime, sb.entct,
sb.inact, sb.inadur, sb.inadist,
sb.smlct, sb.smldur, sb.smldist,
sb.larct, sb.lardur, sb.lardist,
sb.emptyct, sb.emptydur
FROM
(SELECT id, uid, location, animal, starttime, endtime, entct,
inact, inadur, inadist,
smlct, smldur, smldist,
larct, lardur, lardist,
emptyct, emptydur
FROM tmp WHERE uid=x
GROUP BY location) as sb
ON DUPLICATE KEY UPDATE entct=sb.entct, inact=sb.inact, ...
There is boolean data type in SQL Server. Its values can be TRUE
, FALSE
or UNKNOWN
. However, the boolean data type is only the result of a boolean expression containing some combination of comparison operators (e.g. =
, <>
, <
, >=
) or logical operators (e.g. AND
, OR
, IN
, EXISTS
). Boolean expressions are only allowed in a handful of places including the WHERE
clause, HAVING
clause, the WHEN
clause of a CASE
expression or the predicate of an IF
or WHILE
flow control statement.
For all other usages, including the data type of a column in a table, boolean is not allowed. For those other usages, the BIT
data type is preferred. It behaves like a narrowed-down INTEGER
which allows only the values 0
, 1
and NULL
, unless further restricted with a NOT NULL
column constraint or a CHECK
constraint.
To use a BIT
column in a boolean expression it needs to be compared using a comparison operator such as =
, <>
or IS NULL
. e.g.
SELECT
a.answer_body
FROM answers AS a
WHERE a.is_accepted = 0;
From a formatting perspective, a bit
value is typically displayed as 0
or 1
in client software. When a more user-friendly format is required, and it can't be handled at an application tier in front of the database, it can be converted "just-in-time" using a CASE
expression e.g.
SELECT
a.answer_body,
CASE a.is_accepted WHEN 1 THEN 'TRUE' ELSE 'FALSE' END AS is_accepted
FROM answers AS a;
Storing boolean values as a character data type like char(1)
or varchar(5)
is also possible, but that is much less clear, has more storage/network overhead, and requires CHECK
constraints on each column to restrict illegal values.
For reference, the schema of answers
table would be similar to:
CREATE TABLE answers (
...,
answer_body nvarchar(MAX) NOT NULL,
is_accepted bit NOT NULL DEFAULT (0)
);
I prefer to use BINARY(32) since it's the optimized way!
You can place in that 32 hex digits from (00 to FF).
Therefore BINARY(32)!
You can instruct tesseract to use only digits, and if that is not accurate enough then best chance of getting better results is to go trough training process: http://www.resolveradiologic.com/blog/2013/01/15/training-tesseract/
The eval()
function evaluates an expression, but "5+5"
is a string, not an expression. Use parse()
with text=<string>
to change the string into an expression:
> eval(parse(text="5+5"))
[1] 10
> class("5+5")
[1] "character"
> class(parse(text="5+5"))
[1] "expression"
Calling eval()
invokes many behaviours, some are not immediately obvious:
> class(eval(parse(text="5+5")))
[1] "numeric"
> class(eval(parse(text="gray")))
[1] "function"
> class(eval(parse(text="blue")))
Error in eval(expr, envir, enclos) : object 'blue' not found
See also tryCatch.
When encoding query values, either form, plus or percent-20, is valid; however, since the bandwidth of the internet isn't infinite, you should use plus, since it's two fewer bytes.
With the -atime, -ctime, and -mtime switches to find, you can get close to what you want to achieve.
This is a FAQ:
//somexpression[$N]
means "Find every node selected by //somexpression
that is the $N
th child of its parent".
What you want is:
(//input[@id="search_query"])[2]
Remember: The []
operator has higher precedence (priority) than the //
abbreviation.
SELECT *
FROM ...
WHERE EXISTS(SELECT 1
FROM sys.columns c
WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
AND c.name = 'ModifiedByUser'
)
This works for me:
File f = new File("some.properties");
Properties props = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
props.load(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
fis = null;
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
Set this in the constructor:
public class SearchModel
{
public bool IsMale { get; set; }
public bool IsFemale { get; set; }
public SearchModel()
{
IsMale = true;
IsFemale = true;
}
}
Then pass it to the view in your GET action:
[HttpGet]
public ActionResult Search()
{
return new View(new SearchModel());
}
In Google Sheets, to count the number of rows which contain at least one non-empty cell within a two-dimensional range:
=ARRAYFORMULA(
SUM(
N(
MMULT(
N(A1:C5<>""),
TRANSPOSE(COLUMN(A1:C5)^0)
)
>0
)
)
)
Where A1:C5 is the range you're checking for non-empty rows.
The formula comes from, and is explained in the following article from EXCELXOR - https://excelxor.com/2015/03/30/counting-rows-where-at-least-one-condition-is-met/
Use Date.Now
instead of DateTime.Now
Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);
For username and password protected services use the following
curl -u admin:password -X GET http://172.16.2.125:9200 -d '{"sort":[{"lastUpdateTime":{"order":"desc"}}]}'
The new tag for recent Chrome and Chromium browsers is :
--disable-web-security --user-data-dir=c:\my\data
(in the following code, you should substitute 'UTC'
for zone and now()
for timestamp)
timestamp AT TIME ZONE zone
- SQL-standard-conformingtimezone(zone, timestamp)
- arguably more readableThe function timezone(zone, timestamp) is equivalent to the SQL-conforming construct timestamp AT TIME ZONE zone.
'UTC'
) or as an interval (e.g., INTERVAL '-08:00'
) - here is a list of all available time zonesnow()
returns a value of type timestamp (just what we need) with your database's default time zone attached (e.g. 2018-11-11T12:07:22.3+05:00
).timezone('UTC', now())
turns our current time (of type timestamp with time zone) into the timezonless equivalent in UTC
.SELECT timestamp with time zone '2020-03-16 15:00:00-05' AT TIME ZONE 'UTC'
will return 2020-03-16T20:00:00Z
.Docs: timezone()
open terminal
\curl -sSL https://get.rvm.io | bash -s stable
restart terminal then
rvm install ruby-2.4.2
check ruby version it should be 2.4.2
The proposed iterative solutions can be sped up dramatically on two fronts:
1) Multiply the font size by some constant, rather than adding or subtracting 1.
2) First, zero in using a course constant, say, double the size each loop. Then, with a rough idea of where to start, do the same thing with a finer adjustment, say, multiply by 1.1. While the perfectionist might want the exact integer pixel size of the ideal font, most observers don't notice the difference between 100 and 110 pixels. If you are a perfectionist, then repeat a third time with an even finer adjustment.
Rather than writing a specific routine or plug-in that answers the exact question, I just rely on the basic ideas and write variations of the code to handle all kinds of layout issues, not just text, including fitting divs, spans, images,... by width, height, area,... within a container, matching another element....
Here's an example:
var nWindowH_px = jQuery(window).height();
var nWas = 0;
var nTry = 5;
do{
nWas = nTry;
nTry *= 2;
jQuery('#divTitle').css('font-size' ,nTry +'px');
}while( jQuery('#divTitle').height() < nWindowH_px );
nTry = nWas;
do{
nWas = nTry;
nTry = Math.floor( nTry * 1.1 );
jQuery('#divTitle').css('font-size' ,nTry +'px');
}while( nWas != nTry && jQuery('#divTitle').height() < nWindowH_px );
jQuery('#divTitle').css('font-size' ,nWas +'px');
const a = {
foods: {
dinner: 'Pasta'
}
}
let b = JSON.parse(JSON.stringify(a))
b.foods.dinner = 'Soup'
console.log(b.foods.dinner) // Soup
console.log(a.foods.dinner) // Pasta
Using JSON.stringify
and JSON.parse
is the best way. Because by using the spread operator we will not get the efficient answer when the json object contains another object inside it. we need to manually specify that.
If you want to automatically/periodically clean up exited containers and remove images and volumes that aren't in use by a running container you can download the Docker image meltwater/docker-cleanup
.
That way you don't need to go clean it up by hand.
Just run:
docker run -d -v /var/run/docker.sock:/var/run/docker.sock:rw -v /var/lib/docker:/var/lib/docker:rw --restart=unless-stopped meltwater/docker-cleanup:latest
It will run every 30 minutes (or however long you set it using DELAY_TIME=1800 option) and clean up exited containers and images.
More details: https://github.com/meltwater/docker-cleanup/blob/master/README.md
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf())
dat.setDate(dat.getDate() + days);
return dat;
}
function getDates(startDate, stopDate) {
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= stopDate) {
dateArray.push(currentDate);
currentDate = currentDate.addDays(1);
}
return dateArray;
}
var dateArray = getDates(new Date(), (new Date().addDays(7)));
for (i = 0; i < dateArray.length; i ++ ) {
// alert (dateArray[i]);
date=('0'+dateArray[i].getDate()).slice(-2);
month=('0' +(dateArray[i].getMonth()+1)).slice(-2);
year=dateArray[i].getFullYear();
alert(date+"-"+month+"-"+year );
}
It is a little complicated, but you can draw all the objects by the following code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
# draw cube
r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
if np.sum(np.abs(s-e)) == r[1]-r[0]:
ax.plot3D(*zip(s, e), color="b")
# draw sphere
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="r")
# draw a point
ax.scatter([0], [0], [0], color="g", s=100)
# draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
class Arrow3D(FancyArrowPatch):
def __init__(self, xs, ys, zs, *args, **kwargs):
FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
FancyArrowPatch.draw(self, renderer)
a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)
plt.show()
You can use axis
:
> axis(side=1, at=c(0:23))
That is, something like this:
plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()
I wrote this simple shell script using Zenity that lets you pick which avd you want to run. If you don't have ANDROID_HOME defined, you can just replace that with the full path to emulator. This would be easy to do with select instead of Zenity also, but I opted for Zenity since I'm running it from the xfce-application menu (though a .desktop-file).
#!/bin/sh
opt=$(zenity --title="Choose AVD" --text="Choose which emulator to start" --list \
--column="Devices" --separator="\n" `$ANDROID_HOME/emulator/emulator -list-avds`);
$ANDROID_HOME/emulator/emulator -avd $opt
You can return empty array by following two ways:
If you want to return array of int
then
Using {}
:
int arr[] = {};
return arr;
Using new int[0]
:
int arr[] = new int[0];
return arr;
Same way you can return array for other datatypes as well.
If you want to make address directly, the worksheet must exist.
Turning off automatic recalculation want help you :)
But... you can get value indirectly...
.FormulaR1C1 = "=INDIRECT(ADDRESS(2,7,1,0,""" & strProjectName & """),FALSE)"
At the time formula is inserted it will return #REF error, because strProjectName sheet does not exist.
But after this worksheet appear Excel will calculate formula again and proper value will be shown.
Disadvantage: there will be no tracking, so if you move the cell or change worksheet name, the formula will not adjust to the changes as in the direct addressing.
For nodejs log file you can use winston and morgan and in place of your console.log() statement user winston.log() or other winston methods to log. For working with winston and morgan you need to install them using npm. Example: npm i -S winston npm i -S morgan
Then create a folder in your project with name winston and then create a config.js in that folder and copy this code given below.
const appRoot = require('app-root-path');
const winston = require('winston');
// define the custom settings for each transport (file, console)
const options = {
file: {
level: 'info',
filename: `${appRoot}/logs/app.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
},
console: {
level: 'debug',
handleExceptions: true,
json: false,
colorize: true,
},
};
// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
],
exitOnError: false, // do not exit on handled exceptions
});
} else {
logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
new winston.transports.Console(options.console),
],
exitOnError: false, // do not exit on handled exceptions
});
}
// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
write(message) {
logger.info(message);
},
};
module.exports = logger;
After copying the above code make make a folder with name logs parallel to winston or wherever you want and create a file app.log in that logs folder. Go back to config.js and set the path in the 5th line "filename: ${appRoot}/logs/app.log
,
" to the respective app.log created by you.
After this go to your index.js and include the following code in it.
const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));
winston.info('You have successfully started working with winston and morgan');
Using Helper class you can access SQLite Database and can perform the various operations on it by overriding the onCreate() and onUpgrade() methods.
http://technologyguid.com/android-sqlite-database-app-example/
Try
nltk.download('all')
this will download all the data and no need to download individually.
I am not sure about your DBMS. So, I created a temporary table in Redshift and from my experience, I think this query should return what you are looking for:
select min(Id), distinct MailId, EmailAddress, Name
from yourTableName
group by MailId, EmailAddress, Name
I see that I am using a GROUP BY clause
but you still won't have two rows against any particular MailId
.
You might want to arrange your HTML so that the user can still open all of the links even if JavaScript isn’t enabled. (We call this progressive enhancement.) If so, something like this might work well:
<ul class="yourlinks">
<li><a href="http://www.google.com/"></li>
<li><a href="http://www.yahoo.com/"></li>
</ul>
$(function() { // On DOM content ready...
var urls = [];
$('.yourlinks a').each(function() {
urls.push(this.href); // Store the URLs from the links...
});
var multilink = $('<a href="#">Click here</a>'); // Create a new link...
multilink.click(function() {
for (var i in urls) {
window.open(urls[i]); // ...that opens each stored link in its own window when clicked...
}
});
$('.yourlinks').replaceWith(multilink); // ...and replace the original HTML links with the new link.
});
This code assumes you’ll only want to use one “multilink” like this per page. (I’ve also not tested it, so it’s probably riddled with errors.)
JPA was designed to provide an automatic mapping between Objects and a relational database. Since Integer is not a persistant entity, why do you need to use JPA ? A simple JDBC request will work fine.
EDIT: So facebook has changed it again! No more searching by username - have amended the answer below...
https://graph.facebook.com/{{UID}}/picture?redirect=false&height=200&width=200
e.g. https://graph.facebook.com/4/picture?redirect=false&height=200&width=200
Use react native debugger for logging and redux store https://github.com/jhen0409/react-native-debugg
Just download it and run as software then enable Debug mode from the simulator.
It supports other debugging feature just like element in chrome developer tools, which helps to see the styling provided to any component.
Last complete support for redux dev tools
The problem defintely relates to the use of (in this case) the max() function. Any aggregation function used during a join (e.g. to retrieve the max or min or avg value from a joined table) will cause the error. And the same applies to using subqueries instead of joins (as in the original code).
This is incredibly annoying (and unjustified!) as it is a reasonably common thing to want to do. I've also had to use temp tables to get around it (pull the aggregated value into a temp table with an insert statement, then join to this table with your update, then drop the temp table).
Glenn
If you want to download the latest jar between 2 repositores, you can use this solution. I actually use it within my Jenkins pipeline, it works perfectly. Let's say you have a plugins-release-local and plugins-snapshot-local and you want to download the latest jar between these. Your shell script should look like this
NOTE : I use jfrog cli and it's configured with my Artifactory server.
# your repo, you can change it then or pass an argument to the script
# repo = $1 this get the first arg passed to the script
repo=plugins-snapshot-local
# change this by your artifact path, or pass an argument $2
artifact=kshuttle/ifrs16
path=$repo/$artifact
echo $path
~/jfrog rt download --flat $path/maven-metadata.xml version/
version=$(cat version/maven-metadata.xml | grep latest | sed "s/.*<latest>\([^<]*\)<\/latest>.*/\1/")
echo "VERSION $version"
~/jfrog rt download --flat $path/$version/maven-metadata.xml build/
build=$(cat build/maven-metadata.xml | grep '<value>' | head -1 | sed "s/.*<value>\([^<]*\)<\/value>.*/\1/")
echo "BUILD $build"
# change this by your app name, or pass an argument $3
name=ifrs16
jar=$name-$build.jar
url=$path/$version/$jar
# Download
echo $url
~/jfrog rt download --flat $url
def getLatestArtifact(repo, pkg, appName, configDir){
sh """
~/jfrog rt download --flat $repo/$pkg/maven-metadata.xml $configDir/version/
version=\$(cat $configDir/version/maven-metadata.xml | grep latest | sed "s/.*<latest>\\([^<]*\\)<\\/latest>.*/\\1/")
echo "VERSION \$version"
~/jfrog rt download --flat $repo/$pkg/\$version/maven-metadata.xml $configDir/build/
build=\$(cat $configDir/build/maven-metadata.xml | grep '<value>' | head -1 | sed "s/.*<value>\\([^<]*\\)<\\/value>.*/\\1/")
echo "BUILD \$build"
jar=$appName-\$build.jar
url=$repo/$pkg/\$version/\$jar
# Download
echo \$url
~/jfrog rt download --flat \$url
"""
}
def clearDir(dir){
sh """
rm -rf $dir/*
"""
}
node('mynode'){
stage('mysstage'){
def repos = ["plugins-snapshot-local","plugins-release-local"]
for (String repo in repos) {
getLatestArtifact(repo,"kshuttle/ifrs16","ifrs16","myConfigDir/")
}
//optional
clearDir("myConfigDir/")
}
}
This helps alot when you want to get the latest package between 1 or more repos. Hope it helps u too! For more Jenkins scripted pipelines info, visit Jenkins docs.
All declarations of functions and variables in header files should be extern
.
Exceptions to this rule are inline functions defined in the header and variables which - although defined in the header - will have to be local to the translation unit (the source file the header gets included into): these should be static
.
In source files, extern
shouldn't be used for functions and variables defined in the file. Just prefix local definitions with static
and do nothing for shared definitions - they'll be external symbols by default.
The only reason to use extern
at all in a source file is to declare functions and variables which are defined in other source files and for which no header file is provided.
Declaring function prototypes extern
is actually unnecessary. Some people dislike it because it will just waste space and function declarations already have a tendency to overflow line limits. Others like it because this way, functions and variables can be treated the same way.
Convert a string to a DateTime, you could try
DateTime timeValue = Convert.ToDateTime("01:00 PM");
Console.WriteLine(timeValue.ToString("HH:mm"));
Collections use generics which support either reference types or wilcards. You can however use an Integer
wrapper
List<Integer> list = new ArrayList<>();
Facebook Graph is awesome. Just do something like below. I've entereted perl.org URL, you can put any URL there.
You can use SELECT @@IDENTITY as well
To display the html/xml "as is" (i.e. all entities and elements), simply escape the characters <, &, and enclose the result with <pre>:
$XML = '<?xml version="1.0" encoding="UTF-8"?>
<root>
<foo>ó</foo>
<bar>ó</bar>
</root>';
$XML = str_replace('&', '&', $XML);
$XML = str_replace('<', '<', $XML);
echo '<pre>' . $XML . '</pre>';
Prints:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<foo>ó</foo>
<bar>ó</bar>
</root>
Tested on Chrome 45
SELECT (cast(timestamp_1 as bigint) - cast(timestamp_2 as bigint)) FROM table;
In case if someone is having an issue using extract.
Try the array_keys PHP function.
$key_string1 = array_keys($list, 'string1');
We can Remove or Delete a specified column or sprcified columns by drop() method.
Suppose df is a dataframe.
Column to be removed = column0
Code:
df = df.drop(column0, axis=1)
To remove multiple columns col1, col2, . . . , coln, we have to insert all the columns that needed to be removed in a list. Then remove them by drop() method.
Code:
df = df.drop([col1, col2, . . . , coln], axis=1)
I hope it would be helpful.
The shortest way would be:
$("#" + row_id)
Limiting the search to the body doesn't have any benefit.
Also, you should consider renaming your id
s to something more meaningful (and HTML compliant as per Paolo's answer), especially if you have another set of data that needs to be named as well.
Your text may be located in the networking response.There is also a search tool in the Network tab, and you may try it.
What you want to search for may stay either in DOM or in memory. If it is not in DOM, well, it may be in memory, because you have just see it in your computer screen anyway. The text you search for may be loaded either from scripts in the initial DOM or from response in the later request.
If you have Unicode/nChar/nVarChar values you are concatenating, then SQL Server will implicitly convert your string to nVarChar(4000), and it is unfortunately too dumb to realize it will truncate your string or even give you a Warning that data has been truncated for that matter!
When concatenating long strings (or strings that you feel could be long) always pre-concatenate your string building with CAST('' as nVarChar(MAX)) like so:
SET @Query = CAST('' as nVarChar(MAX))--Force implicit conversion to nVarChar(MAX)
+ 'SELECT...'-- some of the query gets set here
+ '...'-- more query gets added on, etc.
What a pain and scary to think this is just how SQL Server works. :(
I know other workarounds on the web say to break up your code into multiple SET/SELECT assignments using multiple variables, but this is unnecessary given the solution above.
For those who hit an 8000 character max, it was probably because you had no Unicode so it was implicitly converted to VarChar(8000).
Explanation:
What's happening behind the scenes is that even though the variable you are assigning to uses (MAX), SQL Server will evaluate the right-hand side of the value you are assigning first and default to nVarChar(4000) or VarChar(8000) (depending on what you're concatenating). After it is done figuring out the value (and after truncating it for you) it then converts it to (MAX) when assigning it to your variable, but by then it is too late.
This is a nice example: The Repository Pattern Example in C#
Basically, repository hides the details of how exactly the data is being fetched/persisted from/to the database. Under the covers:
You will probably get an UAC prompt when importing the reg file. If you accept that, you have more rights.
Since you are writing to the 'policies' key, you need to have elevated rights. This part of the registry protected, because it contains settings that are administered by your system administrator.
Alternatively, you may try to run regedit.exe
from the command prompt.
regedit.exe /S yourfile.reg
.. should silently import the reg file. See RegEdit Command Line Options Syntax for more command line options.
xmlns:android
Defines the Android namespace. This attribute should always be set to "
http://schemas.android.com/apk/res/android
".
refer https://developer.android.com/guide/topics/manifest/manifest-element#nspace
(I know the question is old, but I think this might be good as a reference for people with similar questions)
If you want to load data from an ASCII/text file (which has the benefit or being more or less human-readable and easy to parse in other software), numpy.loadtxt is probably what you want:
If you just want to quickly save and load numpy arrays/matrices to and from a file, take a look at numpy.save and numpy.load:
If you are on Mac OSX Maverick,
it's ~/.bash_profile
not ~/.bashrc
Try putting the code in there, close the terminal and then try again. Should be working
You module and class AthleteList
have the same name. Change:
import AthleteList
to:
from AthleteList import AthleteList
This now means that you are importing the module object and will not be able to access any module methods you have in AthleteList
var lineChartData = {_x000D_
labels: ["", "", "", "", "", "", ""] // To hide horizontal labels_x000D_
,datasets : [_x000D_
{_x000D_
label: "My First dataset",_x000D_
fillColor : "rgba(220,220,220,0.2)",_x000D_
strokeColor : "rgba(220,220,220,1)",_x000D_
pointColor : "rgba(220,220,220,1)",_x000D_
pointStrokeColor : "#fff",_x000D_
pointHighlightFill : "#fff",_x000D_
pointHighlightStroke : "rgba(220,220,220,1)",_x000D_
_x000D_
data: [28, 48, 40, 19, 86, 27, 90]_x000D_
}_x000D_
]_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
window.onload = function(){_x000D_
var options = {_x000D_
scaleShowLabels : false // to hide vertical lables_x000D_
};_x000D_
var ctx = document.getElementById("canvas1").getContext("2d");_x000D_
window.myLine = new Chart(ctx).Line(lineChartData, options);_x000D_
_x000D_
}
_x000D_
In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:
>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)
The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)
The type of a complex number is complex
, and you can use the type as a constructor if you prefer:
>>> complex(2,3)
(2+3j)
A complex number has some built-in accessors:
>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)
Several built-in functions support complex numbers:
>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)
The standard module cmath
has more functions that handle complex numbers:
>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)
For what it's worth, let's say you wanted to resize the view in device independent pixels (dp): -
You need to use a method called applyDimension
, that's a member of the class TypedValue
to convert from dp to pixels. So if I want to set the height to 150dp (say) - then I could do this:
float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, getResources().getDisplayMetrics());
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) someLayout.getLayoutParams();
params.height = (int) pixels;
someLayout.setLayoutParams(params);
where the expression: getResources().getDisplayMetrics()
gets the screen density/resolution
open a new command prompt and run the following command: dotnet --info
I was brought here for a reason not explicitly mentioned in the answers so far, so to save others the trouble:
The error also occurs if the function arguments have changed order - for the same reason as in the accepted answer: the positional arguments clash with the keyword arguments.
In my case it was because the argument order of the Pandas set_axis
function changed between 0.20 and 0.22:
0.20: DataFrame.set_axis(axis, labels)
0.22: DataFrame.set_axis(labels, axis=0, inplace=None)
Using the commonly found examples for set_axis results in this confusing error, since when you call:
df.set_axis(['a', 'b', 'c'], axis=1)
prior to 0.22, ['a', 'b', 'c']
is assigned to axis because it's the first argument, and then the positional argument provides "multiple values".
Download & Install install JDK
$ java -version
Set JAVA_HOME environment variable
$ open -t .zprofile
Or create . zprofile file
$
open -t .zprofile
export JAVA_HOME=$(/usr/libexec/java_home)
Save .zprofile and close the bash file & then write in the terminal for work perfectly.
$ source .zprofile
Setup test in terminal
$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk-13.0.1.jdk/Contents/Home
revalidate()
just request to layout the container, when you experienced simply call revalidate()
works, it could be caused by the updating of child components bounds triggers the repaint()
when their bounds are changed during the re-layout. In the case you mentioned, only component removed and no component bounds are changed, this case no repaint()
is "accidentally" triggered.
You should use return as in:
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (exit) {
return;
}
With AngularJS
:
angular.element('#Element')[0].focus();
I always use Ctrl+Shift+F5 out of habit, it should force a full-refresh including by-passing any http proxies you may be going through.
Inherit Activity Class instead of ListActivity you can resolve this problem.
public class ExampleActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlist);
}
}
There is a javascript plugin that adds this feature to bootstrap.
When rowlink.js
is included you can do:
<table data-link="row">
<tr><td><a href="foo.html">Foo</a></td><td>This is Foo</td></tr>
<tr><td><a href="bar.html">Bar</a></td><td>Bar is good</td></tr>
</table>
The table will be converted so that the whole row can be clicked instead of only the first column.
[Late to the party...]
Another way to do this without the overhead of an Ajax call or WebService handler is to load a special ASPX page after a given amount of time (i.e., prior to the session state time-out, which is typically 20 minutes):
// Client-side JavaScript
function pingServer() {
// Force the loading of a keep-alive ASPX page
var img = new Image(1, 1);
img.src = '/KeepAlive.aspx';
}
The KeepAlive.aspx
page is simply an empty page which does nothing but touch/refresh the Session
state:
// KeepAlive.aspx.cs
public partial class KeepSessionAlive: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Refresh the current user session
Session["refreshTime"] = DateTime.UtcNow;
}
}
This works by creating an img
(image) element and forcing the browser to load its contents from the KeepAlive.aspx
page. Loading that page causes the server to touch (update) the Session
object, extending the session's expiration sliding time window (typically by another 20 minutes). The actual web page contents are discarded by the browser.
An alternative, and perhaps cleaner, way to do this is to create a new iframe
element and load the KeepAlive.aspx
page into it. The iframe
element is hidden, such as by making it a child element of a hidden div
element somewhere on the page.
Activity on the page itself can be detected by intercepting mouse and keyboard actions for the entire page body:
// Called when activity is detected
function activityDetected(evt) {
...
}
// Watch for mouse or keyboard activity
function watchForActivity() {
var opts = { passive: true };
document.body.addEventListener('mousemove', activityDetected, opts);
document.body.addEventListener('keydown', activityDetected, opts);
}
I cannot take credit for this idea; see: https://www.codeproject.com/Articles/227382/Alert-Session-Time-out-in-ASP-Net.
Make the exception happen like this:
when(obj.someMethod()).thenThrow(new AnException());
Verify it has happened either by asserting that your test will throw such an exception:
@Test(expected = AnException.class)
Or by normal mock verification:
verify(obj).someMethod();
The latter option is required if your test is designed to prove intermediate code handles the exception (i.e. the exception won't be thrown from your test method).
I had this error in Visual Studio 2013, with an SSIS project. I set Project, Properties, Debugging, Run64BitRuntime = false and then the SSIS package ran. However, when I deployed the package to the server I had to set the value to true (Server is 64 bit Windows 2012 / Sql 2014 ).
I think the reasoning behind this is that Visual Studio is a 32 bit application.
I assume you're looking for this:
string[,] Tablero = new string[3,3];
The syntax for a jagged array is:
string[][] Tablero = new string[3][];
for (int ix = 0; ix < 3; ++ix) {
Tablero[ix] = new string[3];
}
As far as i know, writing multiple matches is logical AND operation; so what your rule means is if the destination port is "59100" AND "3000" then reject connection with tcp-reset; Workaround is using -mport option. Look out for the man page.
See, the best thing you can do is to just upload the image to the disk and save the URL in MongoDB. Rest when you retrieve the image again. Just specify the URL, and you will get an image. The code for uploading is as follows.
app.post('/upload', function(req, res) {
// Get the temporary location of the file
var tmp_path = req.files.thumbnail.path;
// Set where the file should actually exists - in this case it is in the "images" directory.
target_path = '/tmp/' + req.files.thumbnail.name;
// Move the file from the temporary location to the intended location
fs.rename(tmp_path, target_path, function(err) {
if (err)
throw err;
// Delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files.
fs.unlink(tmp_path, function() {
if (err)
throw err;
//
});
});
});
Now save the target path in your MongoDB database.
Again, while retrieving the image, just extract the URL from the MongoDB database, and use it on this method.
fs.readFile(target_path, "binary", function(error, file) {
if(error) {
res.writeHead(500, {"Content-Type": "text/plain"});
res.write(error + "\n");
res.end();
}
else {
res.writeHead(200, {"Content-Type": "image/png"});
res.write(file, "binary");
}
});
In addition to the PostgreSQL way (\d 'something' or \dt 'table' or \ds 'sequence' and so on)
The SQL standard way, as shown here:
select column_name, data_type, character_maximum_length, column_default, is_nullable
from INFORMATION_SCHEMA.COLUMNS where table_name = '<name of table>';
It's supported by many db engines.
Since python 3.6 you can use fstring :
>>> length = 1
>>> print(f'length = {length:03}')
length = 001
Try this:
package my_default;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) {
try {
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook();
// Get first/desired sheet from the workbook
XSSFSheet sheet = createSheet(workbook, "Sheet 1", false);
// XSSFSheet sheet = workbook.getSheetAt(1);//Don't use this line
// because you get Sheet index (1) is out of range (no sheets)
//Write some information in the cells or do what you want
XSSFRow row1 = sheet.createRow(0);
XSSFCell r1c2 = row1.createCell(0);
r1c2.setCellValue("NAME");
XSSFCell r1c3 = row1.createCell(1);
r1c3.setCellValue("AGE");
//Save excel to HDD Drive
File pathToFile = new File("D:\\test.xlsx");
if (!pathToFile.exists()) {
pathToFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(pathToFile);
workbook.write(fos);
fos.close();
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
private static XSSFSheet createSheet(XSSFWorkbook wb, String prefix, boolean isHidden) {
XSSFSheet sheet = null;
int count = 0;
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
String sName = wb.getSheetName(i);
if (sName.startsWith(prefix))
count++;
}
if (count > 0) {
sheet = wb.createSheet(prefix + count);
} else
sheet = wb.createSheet(prefix);
if (isHidden)
wb.setSheetHidden(wb.getNumberOfSheets() - 1, XSSFWorkbook.SHEET_STATE_VERY_HIDDEN);
return sheet;
}
}
This query should identify columns that are potential problems...
SELECT *
FROM [source].INFORMATION_SCHEMA.COLUMNS src
INNER JOIN [dest].INFORMATION_SCHEMA.COLUMNS dst
ON dst.COLUMN_NAME = src.COLUMN_NAME
WHERE dst.CHARACTER_MAXIMUM_LENGTH < src.CHARACTER_MAXIMUM_LENGTH
class Main {
public static void main(String args[]) throws Exception {
ApplicationContext ac = new
ClassPathXmlApplicationContext("context.xml", Main.class);
DataSource dataSource = (DataSource) ac.getBean("dataSource");
// DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String prasobhName =
jdbcTemplate.query(
"select first_name from customer where last_name like ?",
new PreparedStatementSetter() {
public void setValues(PreparedStatement preparedStatement) throws
SQLException {
preparedStatement.setString(1, "nair%");
}
},
new ResultSetExtractor<Long>() {
public Long extractData(ResultSet resultSet) throws SQLException,
DataAccessException {
if (resultSet.next()) {
return resultSet.getLong(1);
}
return null;
}
}
);
System.out.println(machaceksName);
}
}
You generally should not add an app.config
file to a class library project; it won't be used without some painful bending and twisting on your part. It doesn't hurt the library project at all - it just won't do anything at all.
Instead, you configure the application which is using your library; so the configuration information required would go there. Each application that might use your library likely will have different requirements, so this actually makes logical sense, too.
You can ignore the URL field and simply paste the viewstate into the Viewstate string box.
It does look like you have an old version; the serialisation methods changed in ASP.NET 2.0, so grab the 2.0 version
Take a look at Shell MegaPack control set. It provides Windows Explorer like folder/file browsing with most of the features and functionality like context menus, renaming, drag-drop, icons, overlay icons, thumbnails, etc
You just need to convert your dates to UNIX_TIMESTAMP
. You can write your query like this:
SELECT *
FROM eventList
WHERE
date BETWEEN
UNIX_TIMESTAMP('2013/03/26')
AND
UNIX_TIMESTAMP('2013/03/27 23:59:59');
When you don't specify the time, MySQL will assume 00:00:00
as the time for the given date.
Based on the @MixerOID response, here is my final solution as a component (maybe I create a library). I also support FormArray's:
import {Component, ElementRef, Input, OnInit} from '@angular/core';
import {FormArray, FormGroup, ValidationErrors} from '@angular/forms';
import {TranslateService} from '@ngx-translate/core';
interface AllValidationErrors {
controlName: string;
errorName: string;
errorValue: any;
}
@Component({
selector: 'app-form-errors',
templateUrl: './form-errors.component.html',
styleUrls: ['./form-errors.component.scss']
})
export class FormErrorsComponent implements OnInit {
@Input() form: FormGroup;
@Input() formRef: ElementRef;
@Input() messages: Array<any>;
private errors: AllValidationErrors[];
constructor(
private translateService: TranslateService
) {
this.errors = [];
this.messages = [];
}
ngOnInit() {
this.form.valueChanges.subscribe(() => {
this.errors = [];
this.calculateErrors(this.form);
});
this.calculateErrors(this.form);
}
calculateErrors(form: FormGroup | FormArray) {
Object.keys(form.controls).forEach(field => {
const control = form.get(field);
if (control instanceof FormGroup || control instanceof FormArray) {
this.errors = this.errors.concat(this.calculateErrors(control));
return;
}
const controlErrors: ValidationErrors = control.errors;
if (controlErrors !== null) {
Object.keys(controlErrors).forEach(keyError => {
this.errors.push({
controlName: field,
errorName: keyError,
errorValue: controlErrors[keyError]
});
});
}
});
// This removes duplicates
this.errors = this.errors.filter((error, index, self) => self.findIndex(t => {
return t.controlName === error.controlName && t.errorName === error.errorName;
}) === index);
return this.errors;
}
getErrorMessage(error) {
switch (error.errorName) {
case 'required':
return this.translateService.instant('mustFill') + ' ' + this.messages[error.controlName];
default:
return 'unknown error ' + error.errorName;
}
}
}
And the HTML:
<div *ngIf="formRef.submitted">
<div *ngFor="let error of errors" class="text-danger">
{{getErrorMessage(error)}}
</div>
</div>
Usage:
<app-form-errors [form]="languageForm"
[formRef]="formRef"
[messages]="{language: 'Language'}">
</app-form-errors>
I ran into this problem on Ubuntu 20 with Python Selenium after first downloading the chromedriver separately and then using sudo apt install chromium-browser
Even though they were the same version this kept happening.
My fix was to use the provided chrome driver that came with the repo package located at
/snap/bin/chromium.chromedriver
driver = webdriver.Chrome(chrome_options=options, executable_path='/snap/bin/chromium.chromedriver')
Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories
, and it should work.
The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.
If you use the html approach:
don't add blank lines
Like this:
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
the markup will break.
Remove blank lines:
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
Or if you don't like branching, just negate the two parameters and add 180° to the answer.
(Adding 180° to the return value puts it nicely in the 0-360 range, but flips the angle. Negating both input parameters flips it back.)
The corrected code is
import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
counts = dict()
for line in fhand:
words = line.decode().split()
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
running the code above produces
{'Who': 1, 'is': 1, 'already': 1, 'sick': 1, 'and': 1, 'pale': 1, 'with': 1, 'grief': 1}
Try this:
$("#autoship_option option[selected]").removeAttr("selected");
# -*- mode: python -*-
block_cipher = None
a = Analysis(['SCRIPT.py'],
pathex=[
'folder path',
'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_50c6cb8431e7428f',
'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_c4f50889467f081d'
],
binaries=[(''C:\\Users\\chromedriver.exe'')],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='NAME OF YOUR EXE',
debug=False,
strip=False,
upx=True,
runtime_tmpdir=None,
console=True )
If you are trying to delete a column which is a FOREIGN KEY, you must find the correct name which is not the column name. Eg: If I am trying to delete the server field in the Alarms table which is a foreign key to the servers table.
SHOW CREATE TABLE alarm;
Look for the CONSTRAINT `server_id_refs_id_34554433` FORIEGN KEY (`server_id`) REFERENCES `server` (`id`)
line.ALTER TABLE `alarm` DROP FOREIGN KEY `server_id_refs_id_34554433`;
ALTER TABLE `alarm` DROP `server_id`
This will delete the foreign key server from the Alarms table.
in my case, datas
is an objects of Array for more information please Click Here
<% for(let [index,data] of datas.entries() || []){ %>
Index : <%=index%>
Data : <%=data%>
<%} %>
This might be a bug of the recent anaconda. What works for me:
step1: vim /anaconda/bin/activate
, it shows:
#!/bin/sh
_CONDA_ROOT="/anaconda"
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
\. "$_CONDA_ROOT/etc/profile.d/conda.sh" || return $?
conda activate "$@"
step2: comment out the last line: # conda activate "$@"
Building on the answer of JMax, use this formula for the dynamic named range to make the solution work for multiple rows:
=OFFSET(Sheet2!$A$1,MATCH(INDIRECT("Sheet1!"&ADDRESS(ROW(),COLUMN(),4))&"*",Sheet2!$A$1:$A$300,0)-1,0,COUNTA(Sheet2!$A:$A))
This will scroll to the very top:
$(window).animate({scrollTop: 0});
This will scroll to the very bottom:
$(window).animate({scrollTop: $(document).height() + $(window).height()});
.. change window to your desired container id or class if necessary (in quotes).
From iOS 7 there is an API and you can get (and set) the tint color with:
self.view.tintColor
Or if you need the CGColor:
self.view.tintColor.CGColor
have you tried doing it without the JSON object and just passed two basicnamevaluepairs? also, it might have something to do with your serversettings
Update: this is a piece of code I use:
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(connection);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("HTTP", "HTTP: OK");
} catch (Exception e) {
Log.e("HTTP", "Error in http connection " + e.toString());
}
I had the same error on a page, and I added these lines:
<!--[if lte IE 9]>
<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.3/jquery.xdomainrequest.min.js'></script>
<![endif]-->
and it finally works for me ;) no more error in IE9.
For whatever reason, the gradle script is not picking up the value of ANDROID_HOME from the environment. Try specifying it on the command line explicitly
$ ANDROID_HOME=<sdk location> ./gradlew
I think you are a bit confused on the purpose of custom data attributes. From the w3 spec
Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.
By itself an attribute of data-toggle=value
is basically a key-value pair, in which the key is "data-toggle" and the value is "value".
In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used.
Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle".
Button Toggle
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
}
if (changed) this.$element.toggleClass('active')
}
The context that the code provides shows that Bootstrap is using the data-toggle
attribute as a custom query selector to process the particular element.
From what I see these are the data-toggle options:
You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle
attribute toggles the element to active or not.
Try this:
public class Team
{
public int TeamId { get; set;}
public string Name { get; set; }
public virtual ICollection<Match> HomeMatches { get; set; }
public virtual ICollection<Match> AwayMatches { get; set; }
}
public class Match
{
public int MatchId { get; set; }
public int HomeTeamId { get; set; }
public int GuestTeamId { get; set; }
public float HomePoints { get; set; }
public float GuestPoints { get; set; }
public DateTime Date { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team GuestTeam { get; set; }
}
public class Context : DbContext
{
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Match>()
.HasRequired(m => m.HomeTeam)
.WithMany(t => t.HomeMatches)
.HasForeignKey(m => m.HomeTeamId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Match>()
.HasRequired(m => m.GuestTeam)
.WithMany(t => t.AwayMatches)
.HasForeignKey(m => m.GuestTeamId)
.WillCascadeOnDelete(false);
}
}
Primary keys are mapped by default convention. Team must have two collection of matches. You can't have single collection referenced by two FKs. Match is mapped without cascading delete because it doesn't work in these self referencing many-to-many.
I was having this issue, then resolving the conflict and commiting, and doing git stash pop
again was restoring the same stash again (causing the same conflict :-( ).
What I had to do (WARNING: back up your stash first) is git stash drop
to get rid of it.
In many applications, like MsOffice (until version 2000 or 2002), the maximum number of characters per cell was 255. Moving data from programs able of handling more than 255 characters per field to/from those applications was a nightmare. Currently, the limit is less and less hindering.
use window.open("file2.html");
to open on new window,
or use window.location.href = "file2.html"
to open on same window.
vickramds's comment above, referring to http://torulflundgren.blogspot.com.au/2010/03/cannot-obtain-value-of-local-or.html , did it for me. I checked everything - deleted all the dll, pdb files from local bin folders, Clean, Rebuild, cleared all folders of Temporary ASP.NET Files, ensured TRACE/DEBUG flags were set, checked the DLL paths, etc.
To put it down so it isn't lost, for the affected project(s):
Project Properties --> Build --> Advanced --> Debug Info: Full.
You want to check that you have the Debug configuration selected before you do this, unless of course, you intended otherwise.
I would like to suggest to use a single RecyclerView
and populate your list items dynamically. I've added a github project to describe how this can be done. You might have a look. While the other solutions will work just fine, I would like to suggest, this is a much faster and efficient way of showing multiple lists in a RecyclerView
.
The idea is to add logic in your onCreateViewHolder
and onBindViewHolder
method so that you can inflate proper view for the exact positions in your RecyclerView
.
I've added a sample project along with that wiki too. You might clone and check what it does. For convenience, I am posting the adapter that I have used.
public class DynamicListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int FOOTER_VIEW = 1;
private static final int FIRST_LIST_ITEM_VIEW = 2;
private static final int FIRST_LIST_HEADER_VIEW = 3;
private static final int SECOND_LIST_ITEM_VIEW = 4;
private static final int SECOND_LIST_HEADER_VIEW = 5;
private ArrayList<ListObject> firstList = new ArrayList<ListObject>();
private ArrayList<ListObject> secondList = new ArrayList<ListObject>();
public DynamicListAdapter() {
}
public void setFirstList(ArrayList<ListObject> firstList) {
this.firstList = firstList;
}
public void setSecondList(ArrayList<ListObject> secondList) {
this.secondList = secondList;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// List items of first list
private TextView mTextDescription1;
private TextView mListItemTitle1;
// List items of second list
private TextView mTextDescription2;
private TextView mListItemTitle2;
// Element of footer view
private TextView footerTextView;
public ViewHolder(final View itemView) {
super(itemView);
// Get the view of the elements of first list
mTextDescription1 = (TextView) itemView.findViewById(R.id.description1);
mListItemTitle1 = (TextView) itemView.findViewById(R.id.title1);
// Get the view of the elements of second list
mTextDescription2 = (TextView) itemView.findViewById(R.id.description2);
mListItemTitle2 = (TextView) itemView.findViewById(R.id.title2);
// Get the view of the footer elements
footerTextView = (TextView) itemView.findViewById(R.id.footer);
}
public void bindViewSecondList(int pos) {
if (firstList == null) pos = pos - 1;
else {
if (firstList.size() == 0) pos = pos - 1;
else pos = pos - firstList.size() - 2;
}
final String description = secondList.get(pos).getDescription();
final String title = secondList.get(pos).getTitle();
mTextDescription2.setText(description);
mListItemTitle2.setText(title);
}
public void bindViewFirstList(int pos) {
// Decrease pos by 1 as there is a header view now.
pos = pos - 1;
final String description = firstList.get(pos).getDescription();
final String title = firstList.get(pos).getTitle();
mTextDescription1.setText(description);
mListItemTitle1.setText(title);
}
public void bindViewFooter(int pos) {
footerTextView.setText("This is footer");
}
}
public class FooterViewHolder extends ViewHolder {
public FooterViewHolder(View itemView) {
super(itemView);
}
}
private class FirstListHeaderViewHolder extends ViewHolder {
public FirstListHeaderViewHolder(View itemView) {
super(itemView);
}
}
private class FirstListItemViewHolder extends ViewHolder {
public FirstListItemViewHolder(View itemView) {
super(itemView);
}
}
private class SecondListHeaderViewHolder extends ViewHolder {
public SecondListHeaderViewHolder(View itemView) {
super(itemView);
}
}
private class SecondListItemViewHolder extends ViewHolder {
public SecondListItemViewHolder(View itemView) {
super(itemView);
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
if (viewType == FOOTER_VIEW) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_footer, parent, false);
FooterViewHolder vh = new FooterViewHolder(v);
return vh;
} else if (viewType == FIRST_LIST_ITEM_VIEW) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_first_list, parent, false);
FirstListItemViewHolder vh = new FirstListItemViewHolder(v);
return vh;
} else if (viewType == FIRST_LIST_HEADER_VIEW) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_first_list_header, parent, false);
FirstListHeaderViewHolder vh = new FirstListHeaderViewHolder(v);
return vh;
} else if (viewType == SECOND_LIST_HEADER_VIEW) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_second_list_header, parent, false);
SecondListHeaderViewHolder vh = new SecondListHeaderViewHolder(v);
return vh;
} else {
// SECOND_LIST_ITEM_VIEW
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_second_list, parent, false);
SecondListItemViewHolder vh = new SecondListItemViewHolder(v);
return vh;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try {
if (holder instanceof SecondListItemViewHolder) {
SecondListItemViewHolder vh = (SecondListItemViewHolder) holder;
vh.bindViewSecondList(position);
} else if (holder instanceof FirstListHeaderViewHolder) {
FirstListHeaderViewHolder vh = (FirstListHeaderViewHolder) holder;
} else if (holder instanceof FirstListItemViewHolder) {
FirstListItemViewHolder vh = (FirstListItemViewHolder) holder;
vh.bindViewFirstList(position);
} else if (holder instanceof SecondListHeaderViewHolder) {
SecondListHeaderViewHolder vh = (SecondListHeaderViewHolder) holder;
} else if (holder instanceof FooterViewHolder) {
FooterViewHolder vh = (FooterViewHolder) holder;
vh.bindViewFooter(position);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
int firstListSize = 0;
int secondListSize = 0;
if (secondList == null && firstList == null) return 0;
if (secondList != null)
secondListSize = secondList.size();
if (firstList != null)
firstListSize = firstList.size();
if (secondListSize > 0 && firstListSize > 0)
return 1 + firstListSize + 1 + secondListSize + 1; // first list header, first list size, second list header , second list size, footer
else if (secondListSize > 0 && firstListSize == 0)
return 1 + secondListSize + 1; // second list header, second list size, footer
else if (secondListSize == 0 && firstListSize > 0)
return 1 + firstListSize; // first list header , first list size
else return 0;
}
@Override
public int getItemViewType(int position) {
int firstListSize = 0;
int secondListSize = 0;
if (secondList == null && firstList == null)
return super.getItemViewType(position);
if (secondList != null)
secondListSize = secondList.size();
if (firstList != null)
firstListSize = firstList.size();
if (secondListSize > 0 && firstListSize > 0) {
if (position == 0) return FIRST_LIST_HEADER_VIEW;
else if (position == firstListSize + 1)
return SECOND_LIST_HEADER_VIEW;
else if (position == secondListSize + 1 + firstListSize + 1)
return FOOTER_VIEW;
else if (position > firstListSize + 1)
return SECOND_LIST_ITEM_VIEW;
else return FIRST_LIST_ITEM_VIEW;
} else if (secondListSize > 0 && firstListSize == 0) {
if (position == 0) return SECOND_LIST_HEADER_VIEW;
else if (position == secondListSize + 1) return FOOTER_VIEW;
else return SECOND_LIST_ITEM_VIEW;
} else if (secondListSize == 0 && firstListSize > 0) {
if (position == 0) return FIRST_LIST_HEADER_VIEW;
else return FIRST_LIST_ITEM_VIEW;
}
return super.getItemViewType(position);
}
}
There is another way of keeping your items in a single ArrayList
of objects so that you can set an attribute tagging the items to indicate which item is from first list and which one belongs to second list. Then pass that ArrayList
into your RecyclerView
and then implement the logic inside adapter to populate them dynamically.
Hope that helps.
One of the most well known solutions is a variation of your solution number 3 that uses a pseudo element instead of a non-semantic html element.
It goes something like this...
.cf:after {
content: " ";
display: block;
visibility: hidden;
height: 0;
clear: both;
}
You place that in your stylesheet, and all you need is to add the class 'cf' to the element containing the floats.
What I use is another variation which comes from Nicolas Gallagher.
It does the same thing, but it's shorter, looks neater, and maybe used to accomplish another thing that's pretty useful - preventing the child elements' margins from collapsing with it's parents' (but for that you do need something else - read more about it here http://nicolasgallagher.com/micro-clearfix-hack/ ).
.cf:after {
content: " ";
display: table;
clear: float;
}
A POD is a type (including classes) where the C++ compiler guarantees that there will be no "magic" going on in the structure: for example hidden pointers to vtables, offsets that get applied to the address when it is cast to other types (at least if the target's POD too), constructors, or destructors. Roughly speaking, a type is a POD when the only things in it are built-in types and combinations of them. The result is something that "acts like" a C type.
int
, char
, wchar_t
, bool
, float
, double
are PODs, as are long/short
and signed/unsigned
versions of them.enums
are PODsconst
or volatile
POD is a POD.class
, struct
or union
of PODs is a POD provided that all non-static data members are public
, and it has no base class and no constructors, destructors, or virtual methods. Static members don't stop something being a POD under this rule. This rule has changed in C++11 and certain private members are allowed: Can a class with all private members be a POD class?3.9(10): "Arithmetic types (3.9.1), enumeration types, pointer types, and pointer to member types (3.9.2) and cv-qualified versions of these types (3.9.3) are collectively caller scalar types. Scalar types, POD-struct types, POD-union types (clause 9), arrays of such types and cv-qualified versions of these types (3.9.3) are collectively called POD types"
9(4): "A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-define copy operator and no user-defined destructor. Similarly a POD-union is an aggregate union that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-define copy operator and no user-defined destructor.
8.5.1(1): "An aggregate is an array or class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10) and no virtual functions (10.3)."
The most common reason I've had for a "broken pipe" is that one machine (of a pair communicating via socket) has shut down its end of the socket before communication was complete. About half of those were because the program communicating on that socket had terminated.
If the program sending bytes sends them out and immediately shuts down the socket or terminates itself, it is possible for the socket to cease functioning before the bytes have been transmitted and read.
Try putting pauses anywhere you are shutting down the socket and before you allow the program to terminate to see if that helps.
FYI: "pipe" and "socket" are terms that get used interchangeably sometimes.
I know this is an old question, but it took me some time to sort this out given the sparse Angular documentation. The RouteProvider and routeParams is the way to go. The route wires up the URL to your Controller/View and the routeParams can be passed into the controller.
Check out the Angular seed project. Within the app.js you'll find an example for the route provider. To use params simply append them like this:
$routeProvider.when('/view1/:param1/:param2', {
templateUrl: 'partials/partial1.html',
controller: 'MyCtrl1'
});
Then in your controller inject $routeParams:
.controller('MyCtrl1', ['$scope','$routeParams', function($scope, $routeParams) {
var param1 = $routeParams.param1;
var param2 = $routeParams.param2;
...
}]);
With this approach you can use params with a url such as: "http://www.example.com/view1/param1/param2"
This question is similar to How do I limit the number of rows returned by an Oracle query after ordering?.
It talks about how to implement a MySQL limit on an oracle database which judging by your tags and post is what you are using.
The relevant section is:
select *
from
( select *
from emp
order by sal desc )
where ROWNUM <= 5;
I already said that I was new to exec()
function. After doing some more digging, I came upon 2>&1
which needs to be added at the end of command in exec()
.
Thanks @mattosmat
for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.
So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.
For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.
exec('some_command 2>&1', $output);
print_r($output); // to see the response to your command
Thanks for all the help guys, I appreciate it ;)
I found a solution for how to set a global variable in a mailinglist posting via assign:
a <- "old"
test <- function () {
assign("a", "new", envir = .GlobalEnv)
}
test()
a # display the new value
Use saved_change_to_published?
:
class SomeModel < ActiveRecord::Base
after_update :send_notification_after_change
def send_notification_after_change
Notification.send(…) if (saved_change_to_published? && self.published == true)
end
end
Or if you prefer, saved_change_to_attribute?(:published)
.
Warning
This approach works through Rails 5.1 (but is deprecated in 5.1 and has breaking changes in 5.2). You can read about the change in this pull request.
In your after_update
filter on the model you can use _changed?
accessor. So for example:
class SomeModel < ActiveRecord::Base
after_update :send_notification_after_change
def send_notification_after_change
Notification.send(...) if (self.published_changed? && self.published == true)
end
end
It just works.
You are using Python 2 for which the input()
function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError
exception.
To fix the problem, in Python 2, you can use raw_input()
. This returns the string entered by the user and does not attempt to evaluate it.
Note that if you were using Python 3, input()
behaves the same as raw_input()
does in Python 2.
My "DerivedData" with Xcode 10.2 and Mojave was here:
MacHD/Users/[MyUser]/Library/Developer/Xcode
They have a very good answer here: https://stackoverflow.com/a/32455275/165865
Just run below images:
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock nate/dockviz images -t
An example of the mathematically only calculation, without any Date
functions.
const date = new Date();_x000D_
const ts = +date;_x000D_
_x000D_
const mondayTS = ts - ts % (60 * 60 * 24 * (7-4) * 1000);_x000D_
_x000D_
const monday = new Date(mondayTS);_x000D_
console.log(monday.toISOString(), 'Day:', monday.getDay());
_x000D_
const formatTS = v => new Date(v).toISOString();_x000D_
const adjust = (v, d = 1) => v - v % (d * 1000);_x000D_
_x000D_
const d = new Date('2020-04-22T21:48:17.468Z');_x000D_
const ts = +d; // 1587592097468_x000D_
_x000D_
const test = v => console.log(formatTS(adjust(ts, v)));_x000D_
_x000D_
test(); // 2020-04-22T21:48:17.000Z_x000D_
test(60); // 2020-04-22T21:48:00.000Z_x000D_
test(60 * 60); // 2020-04-22T21:00:00.000Z_x000D_
test(60 * 60 * 24); // 2020-04-22T00:00:00.000Z_x000D_
test(60 * 60 * 24 * (7-4)); // 2020-04-20T00:00:00.000Z, monday_x000D_
_x000D_
// So, what does `(7-4)` mean?_x000D_
// 7 - days number in the week_x000D_
// 4 - shifting for the weekday number of the first second of the 1970 year, the first time stamp second._x000D_
// new Date(0) ---> 1970-01-01T00:00:00.000Z_x000D_
// new Date(0).getDay() ---> 4
_x000D_
Try the following command iptables-save
.
You can decode it to str with receive.decode('utf_8')
.
Below is the code which I'm using
//This URL not exist, it's only an example.
string url = "http://myBox.s3.amazonaws.com/";
//Instantiate new CustomWebRequest class
CustomWebRequest wr = new CustomWebRequest(url);
//Set values for parameters
wr.ParamsCollection.Add(new ParamsStruct("key", "${filename}"));
wr.ParamsCollection.Add(new ParamsStruct("acl", "public-read"));
wr.ParamsCollection.Add(new ParamsStruct("success_action_redirect", "http://www.yahoo.com"));
wr.ParamsCollection.Add(new ParamsStruct("x-amz-meta-uuid", "14365123651274"));
wr.ParamsCollection.Add(new ParamsStruct("x-amz-meta-tag", ""));
wr.ParamsCollection.Add(new ParamsStruct("AWSAccessKeyId", "zzzz"));
wr.ParamsCollection.Add(new ParamsStruct("Policy", "adsfadsf"));
wr.ParamsCollection.Add(new ParamsStruct("Signature", "hH6lK6cA="));
//For file type, send the inputstream of selected file
StreamReader sr = new StreamReader(@"file.txt");
wr.ParamsCollection.Add(new ParamsStruct("file", sr, ParamsStruct.ParamType.File, "file.txt"));
wr.PostData();
from the following link I've downloaded the same code http://www.codeproject.com/KB/cs/multipart_request_C_.aspx
Any Help
Officially it's Ctrl+F11 & Ctrl+F12 or KEYPAD 7 & KEYPAD 9.
In practise it's a bit quirky.
Specifically it's Left Ctrl+F11 and Left Ctrl+F12 to switch to previous orientation and next orientation respectively.
You have to release Ctrl before you can rotate again.
KEYPAD 7 and KEYPAD 9 only work with Num Lock OFF (so they're acting as Home & PageUp rather than 7 & 9).
The only orientations are vertically upright and rotated one quarter-turn anti-clockwise.
Maybe a bit too much info for such a simple question, but it drove me half-mad finding this out.
Note: This was tested on Android SDK R16 and a very old keyboard, modern keyboards may behave differently.
You could do something like:
using (TextReader rdr = OpenYourFile()) {
string line;
while ((line = rdr.ReadLine()) != null) {
string[] fields = line.Split('\t'); // THIS LINE DOES THE MAGIC
int theInt = Convert.ToInt32(fields[1]);
}
}
The reason you didn't find relevant result when searching for 'formatting' is that the operation you are performing is called 'parsing'.
if you're using React I found 'react-moment'
library more easy to handle for Front-End related tasks, just import <Moment>
component and add unix
prop:
import Moment from 'react-moment'
// get date variable
const {date} = this.props
<Moment unix>{date}</Moment>