You must not change the UI offside the main thread! UIKit is not thread safe, so that above problem and also some other weird problems will arise if you do that. The app can even crash.
So, to do the UIKit operations, you need to define block and let it be executed on the main queue: such as,
NSOperationQueue.mainQueue().addOperationWithBlock {
}
I hate to point out the obvious, but System.IO.FileNotFoundException means the program did not find the file you specified. So what you need to do is check what file your code is looking for in production.
To see what file your program is looking for in production (look at the FileName property of the exception), try these techniques:
Then look at the file system on the machine and see if the file exists. Most likely the case is that it doesn't exist.
In Swift 3, you can create an extension to do it:
extension NSView {
func setBackgroundColor(_ color: NSColor) {
wantsLayer = true
layer?.backgroundColor = color.cgColor
}
}
// how to use
btn.setBackgroundColor(NSColor.gray)
Marshal.Copy works but is rather slow. Faster is to copy the bytes in a for loop. Even faster is to cast the byte array to a ulong array, copy as much ulong as fits in the byte array, then copy the possible remaining 7 bytes (the trail that is not 8 bytes aligned). Fastest is to pin the byte array in a fixed statement as proposed above in Tyalis' answer.
This is a stone age question and yet still very relevant. Specially now that Android team is pushing more towards adhering to single activity models, communication between the fragments becomes all the more important. LiveData and Interfaces are perfectly fine ways to tackle this issue. But now Google has finally addressed this problem and tried to bring a much simpler solution using FragmentManager. Here's how it can be done in Kotlin.
In receiver fragment add a listener:
setFragmentResultListener(
"data_request_key",
lifecycleOwner,
FragmentResultListener { requestKey: String, bundle: Bundle ->
// unpack the bundle and use data
val frag1Str = bundle.getString("frag1_data_key")
})
In sender fragment(frag1):
setFragmentResult(
"data_request_key",
bundleOf("frag1_data_key" to value)
)
Remember this functionality is only available in fragment-ktx version 1.3.0-alpha04 and up.
Credits and further reading:
git reset filename.txt
If you have a modification in filename.txt , you added it to stage by mistake and you want to remove the file from staging but you don't want to lose the changes.
I ran into this problem today and this was the trick I did, which worked for me:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("DAOMANAGER");
EntityManagerem = emf.createEntityManager();
org.hibernate.Session session = ((EntityManagerImpl) em).getSession();
java.sql.Connection connectionObj = session.connection();
Though not the best way but does the job.
I had the same problem, and didn´t want to rewrite the code, so I wrote a function to modify the code and create the inline declarated events:
function compile(qSel){
var matches = [];
var match = null;
var c = 0;
var html = $(qSel).html();
var pattern = /(<(.*?)on([a-zA-Z]+)\s*=\s*('|")(.*)('|")(.*?))(>)/mg;
while (match = pattern.exec(html)) {
var arr = [];
for (i in match) {
if (!isNaN(i)) {
arr.push(match[i]);
}
}
matches.push(arr);
}
var items_with_events = [];
var compiledHtml = html;
for ( var i in matches ){
var item_with_event = {
custom_id : "my_app_identifier_"+i,
code : matches[i][5],
on : matches[i][3],
};
items_with_events.push(item_with_event);
compiledHtml = compiledHtml.replace(/(<(.*?)on([a-zA-Z]+)\s*=\s*('|")(.*)('|")(.*?))(>)/m, "<$2 custom_id='"+item_with_event.custom_id+"' $7 $8");
}
$(qSel).html(compiledHtml);
for ( var i in items_with_events ){
$("[custom_id='"+items_with_events[i].custom_id+"']").bind(items_with_events[i].on, function(){
eval(items_with_events[i].code);
});
}
}
$(document).ready(function(){
compile('#content');
})
This should remove all inline events from the selected node, and recreate them with jquery instead.
The answers above, are now antiquated due to new pipeline syntax. Below prints out the environment variables.
script {
sh 'env > env.txt'
String[] envs = readFile('env.txt').split("\r?\n")
for(String vars: envs){
println(vars)
}
}
You can just create a folder ProgramFiles at local D or local C to install those apps that can be install to a folder name which has a SPACES / Characters on it.
Using /proc/tty/drivers only indicates which tty drivers are loaded. If you're looking for a list of the serial ports check out /dev/serial, it will have two subdirectories: by-id and by-path.
EX:
# find . -type l
./by-path/usb-0:1.1:1.0-port0
./by-id/usb-Prolific_Technology_Inc._USB-Serial_Controller-if00-port0
Thanks to this post: https://superuser.com/questions/131044/how-do-i-know-which-dev-ttys-is-my-serial-port
iterate through the array and check its name value.
An Iterable
is a simple representation of a series of elements that can be iterated over. It does not have any iteration state such as a "current element". Instead, it has one method that produces an Iterator
.
An Iterator
is the object with iteration state. It lets you check if it has more elements using hasNext()
and move to the next element (if any) using next()
.
Typically, an Iterable
should be able to produce any number of valid Iterator
s.
If the content is not too large, you can also use
SELECT CAST ( <blobfield> AS RAW( <maxFieldLength> ) ) FROM <table>;
or
SELECT DUMP ( CAST ( <blobfield> AS RAW( <maxFieldLength> ) ) ) FROM <table>;
This will show you the HEX values.
I had this problem even after setting the config properly. git config
My scenario was issuing git command through supervisor (in Linux). On further debugging, supervisor was not reading the git config from home folder. Hence, I had to set the environment HOME variable in the supervisor config so that it can locate the git config correctly. It's strange that supervisor was not able to locate the git config just from the username configured in supervisor's config (/etc/supervisor/conf.d).
you may also want to encode and decode to/from base64
function uncompress(str:String):ByteArray {
import mx.utils.Base64Decoder;
var dec:Base64Decoder = new Base64Decoder();
dec.decode(str);
var newByteArr:ByteArray=dec.toByteArray();
return newByteArr;
}
// Compress a ByteArray into a Base64 String.
function compress(bytes:ByteArray):String {
import mx.utils.Base64Decoder; //Transform String in a ByteArray.
import mx.utils.Base64Encoder; //Transform ByteArray in a readable string.
var enc:Base64Encoder = new Base64Encoder();
enc.encodeBytes(bytes);
return enc.drain().split("\n").join("");
}
If I remember rightly, then adding an unload() event means that page cannot be cached (in forward/backward cache) - because it's state changes/may change when user navigates away. So - it is not safe to restore the last-second state of the page when returning to it by navigating through history object.
Your syntax and logic are incorrect in a number of ways. You need to create an index variable and use it to access the array's elements, like so:
int i = 0; // Create a separate integer to serve as your array indexer.
while(i < 10) { // The indexer needs to be less than 10, not A itself.
sum += A[i]; // either sum = sum + ... or sum += ..., but not both
i++; // You need to increment the index at the end of the loop.
}
The above example uses a while
loop, since that's the approach you took. A more appropriate construct would be a for
loop, as in Bogdan's answer.
After many months, I returned to develop an AngularJS (1.6.4) app, for which I chose Chrome (PC) and Safari (MAC) for testing during development. This code presented this Error: $injector:modulerr Module Error on IE 11.0.9600 (Windows 7, 32-bit).
Upon investigation, it became clear that error was due to forEach loop being used, just replaced all the forEach loops with normal for loops for things to work as-is...
It was basically an IE11 issue (answered here) rather than an AngularJS issue, but I want to put this reply here because the exception raised was an AngularJS exception. Hope it would help some of us out there.
similarly. don't use lambda functions... just replace ()=>{...} with good ol' function(){...}
I haven't seen this done before, but this is how it was done for emulating IE 8/7 when using IE 9:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">
If not, then try this one:
<meta http-equiv="X-UA-Compatible" content="IE=9">
Add those to your header with the other meta tags. This should force IE10 to render as IE9.
Another option you could do (assuming you are using PHP) is add this to your .htaccess
file:
Header set X-UA-Compatible "IE=9"
This will perform the action universally, rather than having to worry about adding the meta tag to all of your headers.
Maybe this could be a little older article. but must of the above answers don´t help me as I need. Then I wrote a little snippet for that.
This accepts any XML that hast at least 3 levels (Like this sample):
<XmlData>
<XmlRow>
<XmlField1>Data 1</XmlField1>
<XmlField2>Data 2</XmlField2>
<XmlField3>Data 3</XmlField3>
.......
</XmlRow>
</XmlData>
public static class XmlParser
{
/// <summary>
/// Converts XML string to DataTable
/// </summary>
/// <param name="Name">DataTable name</param>
/// <param name="XMLString">XML string</param>
/// <returns></returns>
public static DataTable BuildDataTableFromXml(string Name, string XMLString)
{
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(XMLString));
DataTable Dt = new DataTable(Name);
try
{
XmlNode NodoEstructura = doc.FirstChild.FirstChild;
// Table structure (columns definition)
foreach (XmlNode columna in NodoEstructura.ChildNodes)
{
Dt.Columns.Add(columna.Name, typeof(String));
}
XmlNode Filas = doc.FirstChild;
// Data Rows
foreach (XmlNode Fila in Filas.ChildNodes)
{
List<string> Valores = new List<string>();
foreach (XmlNode Columna in Fila.ChildNodes)
{
Valores.Add(Columna.InnerText);
}
Dt.Rows.Add(Valores.ToArray());
}
} catch(Exception)
{
}
return Dt;
}
}
This solve my problem
You're population is from the server-side. Using the registerclientscript will put the script at the beginning of the form.. you'll want to use RegisterStartupScript(Block) to have the script placed at the end of the page in question.
The former tries to run the script before the text area exists in the dom, the latter will run the script after that element in the page is created.
Here is simple example. you can use it like
wget -q -O - http://example.com/backup >/dev/null 2>&1
and in start you can add your option like (*****). Its up to your system requirements either you want to run it every minute or hours etc.
Try this
@Entity
@Table(name="tblperson")
public class Person {
public int id;
public OtherInfo otherInfo;
@Id //Here Id is autogenerated
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@OneToOne(cascade = CascadeType.ALL,targetEntity=OtherInfo.class)
@JoinColumn(name="otherInfo_id") //there should be a column otherInfo_id in Person
public OtherInfo getOtherInfo() {
return otherInfo;
}
public void setOtherInfo(OtherInfo otherInfo) {
this.otherInfo= otherInfo;
}
rest of attributes ...
}
@Entity
@Table(name="tblotherInfo")
public class OtherInfo {
private int id;
private Person person;
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@OneToOne(mappedBy="OtherInfo",targetEntity=Person.class)
public College getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
rest of attributes ...
}
To forget directory recursively add /*/*
to the path:
git update-index --assume-unchanged wordpress/wp-content/uploads/*/*
Using git rm --cached
is not good for collaboration. More details here: How to stop tracking and ignore changes to a file in Git?
Some times above solutions do not work, then you can try below:
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',true));
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',false));
Another way you can try is:
jQuery("input:radio[name=yourElementName]:nth(0)").attr('checked',true);
I think this is the clearest way:
require 'open-uri'
File.write 'image.png', open('http://example.com/image.png').read
You can use strip() or split() to control the spaces values as in the following:
words = " first second "
# Remove end spaces
def remove_end_spaces(string):
return "".join(string.rstrip())
# Remove the first and end spaces
def remove_first_end_spaces(string):
return "".join(string.rstrip().lstrip())
# Remove all spaces
def remove_all_spaces(string):
return "".join(string.split())
# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
I assume your XML response looks like this:
var xml = @"<names>
<name>
foo
</name>
<name>
bar
</name>
</names>";
The best way to process XML is to use an XML parser, such as LINQ to XML:
var doc = XDocument.Parse(xml);
var containsFoo = doc.Root
.Elements("name")
.Any(e => ((string)e).Trim() == "foo");
toString() is a debug info string. The default implementation returns the class name and the system identity hash. Collections return all elements but arrays not.
Also be aware of NullPointerException
creating the log!
In this case a Arrays.toString()
may help:
Object temp = data.getParameterValue("request");
String log = temp == null ? "null" : (temp.getClass().isArray() ? Arrays.toString((Object[])temp) : temp.toString());
log.info("end " + temp);
You can also use Arrays.asList()
:
Object temp = data.getParameterValue("request");
Object log = temp == null ? null : (temp.getClass().isArray() ? Arrays.asList((Object[])temp) : temp);
log.info("end " + temp);
This may result in a ClassCastException
for primitive arrays (int[]
, ...).
You can try put in a shortcut to the site and tell the .bat file to open that.
start Google.HTML
exit
This error also occurs when your app's minSdk is higher than any library's minSdk.
app's minSdk >= libraries minSdk
In interface builder you can configure options Edge Insets for UIButton, separately each of three parts: content, image, title
Xcode 8:
It can depend, especially on whether your file will have the same number of items on each row or not. If it will, then you probably want a 2D matrix class of some sort, usually something like this:
class array2D {
std::vector<double> data;
size_t columns;
public:
array2D(size_t x, size_t y) : columns(x), data(x*y) {}
double &operator(size_t x, size_t y) {
return data[y*columns+x];
}
};
Note that as it's written, this assumes you know the size you'll need up-front. That can be avoided, but the code gets a little larger and more complex.
In any case, to read the numbers and maintain the original structure, you'd typically read a line at a time into a string, then use a stringstream to read numbers from the line. This lets you store the data from each line into a separate row in your array.
If you don't know the size ahead of time or (especially) if different rows might not all contain the same number of numbers:
11 12 13
23 34 56 78
You might want to use a std::vector<std::vector<double> >
instead. This does impose some overhead, but if different rows may have different sizes, it's an easy way to do the job.
std::vector<std::vector<double> > numbers;
std::string temp;
while (std::getline(infile, temp)) {
std::istringstream buffer(temp);
std::vector<double> line((std::istream_iterator<double>(buffer)),
std::istream_iterator<double>());
numbers.push_back(line);
}
...or, with a modern (C++11) compiler, you can use brackets for line
's initialization:
std::vector<double> line{std::istream_iterator<double>(buffer),
std::istream_iterator<double>()};
What is happening here is that database route does not accept any url methods.
I would try putting the url methods in the app route just like you have in the entry_page function:
@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
if request.method == 'POST':
date = request.form['date']
title = request.form['blog_title']
post = request.form['blog_main']
post_entry = models.BlogPost(date = date, title = title, post = post)
db.session.add(post_entry)
db.session.commit()
return redirect(url_for('database'))
else:
return render_template('entry.html')
@app.route('/database', methods=['GET', 'POST'])
def database():
query = []
for i in session.query(models.BlogPost):
query.append((i.title, i.post, i.date))
return render_template('database.html', query = query)
Add a CSS class to the <option>
tag to style it: http://jsfiddle.net/Ahreu/
Currently WebKit browsers don't support this behavior, as it's undefined by the spec. Take a look at this: How to style a select tag's option element?
A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.
A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.
A simple tcp server I had for serving the flash policy file was causing this. I can now catch the error using a handler:
# serving the flash policy file
net = require("net")
net.createServer((socket) =>
//just added
socket.on("error", (err) =>
console.log("Caught flash policy server socket error: ")
console.log(err.stack)
)
socket.write("<?xml version=\"1.0\"?>\n")
socket.write("<!DOCTYPE cross-domain-policy SYSTEM \"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd\">\n")
socket.write("<cross-domain-policy>\n")
socket.write("<allow-access-from domain=\"*\" to-ports=\"*\"/>\n")
socket.write("</cross-domain-policy>\n")
socket.end()
).listen(843)
Here's what works for me as of Gradle 4.0.
sourceSets {
integrationTest {
compileClasspath += sourceSets.test.compileClasspath
runtimeClasspath += sourceSets.test.runtimeClasspath
}
}
task integrationTest(type: Test) {
description = "Runs the integration tests."
group = 'verification'
testClassesDirs = sourceSets.integrationTest.output.classesDirs
classpath = sourceSets.integrationTest.runtimeClasspath
}
As of version 4.0, Gradle now uses separate classes directories for each language in a source set. So if your build script uses sourceSets.integrationTest.output.classesDir
, you'll see the following deprecation warning.
Gradle now uses separate output directories for each JVM language, but this build assumes a single directory for all classes from a source set. This behaviour has been deprecated and is scheduled to be removed in Gradle 5.0
To get rid of this warning, just switch to sourceSets.integrationTest.output.classesDirs
instead. For more information, see the Gradle 4.0 release notes.
$('#my_select').bind('mousedown', function (event) {_x000D_
event.preventDefault();_x000D_
event.stopImmediatePropagation();_x000D_
});
_x000D_
The fix for me was locally installing webpack as devDependency. Although I have it as devDependencies
it was not installed in node_modules folder. So I ran
npm install --only=dev
I have just got an solution a little bit easier do get an list out of an JSON object. Hope this can help.
I got an JSON like this:
{"Accounts":"[{\"bank\":\"Itau\",\"account\":\"456\",\"agency\":\"0444\",\"digit\":\"5\"}]"}
And made some types like this
public class FinancialData
{
public string Accounts { get; set; } // this will store the JSON string
public List<Accounts> AccountsList { get; set; } // this will be the actually list.
}
public class Accounts
{
public string bank { get; set; }
public string account { get; set; }
public string agency { get; set; }
public string digit { get; set; }
}
and the "magic" part
Models.FinancialData financialData = (Models.FinancialData)JsonConvert.DeserializeObject(myJSON,typeof(Models.FinancialData));
var accounts = JsonConvert.DeserializeObject(financialData.Accounts) as JArray;
foreach (var account in accounts)
{
if (financialData.AccountsList == null)
{
financialData.AccountsList = new List<Models.Accounts>();
}
financialData.AccountsList.Add(JsonConvert.DeserializeObject<Models.Accounts>(account.ToString()));
}
This helped me:
<p>Date/Time: <span id="datetime"></span></p><script>var dt = new Date();
document.getElementById("datetime").innerHTML=dt.toLocaleString();</script>
This works for me. in place of customTheme you can put you theme in styles. in this code you can also change the font and text size.
<style name="MyTheme.NavMenu" parent="CustomTheme">
<item name="android:textSize">16sp</item>
<item name="android:fontFamily">@font/ssp_semi_bold</item>
<item name="android:textColorPrimary">@color/yourcolor</item>
</style>
here is my navigation view
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:theme="@style/MyTheme.NavMenu"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer">
<include layout="@layout/layout_update_available"/>
</android.support.design.widget.NavigationView>
Using split()
will be the most Pythonic way of splitting on a string.
It's also useful to remember that if you use split()
on a string that does not have a whitespace then that string will be returned to you in a list.
Example:
>>> "ark".split()
['ark']
Maybe not THE answer, but it's definitely AN answer.
If nothing else is working for you, go the nuclear option: Close IDEA and delete the ".../.IntelliJIdea/system" directory using your local file system tools.
The .IntelliJIdea directory is usually found in your home directory. Your IDE configuration is in the ".../.IntelliJIdea/config" directory, so it should be fine.
Obviously, this is not the "IDEA" way to do it and would be completely unsupported by JetBrains. Also - I don't use Android Studio so I dunno if this will cause problems, but there you go.
It's worked for me before when I've had problems getting IDEA to start and nothing else works to get me going. Maybe back up your entire .IntelliJIdea directory if you have a morbid fear of losing all your work >.<
{{ app.user.username|default('') }}
Just present login username for example, filter function default('') should be nice when user is NOT login by just avoid annoying error message.
For is()
import static org.hamcrest.CoreMatchers.*;
For assertThat()
import static org.junit.Assert.*;
For when() and verify()
import static org.mockito.Mockito.*;
Assuming Column A contains the values you want to find single unique instance of, and has a Heading row I used the following formula. If you wanted it to scale with an unpredictable number of rows, you could replace A772 (where my data ended) with =ADDRESS(COUNTA(A:A),1).
=IF(COUNTIF(A5:$A$772,A5)=1,A5,"")
This will display the unique value at the LAST instance of each value in the column and doesn't assume any sorting. It takes advantage of the lack of absolutes to essentially have a decreasing "sliding window" of data to count. When the countif in the reduced window is equal to 1, then that row is the last instance of that value in the column.
String[] mString = new String[] {"B", "D", "F"};
for (int j = 0; j < mString.length-1; j++) {
List_Of_Array.remove(mString[j]);
}
I found that I needed to install another version of ruby. So running the command
$ sudo apt-get install ruby1.9.1-dev
and then attempt to install the extension
If you run into issues where it is telling you that you don't have g++ you can run the following command to install it
$ sudo apt-get install g++
var charCount = "string with periods...".Count(x => '.' == x);
My use case was I wanted to replace
foo:/Drive_Letter
with foo:/bar/baz/xyz
In my case I was able to do it with the following code.
I was in the same directory location where there were bulk of files.
find . -name "*.library" -print0 | xargs -0 sed -i '' -e 's/foo:\/Drive_Letter:/foo:\/bar\/baz\/xyz/g'
hope that helped.
UPDATE s|foo:/Drive_letter:|foo:/ba/baz/xyz|g
Following @ragzzy 's answer I use
public static string Value(this IWebElement element, IJavaScriptExecutor javaScriptExecutor)
{
try
{
string value = javaScriptExecutor.ExecuteScript("return arguments[0].value", element) as string;
return value;
}
catch (Exception)
{
return null;
}
}
It works quite well and does not alter the DOM
I had a similar issue in MVC (which lead me to this problem).
I am receiving a FORM as a string response from a WebClient.UploadValues() request, which I then have to submit - so I can't use a second WebClient or HttpWebRequest. This request returned the string.
using (WebClient client = new WebClient())
{
byte[] response = client.UploadValues(urlToCall, "POST", new NameValueCollection()
{
{ "test", "value123" }
});
result = System.Text.Encoding.UTF8.GetString(response);
}
My solution, which could be used to solve the OP, is to append a Javascript auto submit to the end of the code, and then using @Html.Raw() to render it on a Razor page.
result += "<script>self.document.forms[0].submit()</script>";
someModel.rawHTML = result;
return View(someModel);
Razor Code:
@model SomeModel
@{
Layout = null;
}
@Html.Raw(@Model.rawHTML)
I hope this can help anyone who finds themselves in the same situation.
I'm doing this on my raspberry pi from the command line by running:
for i in *;do omxplayer "$i";done
if (iar1 == iar2)
Here iar1
and iar2
are decaying to pointers to the first elements of the respective arrays. Since they are two distinct arrays, the pointer values are, of course, different and your comparison tests not equal.
To do an element-wise comparison, you must either write a loop; or use std::array
instead
std::array<int, 5> iar1 {1,2,3,4,5};
std::array<int, 5> iar2 {1,2,3,4,5};
if( iar1 == iar2 ) {
// arrays contents are the same
} else {
// not the same
}
Look at Morris in-order tree traversal which uses constant space and runs in O(n) (up to 3 times longer than your normal recursive traversal - but you save hugely on space). If the nodes are modifiable, than you could save the calculated result of the sub-tree as you backtrack to its root (by writing directly to the Node).
I had this error once and it ended up being the server's hard drive that run out of disk space.
You were almost there:
You just need to append the li
to ul
and voila!
So just add
ul.appendChild(li);
to the end of your function so the end function will be like this:
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Element 4"));
ul.appendChild(li);
}
Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)
They are designed to work with WCF.
If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP
From the Linux manual page:
h A following integer conversion corresponds to a short int or unsigned short int argument, or a fol- lowing n conversion corresponds to a pointer to a short int argument.
So to print an unsigned short integer, the format string should be "%hu"
.
For me the problem was caused by a gradle.properties file in the list of Gradle scripts. It showed as gradle.properties (global) and refered to a file in C:\users\.gradle\gradle.properties. I right-clicked on it and selected delete from the menu to delete it. It deleted the file from the hard disk and my project now builds and runs. I guess that the global file was overwriting something that was used to locate the package android.support
Angular: 8.2.11
<td>{{ data.DateofBirth | date }}</td>
Output: Jun 9, 1973
<td>{{ data.DateofBirth | date: 'dd/MM/yyyy' }}</td>
Output: 09/06/1973
<td>{{ data.DateofBirth | date: 'dd/MM/yyyy hh:mm a' }}</td>
Output: 09/06/1973 12:00 AM
I usually use one over the other based on the time complexities of the operations that I'd perform on that particular List.
|---------------------|---------------------|--------------------|------------|
| Operation | ArrayList | LinkedList | Winner |
|---------------------|---------------------|--------------------|------------|
| get(index) | O(1) | O(n) | ArrayList |
| | | n/4 steps in avg | |
|---------------------|---------------------|--------------------|------------|
| add(E) | O(1) | O(1) | LinkedList |
| |---------------------|--------------------| |
| | O(n) in worst case | | |
|---------------------|---------------------|--------------------|------------|
| add(index, E) | O(n) | O(n) | LinkedList |
| | n/2 steps | n/4 steps | |
| |---------------------|--------------------| |
| | | O(1) if index = 0 | |
|---------------------|---------------------|--------------------|------------|
| remove(index, E) | O(n) | O(n) | LinkedList |
| |---------------------|--------------------| |
| | n/2 steps | n/4 steps | |
|---------------------|---------------------|--------------------|------------|
| Iterator.remove() | O(n) | O(1) | LinkedList |
| ListIterator.add() | | | |
|---------------------|---------------------|--------------------|------------|
|--------------------------------------|-----------------------------------|
| ArrayList | LinkedList |
|--------------------------------------|-----------------------------------|
| Allows fast read access | Retrieving element takes O(n) |
|--------------------------------------|-----------------------------------|
| Adding an element require shifting | o(1) [but traversing takes time] |
| all the later elements | |
|--------------------------------------|-----------------------------------|
| To add more elements than capacity |
| new array need to be allocated |
|--------------------------------------|
You can use the lower
function:
Guide.where("lower(title)='attack'")
As a comment: Work on your question. The title isn't terribly informative, and you drop a big chunk of code at the end that is irrelevant to your question.
In answer to your first question, it should be as simple as replacing:
when(LoggerFactory.getLogger(GoodbyeController.class)).thenReturn(loggerMock);
with
when(LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);
Regarding your second question (and possibly the puzzling behavior with the first), I think the problem is that logger is static. So,
private static Logger logger = LoggerFactory.getLogger(GoodbyeController.class);
is executed when the class is initialized, not the when the object is instantiated. Sometimes this can be at about the same time, so you'll be OK, but it's hard to guarantee that. So you set up LoggerFactory.getLogger to return your mock, but the logger variable may have already been set with a real Logger object by the time your mocks are set up.
You may be able to set the logger explicitly using something like ReflectionTestUtils (I don't know if that works with static fields) or change it from a static field to an instance field. Either way, you don't need to mock LoggerFactory.getLogger because you'll be directly injecting the mock Logger instance.
It can be very pragmatic to configure specific infrastructure concerns as singletons or global variables. My favourite example of this is Dependency Injection frameworks that make use of singletons to act as a connection point to the framework.
In this case you are taking a dependency on the infrastructure to simplify using the library and avoid unneeded complexity.
The best way I see is to use live() or delegate() to capture the event in a parent and not in each child element.
If your button is inside a #parent element, you can replace:
$('#myButton').bind('click', onButtonClicked);
by
$('#parent').delegate('#myButton', 'click', onButtonClicked);
even if #myButton doesn't exist yet when this code is executed.
set shell=CreateObject("Shell.Application")
' shell.ShellExecute "application", "arguments", "path", "verb", window
shell.ShellExecute "slipery.bat",,"C:\Users\anthony\Desktop\dvx", "runas", 1
set shell=nothing
Here's a 2020 answer - if you don't need to support the older .xls format (so pre 2003) you could use either:
or
Pros :
Cons:
Disclaimer: I am the author of LightweightExcelReader and ExcelToEnumerable
I faced this while using jQuery FileUpload plugin.
Then I took a look in their documentation, most exactly in the Content-Type Negotiation section and followed their suggestion for Ruby/Rails.
render(json: <some-data>, content_type: request.format)
Which fixed the issue for me.
Quick Explanation: for old IE/Opera versions, this plugin will use an iframe with text/plain
or text/html
content-type, so if you force the response to json
, browser will try download it. Using the same content-type as in the request will make it work for any browser.
I've historically rolled my own access at a low level (XML generation and parsing) to deal with the occasional need to do SOAP style requests from Objective-C. That said, there's a library available called SOAPClient (soapclient) that is open source (BSD licensed) and available on Google Code (mac-soapclient) that might be of interest.
I won't attest to it's abilities or effectiveness, as I've never used it or had to work with it's API's, but it is available and might provide a quick solution for you depending on your needs.
Apple had, at one time, a very broken utility called WS-MakeStubs. I don't think it's available on the iPhone, but you might also be interested in an open-source library intended to replace that - code generate out Objective-C for interacting with a SOAP client. Again, I haven't used it - but I've marked it down in my notes: wsdl2objc
It worked only after removing the eclipse folder and all related folders like .p2, .eclipse (in my case they are at different location where I have saved eclipse installer) etc. and after re-downloading the eclipse, it worked.
I had one problem because when I tried to change my NavigationItem title programmatically i was not able to find my family font (tried many things but impossible to make it run correctly) so I found one workaround very nice and easy in storyboard.
Finally you should have something like that in document outline:
And something like that in your ViewController:
Hope it can help.
You have to install grunt in your project folder
create your package.json
$ npm init
install grunt for this project, this will be installed under node_modules/
. --save-dev will add this module to devDependency in your package.json
$ npm install grunt --save-dev
then create gruntfile.js and run
$ grunt
Here's another:
data[data$Code == "A" | data$Code == "B", ]
It's also worth mentioning that the subsetting factor doesn't have to be part of the data frame if it matches the data frame rows in length and order. In this case we made our data frame from this factor anyway. So,
data[Code == "A" | Code == "B", ]
also works, which is one of the really useful things about R.
Yes, You can do it this way too
List<String> listTab = new List();
map.forEach((key, val) {
listTab.add(val);
});
//your widget//
bottom: new TabBar(
controller: _controller,
isScrollable: true,
tabs: listTab
,
),
You can use Request
object or Uri
object to get host of url.
Using Request.Url
string host = Request.Url.Host;
Using Uri
Uri myUri = new Uri("http://www.contoso.com:8080/");
string host = myUri.Host; // host is "www.contoso.com"
preg_replace('#[^\w()/.%\-&]#',"",$string);
Maybe EXISTS
can help.
and exists (select 1 from @DocumentNames where pcd.Name like DocName+'%' or CD.DocumentName like DocName+'%')
entryComponents
is vital. Above answers on this are correct.But...
providedIn: 'root'
to providedIn: MyModule
. As general good practice you should just use the providedIn: SomeModule
for all dialog services that are in modules.Peer authentication means that postgres asks the operating system for your login name and uses this for authentication. To login as user "dev" using peer authentication on postgres, you must also be the user "dev" on the operating system.
You can find details to the authentication methods in the Postgresql documentation.
Hint: If no authentication method works anymore, disconnect the server from the network and use method "trust" for "localhost" (and double check that your server is not reachable through the network while method "trust" is enabled).
SELECT tab.*,
row_number() OVER () as rnum
FROM tab;
Here's the relevant section in the docs.
P.S. This, in fact, fully matches the answer in the referenced question.
You can click on the Project window, press Alt-Insert, and select Folder->Assets Folder. Android Studio will add it automatically to the correct location.
You are most likely looking at your Project with the new(ish) "Android View". Note that this is a view and not the actual folder structure on disk (which hasn't changed since the introduction of Gradle as the new build tool). You can switch to the old "Project View" by clicking on the word "Android" at the top of the Project window and selecting "Project".
To go directly to that folder, you can use the Set-Location
cmdlet or cd
alias:
Set-Location "Q:\My Test Folder"
in my own case in django 1.10.1 running on python2.7.11, I was trying to start the server using django-admin runserver
instead of manage.py runserver
in my project directory.
I installed ArcGIS Pro 1.4 and it didn't register the Python 3.5.2 it installed which prevented me from installing any add-ons. I resolved this by using the "reg" command in an Administrator PowerShell session to manually create and populate the necessary registry keys/values (where Python is installed in C:\Python35):
reg add "HKLM\Software\Python\PythonCore\3.5\Help\Main Python Documentation" /reg:64 /ve /t REG_SZ /d "C:\Python35\Doc\Python352.chm"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath\InstallGroup" /reg:64 /ve /t REG_SZ /d "Python 3.5"
reg add "HKLM\Software\Python\PythonCore\3.5\PythonPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\Lib;C:\Python35\DLLs;C:\Python35\Lib\lib-tk"
I find this easier than using Registry Editor but that's solely a personal preference.
The same commands can be executed in CMD.EXE session if you prefer; just make sure you run it as Administrator.
$('#myform').on('submit',function(event){
// block form submit event
event.preventDefault();
// Do some stuff here
...
// Continue the form submit
event.currentTarget.submit();
});
Everybody has the right idea, but I like to be a little more explicit and trim the values.
$('#apply-form input').blur(function() {
if(!$.trim(this.value).length) { // zero-length string AFTER a trim
$(this).parents('p').addClass('warning');
}
});
if you dont use .length , then an entry of '0' can get flagged as bad, and an entry of 5 spaces could get marked as ok without the $.trim . Best of Luck.
They serve the actual image inside CSS so there will be less HTTP requests per page.
Sometimes you have to remove the current options in order to manipulate the selected options.
Here is an example how to set options:
<select id="mySelectId" class="chosen-select" multiple="multiple">
<option value=""></option>
<option value="Argentina">Argentina</option>
<option value="Germany">Germany</option>
<option value="Greece">Greece</option>
<option value="Japan">Japan</option>
<option value="Thailand">Thailand</option>
</select>
<script>
activateChosen($('body'));
selectChosenOptions($('#mySelectId'), ['Argentina', 'Germany']);
function activateChosen($container, param) {
param = param || {};
$container.find('.chosen-select:visible').chosen(param);
$container.find('.chosen-select').trigger("chosen:updated");
}
function selectChosenOptions($select, values) {
$select.val(null); //delete current options
$select.val(values); //add new options
$select.trigger('chosen:updated');
}
</script>
JSFiddle (including howto append options): https://jsfiddle.net/59x3m6op/1/
Ok I know this for VBA but if you need to do this for a once off bulk delete you can use the following Excel functionality: http://blog.contextures.com/archives/2010/06/21/fast-way-to-find-and-delete-excel-rows/ Hope this helps anyone
Example looking for the string "paper":
Put them into a list
and use merge
with Reduce
Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
# id v1 v2 v3
# 1 1 1 NA NA
# 2 10 4 NA NA
# 3 2 3 4 NA
# 4 43 5 NA NA
# 5 73 2 NA NA
# 6 23 NA 2 1
# 7 57 NA 3 NA
# 8 62 NA 5 2
# 9 7 NA 1 NA
# 10 96 NA 6 NA
You can also use this more concise version:
Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))
Finding a linear model such as this one can be handled with OpenTURNS.
In OpenTURNS this is done with the LinearModelAlgorithm
class which creates a linear model from numerical samples. To be more specific, it builds the following linear model :
Y = a0 + a1.X1 + ... + an.Xn + epsilon,
where the error epsilon is gaussian with zero mean and unit variance. Assuming your data is in a csv file, here is a simple script to get the regression coefficients ai :
from __future__ import print_function
import pandas as pd
import openturns as ot
# Assuming the data is a csv file with the given structure
# Y X1 X2 .. X7
df = pd.read_csv("./data.csv", sep="\s+")
# Build a sample from the pandas dataframe
sample = ot.Sample(df.values)
# The observation points are in the first column (dimension 1)
Y = sample[:, 0]
# The input vector (X1,..,X7) of dimension 7
X = sample[:, 1::]
# Build a Linear model approximation
result = ot.LinearModelAlgorithm(X, Y).getResult()
# Get the coefficients ai
print("coefficients of the linear regression model = ", result.getCoefficients())
You can then easily get the confidence intervals with the following call :
# Get the confidence intervals at 90% of the ai coefficients
print(
"confidence intervals of the coefficients = ",
ot.LinearModelAnalysis(result).getCoefficientsConfidenceInterval(0.9),
)
You may find a more detailed example in the OpenTURNS examples.
#header2
{
display: table-cell;
vertical-align: bottom;
background-color:Red;
}
<div style="text-align:center; height:300px; width:50%;" id="header2">
<div class="right" id="header-content2">
<p>this is a test</p>
</div>
</div>
To increase the area of a text link you can use the following css;
a {
display: inline-block;
position: relative;
z-index: 1;
padding: 2em;
margin: -2em;
}
Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.
>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False
Edit
Further explanation: How does Python compare string and int?
<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">
In above html tag we have different attributes like src
, alt
, width
and height
.
If you want to get the any attribute value from above html tag you have to pass attribute value in getAttribute()
method
Syntax:
getAttribute(attributeValue)
getAttribute(src) you get w3schools.jpg
getAttribute(height) you get 142
getAttribute(width) you get 104
To delete all files and directories within the current directory:
find . -mtime +3 | xargs rm -Rf
Or alternatively, more in line with the OP's original command:
find . -mtime +3 -exec rm -Rf -- {} \;
ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
//get a customerName
//get an amount
custArr.add(new Customer(customerName, amount);
}
For this to work... you'll have to fix your constructor...
Assuming your Customer
class has variables called name
and sale
, your constructor should look like this:
public Customer(String customerName, double amount) {
name = customerName;
sale = amount;
}
Change your Store
class to something more like this:
public class Store {
private ArrayList<Customer> custArr;
public new Store() {
custArr = new ArrayList<Customer>();
}
public void addSale(String customerName, double amount) {
custArr.add(new Customer(customerName, amount));
}
public Customer getSaleAtIndex(int index) {
return custArr.get(index);
}
//or if you want the entire ArrayList:
public ArrayList getCustArr() {
return custArr;
}
}
If you are using the Spring Boot Maven Plugin, run:
mvn spring-boot:run -Dspring-boot.run.profiles=foo,bar
(https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-profiles.html)
$result = mysql_query($query) or die("Data not found.");
$rows=array();
while($r=mysql_fetch_assoc($result))
{
$rows[]=$r;
}
header("Content-type:application/json");
echo json_encode($rows);
If you are using Appcompact
Activity use these three lines in your theme.
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowActionBarOverlay">false</item>
You need to use LogLevel rewrite:trace3
to your httpd.conf
in newer version
http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#logging
Anaconda is made for the purpose you are asking. It is also an environment manager. It separates out environments. It was made because stable and legacy packages were not supported with newer/unstable versions of host languages; therefore a software was required that could separate and manage these versions on the same machine without the need to reinstall or uninstall individual host programming languages/environments.
You can find creation/deletion of environments in the Anaconda documentation.
Hope this helped.
The answers of others do not give you the exact number!
This function calculates the desired number accurately and returns it in the string to prevent it from being changed by javascript!
If you need a numerical result, just multiply the result of the function in number one!
function toNonExponential(value) {
// if value is not a number try to convert it to number
if (typeof value !== "number") {
value = parseFloat(value);
// after convert, if value is not a number return empty string
if (isNaN(value)) {
return "";
}
}
var sign;
var e;
// if value is negative, save "-" in sign variable and calculate the absolute value
if (value < 0) {
sign = "-";
value = Math.abs(value);
}
else {
sign = "";
}
// if value is between 0 and 1
if (value < 1.0) {
// get e value
e = parseInt(value.toString().split('e-')[1]);
// if value is exponential convert it to non exponential
if (e) {
value *= Math.pow(10, e - 1);
value = '0.' + (new Array(e)).join('0') + value.toString().substring(2);
}
}
else {
// get e value
e = parseInt(value.toString().split('e+')[1]);
// if value is exponential convert it to non exponential
if (e) {
value /= Math.pow(10, e);
value += (new Array(e + 1)).join('0');
}
}
// if value has negative sign, add to it
return sign + value;
}
The following are the ways we can use to check the dependencies:
Method 1: Using sp_depends
sp_depends 'dbo.First'
GO
Method 2: Using information_schema.routines
SELECT *
FROM information_schema.routines ISR
WHERE CHARINDEX('dbo.First', ISR.ROUTINE_DEFINITION) > 0
GO
Method 3: Using DMV sys.dm_sql_referencing_entities
SELECT referencing_schema_name, referencing_entity_name,
referencing_id, referencing_class_desc, is_caller_dependent
FROM sys.dm_sql_referencing_entities ('dbo.First', 'OBJECT');
GO
If you are doing a lot of functionality based on scroll position, Scroll magic (http://scrollmagic.io/) is built entirely for this purpose.
It makes it easy to trigger JS based on when the user reaches certain elements when scrolling. It also integrates with the GSAP animation engine (https://greensock.com/) which is great for parallax scrolling websites
When you need to toggle an element away, and you don't need to animate the margin property. You could try margin-top: -999999em
. Just don't transition all.
use this..
$(".content_box a:not('.button')")
All of the above might be true, however for me "online-updating" of figures only works with some backends, specifically wx
. You just might try to change to this, e.g. by starting ipython/pylab by ipython --pylab=wx
! Good luck!
If we define dx = x2 - x1
and dy = y2 - y1
, then the normals are (-dy, dx)
and (dy, -dx)
.
Note that no division is required, and so you're not risking dividing by zero.
(new FileInfo(filePath)).Directory.Create()
Before writing to the file.
System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);
Use shell=True
if you're passing a string to subprocess.call
.
From docs:
If passing a single string, either
shell
must beTrue
or else the string must simply name the program to be executed without specifying any arguments.
subprocess.call(crop, shell=True)
or:
import shlex
subprocess.call(shlex.split(crop))
grant CREATE SESSION
Ref.. http://ss64.com/ora/grant.html
HTH,
Kent
<html>
<head>
<script src="angular.min.js"></script>
</head>
<body>
<div ng-app="shoppingCartParentModule" >
<div ng-controller="ShoppingCartController">
<h1>Your order</h1>
<div ng-repeat="item in items">
<span>{{item.product_name}}</span>
<span>{{item.price | currency}}</span>
<button ng-click="remove($index);">Remove</button>
</div>
</div>
<div ng-controller="NamesController">
<h1>List of Names</h1>
<div ng-repeat="name in names">
<p>{{name.username}}</p>
</div>
</div>
</div>
</body>
<script>
var shoppingCartModule = angular.module("shoppingCart", [])
shoppingCartModule.controller("ShoppingCartController",
function($scope) {
$scope.items = [
{product_name: "Product 1", price: 50},
{product_name: "Product 2", price: 20},
{product_name: "Product 3", price: 180}
];
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
}
);
var namesModule = angular.module("namesList", [])
namesModule.controller("NamesController",
function($scope) {
$scope.names = [
{username: "Nitin"},
{username: "Mukesh"}
];
}
);
angular.module("shoppingCartParentModule",["shoppingCart","namesList"])
</script>
</html>
No, it will not be evaluated. And this is very useful. For example, if you need to test whether a String is not null or empty, you can write:
if (str != null && !str.isEmpty()) {
doSomethingWith(str.charAt(0));
}
or, the other way around
if (str == null || str.isEmpty()) {
complainAboutUnusableString();
} else {
doSomethingWith(str.charAt(0));
}
If we didn't have 'short-circuits' in Java, we'd receive a lot of NullPointerExceptions in the above lines of code.
If you use Android default action bar then. If you change from java then some time show previous color.
Example
Then your action bar code inside "app_bar_main". So go inside app_bar_main.xml and just add Background.
Example
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#33691e" <!--use your color -->
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main1" />
I am not sure it works with all type of data but the only solution I found for the moment is to test if index returns blank:
=IF(ISBLANK(INDEX(a,b,c)),"",INDEX(a,b,c))
The formula
=IF(INDEX(a,b,c),INDEX(a,b,c),"")
does not work with text
I think your issue is that Range("H18")
doesn't contain a formula. Also, you could make your code more efficient by eliminating x
. Instead, change your code to
Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")
use open public proxy YQL, hosted by Yahoo. Handles XML and HTML
https://gist.github.com/rickdog/d66a03d1e1e5959aa9b68869807791d5
Regarding Bruce Adams answer:
Your answer creates dangerous confusion. DESTDIR is intended for installs out of the root tree. It allows one to see what would be installed in the root tree if one did not specify DESTDIR. PREFIX is the base directory upon which the real installation is based.
For example, PREFIX=/usr/local indicates that the final destination of a package is /usr/local. Using DESTDIR=$HOME will install the files as if $HOME was the root (/). If, say DESTDIR, was /tmp/destdir, one could see what 'make install' would affect. In that spirit, DESTDIR should never affect the built objects.
A makefile segment to explain it:
install:
cp program $DESTDIR$PREFIX/bin/program
Programs must assume that PREFIX is the base directory of the final (i.e. production) directory. The possibility of symlinking a program installed in DESTDIR=/something only means that the program does not access files based upon PREFIX as it would simply not work. cat(1) is a program that (in its simplest form) can run from anywhere. Here is an example that won't:
prog.pseudo.in:
open("@prefix@/share/prog.db")
...
prog:
sed -e "s/@prefix@/$PREFIX/" prog.pseudo.in > prog.pseudo
compile prog.pseudo
install:
cp prog $DESTDIR$PREFIX/bin/prog
cp prog.db $DESTDIR$PREFIX/share/prog.db
If you tried to run prog from elsewhere than $PREFIX/bin/prog, prog.db would never be found as it is not in its expected location.
Finally, /etc/alternatives really does not work this way. There are symlinks to programs installed in the root tree (e.g. vi -> /usr/bin/nvi, vi -> /usr/bin/vim, etc.).
Easy task with grep
:
grep -v help filename
Append > newFileName
to redirect output to a new file.
To clarify it, the normal behavior will be printing the lines on screen. To pipe it to a file, the >
can be used. Thus, in this command:
grep -v help filename > newFileName
grep
calls the grep
program, obviously-v
is a flag to inverse the output. By defaulf, grep
prints the lines that match the given pattern. With this flag, it will print the lines that don't match the pattern.help
is the pattern to matchfilename
is the name of the input file>
redirects the output to the following itemnewFileName
the new file where output will be saved.As you may noticed, you will not be deleting things in your file. grep
will read it and another file will be saved, modified accordingly.
This worked for me:
I simply cd "C:\the_path_of_the_project_where_package.json_is"
before I ran "npm start"
You can sort the dataFrame by count and then remove duplicates. I think it's easier:
df.sort_values('count', ascending=False).drop_duplicates(['Sp','Mt'])
You inherit class attributes, not class constructors .This is how it goes :
If no constructor is added in the super class, if no then the compiler adds a no argument contructor. This default constructor is invoked implicitly whenever a new instance of the sub class is created . Here the sub class may or may not have constructor, all is ok .
if a constructor is provided in the super class, the compiler will see if it is a no arg constructor or a constructor with parameters.
if no args, then the compiler will invoke it for any sub class instanciation . Here also the sub class may or may not have constructor, all is ok .
if 1 or more contructors in the parent class have parameters and no args constructor is absent, then the subclass has to have at least 1 constructor where an implicit call for the parent class construct is made via super (parent_contractor params) .
this way you are sure that the inherited class attributes are always instanciated .
Omit the parenthesis:
ALTER TABLE User
ADD CONSTRAINT userProperties
FOREIGN KEY(properties)
REFERENCES Properties(ID)
Not quite - since each "left" row in a left-outer-join will match 0-n "right" rows (in the second table), where-as yours matches only 0-1. To do a left outer join, you need SelectMany
and DefaultIfEmpty
, for example:
var query = from c in db.Customers
join o in db.Orders
on c.CustomerID equals o.CustomerID into sr
from x in sr.DefaultIfEmpty()
select new {
CustomerID = c.CustomerID, ContactName = c.ContactName,
OrderID = x == null ? -1 : x.OrderID };
Yes, many changes at Heroku. If you're using a Heroku dyno for your webserver, you have to find way to alias from one DNS
name to another DNS
name (since each Heroku DNS endpoint may resolve to many IP addrs to dynamically adjust to request loads).
A CNAME
record is for aliasing www.example.com
-> www.example.com.herokudns.com.
You can't use CNAME
for a naked domain (@
), i.e. example.com
(unless you find a name server that can do CNAME Flattening
- which is what I did).
But really the easiest solution, that can pretty much be taken care of all in your GoDaddy account, is to create a CNAME record
that does this: www.example.com -> www.example.com.herokudns.com
.
And then create a permanent 301 redirect from example.com
to www.example.com
.
This requires only one heroku custom domain name configured in your heroku app settings: www.example.com.herokudns.com
. @Jonathan Roy talks about this (above) but provides a bad link.
I have slightly modified the accepted answer by handling value types. I came across this when trying to do the following and because GetProperties() is zero length for value types I was getting an empty dataset. I know this is not the use case for the OP but thought I'd post this change in case anyone else came across the same thing.
Enumerable.Range(1, 10).ToList().ToDataSet();
public static DataSet ToDataSet<T>(this IList<T> list)
{
var elementType = typeof(T);
var ds = new DataSet();
var t = new DataTable();
ds.Tables.Add(t);
if (elementType.IsValueType)
{
var colType = Nullable.GetUnderlyingType(elementType) ?? elementType;
t.Columns.Add(elementType.Name, colType);
} else
{
//add a column to table for each public property on T
foreach (var propInfo in elementType.GetProperties())
{
var colType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
t.Columns.Add(propInfo.Name, colType);
}
}
//go through each property on T and add each value to the table
foreach (var item in list)
{
var row = t.NewRow();
if (elementType.IsValueType)
{
row[elementType.Name] = item;
}
else
{
foreach (var propInfo in elementType.GetProperties())
{
row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
}
}
t.Rows.Add(row);
}
return ds;
}
C:\xampp>mysql -u root -p mydatabase < C:\DB_Backups\stage-new.sql
Enter password:
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the ma
nual that corresponds to your MySQL server version for the right syntax to use n
ear 'stage-new.sql
----lot of space----
' at line 1
The reason was when I dumped the DB I used following command :
mysqldump -h <host> -u <username> -p <database> > dumpfile.sql
dumpfile.sql
By mistaken dumpfile.sql added twice in the syntax.
Solution : I removed the dumpfile.sql text added to first line of the exported dumpfile.
Well, this is my final solution for a simple db, for Linux:
# Read this before!
#
# * roles in postgres are users, and can be used also as group of users
# * $ROLE_LOCAL will be the user that access the db for maintenance and
# administration. $ROLE_REMOTE will be the user that access the db from the webapp
# * you have to change '$ROLE_LOCAL', '$ROLE_REMOTE' and '$DB'
# strings with your desired names
# * it's preferable that $ROLE_LOCAL == $DB
#-------------------------------------------------------------------------------
//----------- SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - START ----------//
cd /etc/postgresql/$VERSION/main
sudo cp pg_hba.conf pg_hba.conf_bak
sudo -e pg_hba.conf
# change all `md5` with `scram-sha-256`
# save and exit
//------------ SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - END -----------//
sudo -u postgres psql
# in psql:
create role $ROLE_LOCAL login createdb;
\password $ROLE_LOCAL
create role $ROLE_REMOTE login;
\password $ROLE_REMOTE
create database $DB owner $ROLE_LOCAL encoding "utf8";
\connect $DB $ROLE_LOCAL
# Create all tables and objects, and after that:
\connect $DB postgres
revoke connect on database $DB from public;
revoke all on schema public from public;
revoke all on all tables in schema public from public;
grant connect on database $DB to $ROLE_LOCAL;
grant all on schema public to $ROLE_LOCAL;
grant all on all tables in schema public to $ROLE_LOCAL;
grant all on all sequences in schema public to $ROLE_LOCAL;
grant all on all functions in schema public to $ROLE_LOCAL;
grant connect on database $DB to $ROLE_REMOTE;
grant usage on schema public to $ROLE_REMOTE;
grant select, insert, update, delete on all tables in schema public to $ROLE_REMOTE;
grant usage, select on all sequences in schema public to $ROLE_REMOTE;
grant execute on all functions in schema public to $ROLE_REMOTE;
alter default privileges for role $ROLE_LOCAL in schema public
grant all on tables to $ROLE_LOCAL;
alter default privileges for role $ROLE_LOCAL in schema public
grant all on sequences to $ROLE_LOCAL;
alter default privileges for role $ROLE_LOCAL in schema public
grant all on functions to $ROLE_LOCAL;
alter default privileges for role $ROLE_REMOTE in schema public
grant select, insert, update, delete on tables to $ROLE_REMOTE;
alter default privileges for role $ROLE_REMOTE in schema public
grant usage, select on sequences to $ROLE_REMOTE;
alter default privileges for role $ROLE_REMOTE in schema public
grant execute on functions to $ROLE_REMOTE;
# CTRL+D
If it's a static method, you can call it by using the class name in place of an object.
++ This worked for me. It's vanilla javascirpt
and good for use cases such as de-cluttering when testing with ngMocks
library:
<!-- specRunner.html - keep this at the top of your <script> asset loading so that it is available readily -->
<!-- Frienly tip - have all JSON files in a json-data folder for keeping things organized-->
<script src="json-data/findByIdResults.js" charset="utf-8"></script>
<script src="json-data/movieResults.js" charset="utf-8"></script>
This is your javascript
file that contains the JSON
data
// json-data/JSONFindByIdResults.js
var JSONFindByIdResults = {
"Title": "Star Wars",
"Year": "1983",
"Rated": "N/A",
"Released": "01 May 1983",
"Runtime": "N/A",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "N/A",
"Writer": "N/A",
"Actors": "Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones",
"Plot": "N/A",
"Language": "English",
"Country": "USA",
"Awards": "N/A",
"Poster": "N/A",
"Metascore": "N/A",
"imdbRating": "7.9",
"imdbVotes": "342",
"imdbID": "tt0251413",
"Type": "game",
"Response": "True"
};
Finally, work with the JSON data anywhere in your code
// working with JSON data in code
var findByIdResults = window.JSONFindByIdResults;
Note:- This is great for testing and even karma.conf.js
accepts these files for running tests as seen below. Also, I recommend this only for de-cluttering data and testing/development
environment.
// extract from karma.conf.js
files: [
'json-data/JSONSearchResultHardcodedData.js',
'json-data/JSONFindByIdResults.js'
...
]
Hope this helps.
++ Built on top of this answer https://stackoverflow.com/a/24378510/4742733
UPDATE
An easier way that worked for me is just include a function
at the bottom of the code returning whatever JSON
.
// within test code
let movies = getMovieSearchJSON();
.....
...
...
....
// way down below in the code
function getMovieSearchJSON() {
return {
"Title": "Bri Squared",
"Year": "2011",
"Rated": "N/A",
"Released": "N/A",
"Runtime": "N/A",
"Genre": "Comedy",
"Director": "Joy Gohring",
"Writer": "Briana Lane",
"Actors": "Brianne Davis, Briana Lane, Jorge Garcia, Gabriel Tigerman",
"Plot": "N/A",
"Language": "English",
"Country": "USA",
"Awards": "N/A",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjEzNDUxMDI4OV5BMl5BanBnXkFtZTcwMjE2MzczNQ@@._V1_SX300.jpg",
"Metascore": "N/A",
"imdbRating": "8.2",
"imdbVotes": "5",
"imdbID": "tt1937109",
"Type": "movie",
"Response": "True"
}
}
After=
dependency is only effective when service including After=
and service included by After=
are both scheduled to start as part of your boot up.
Ex:
a.service
[Unit]
After=b.service
This way, if both a.service
and b.service
are enabled, then systemd will order b.service
after a.service
.
If I am not misunderstanding, what you are asking is how to start b.service
when a.service
starts even though b.service
is not enabled.
The directive for this is Wants=
or Requires=
under [Unit]
.
website.service
[Unit]
Wants=mongodb.service
After=mongodb.service
The difference between Wants=
and Requires=
is that with Requires=
, a failure to start b.service
will cause the startup of a.service
to fail, whereas with Wants=
, a.service
will start even if b.service
fails. This is explained in detail on the man page of .unit
.
You can use sklearn.preprocessing.LabelBinarizer
:
Example:
import sklearn.preprocessing
a = [1,0,3]
label_binarizer = sklearn.preprocessing.LabelBinarizer()
label_binarizer.fit(range(max(a)+1))
b = label_binarizer.transform(a)
print('{0}'.format(b))
output:
[[0 1 0 0]
[1 0 0 0]
[0 0 0 1]]
Amongst other things, you may initialize sklearn.preprocessing.LabelBinarizer()
so that the output of transform
is sparse.
That's the for each loop syntax. It is looping through each object in the collection returned by objectListing.getObjectSummaries()
.
I just ran into this problem myself.
The fix I come out with was to go to the organizer, click on the "provisioning profiles" tab, and press refresh in the low corner.
You ll be asked to give your itunes connect password , just follow the instruction.
Hope it helps
Clearly HttpContext.Current
is not null
only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".
It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.
Overall, don't use Application["Setting"]
to store global stuffs, as they are not global as you discovered.
If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContext
or Application["Settings"]
, as that violates the principles of isolation and decoupling.
Update:
Due to the introduction of async/await
it is more often that such issues happen, so you might consider the following tip,
In general, you should only call HttpContext.Current
in only a few scenarios (within an HTTP module for example). In all other cases, you should use
Page.Context
https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.page.context?view=netframework-4.7.2 Controller.HttpContext
https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.controller.httpcontext?view=aspnet-mvc-5.2instead of HttpContext.Current
.
Try this :
<button> @Html.ActionLink(" ", "DeletePhoto", "PhotoAndVideo", new { id = item.Id }, new { @class = "modal-link1", @OnClick = "return confirm('Are you sure you to delete this Record?');" })</button>
Check out the documentation on boundary conditions:
http://java.sun.com/docs/books/tutorial/essential/regex/bounds.html
Check out this sample:
public static void main(final String[] args)
{
String x = "I found the value -12 in my string.";
System.err.println(Arrays.toString(x.split("\\b-?\\d+\\b")));
}
When you print it out, notice that the output is this:
[I found the value -, in my string.]
This means that the "-" character is not being picked up as being on the boundary of a word because it's not considered a word character. Looks like @brianary kinda beat me to the punch, so he gets an up-vote.
It seems you are connecting to the wrong database. R u sure "jdbc:postgresql://localhost/testDB"
will connect you to the actual datasource ?
Generally they are of the form "jdbc://hostname/databasename".
Look into Postgresql log file.
Firefox and Chrome are different
Chrome ignores the TR's background-color
Example: http://jsfiddle.net/T4NK3R/9SE4p/
<tr style="background-color:#F00">
<td style="background-color:#FFF; border-radius:20px">
</tr>
In FF the TD gets red corners, in Chrome not
You must use $rootScope to send and capture events between controllers in same app. Inject $rootScope dependency to your controllers. Here is a working example.
app.controller('firstCtrl', function($scope, $rootScope) {
function firstCtrl($scope) {
{
$rootScope.$emit('someEvent', [1,2,3]);
}
}
app.controller('secondCtrl', function($scope, $rootScope) {
function secondCtrl($scope)
{
$rootScope.$on('someEvent', function(event, data) { console.log(data); });
}
}
Events linked into $scope object just work in the owner controller. Communication between controllers is done via $rootScope or Services.
As all the other answers say; it can be almost anything but is usually "JQuery".
However, in ES6 it is a string interpolation operator in a template "literal" eg.
var s = "new" ; // you can put whatever you think appropriate here.
var s2 = `There are so many ${s} ideas these days !!` ; //back-ticks not quotes
console.log(s2) ;
result:
There are so many new ideas these days !!
In CellContentDoubleClick event fires only when double clicking on cell's content. I used this and works:
private void dgvUserList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show(e.RowIndex.ToString());
}
Use the below css
input[type="submit"] {_x000D_
font-size: 20px;_x000D_
background: pink;_x000D_
border: none;_x000D_
padding: 10px 20px;_x000D_
}_x000D_
.flat-btn {_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
appearance: none;_x000D_
border-radius: 0;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
margin: 25px 0 10px;_x000D_
font-size: 20px;_x000D_
}
_x000D_
<h2>iOS Styled Button!</h2>_x000D_
<input type="submit" value="iOS Styled Button!" />_x000D_
_x000D_
<h2>No More Style! Button!</h2>_x000D_
<input class="flat-btn" type="submit" value="No More Style! Button!" />
_x000D_
To check if the index is defined: isset($something['say'])
I'm going to assume your host is using C-Panel - and that it's probably HostGator or GoDaddy. In both cases they use C-Panel (in fact, a lot of hosts do) to make the Server administration as easy as possible on you, the end user. Even if you are hosting through someone else - see if you can log in to some kind of admin panel and find an .htaccess file that you can edit. (Note: The period before just means that it's a "hidden" file/directory).
Once you find the htaccess file add the following line:
Header set Access-Control-Allow-Origin "*"
Just to see if it works.
Warning: Do not use this line on a production serverIt should work. If not, call your host and ask them why the line isn't working - they'll probably be able to help you quickly from there.
*
to the address of the requesting domain http://cyclistinsuranceaustralia.com.au/
. You may find an issue with canonical addressing (including the www) and if so you may need to configure your host for a redirect. That's a different and smaller bridge to cross though. You'll at least be in the right place.What I would suggest is not converting the non-static class to a static class because in that case, your inner class can't access the non-static members of outer class.
Example :
class Outer
{
class Inner
{
//...
}
}
So, in such case, you can do something like:
Outer o = new Outer();
Outer.Inner obj = o.new Inner();
Go to Developer settings and check that for Debugging\Select App for Debugging is empty
git stash
to save your uncommited changesgit stash list
to list your saved uncommited stashesgit stash apply stash@{x}
where x can be 0,1,2..no of stashes that you have madeyou can do
square_list =[i**2 for i in start_list]
which returns
[25, 9, 1, 4, 16]
or, if the list already has values
square_list.extend([i**2 for i in start_list])
which results in a list that looks like:
[25, 9, 1, 4, 16]
Note: you don't want to do
square_list.append([i**2 for i in start_list])
as it literally adds a list to the original list, such as:
[_original_, _list_, _data_, [25, 9, 1, 4, 16]]
You may use the jquery's Contents method to get the content of the iframe.
That can happen if for some reason a x86 resource is loaded from a x64 machine. To avoid that explicitly, add this preprocessor directive to stdafx.h (of course, in my example the problematic resource is Windows Common Controls DLL.
#if defined(_WIN64)
#pragma comment(linker, "\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df'\"")
#endif
I figured out how to do this. I was building an application very similar to the example/tutorial you discussed in your original question.
Here's a snippet of the code that worked for me:
int pageSize = 4;
int pageNumber = (page ?? 1);
//Used the following two formulas so that it doesn't round down on the returned integer
decimal totalPages = ((decimal)(viewModel.Teachers.Count() /(decimal) pageSize));
ViewBag.TotalPages = Math.Ceiling(totalPages);
//These next two functions could maybe be reduced to one function....would require some testing and building
viewModel.Teachers = viewModel.Teachers.ToPagedList(pageNumber, pageSize);
ViewBag.OnePageofTeachers = viewModel.Teachers;
ViewBag.PageNumber = pageNumber;
return View(viewModel);
I added
using.PagedList;
to my controller as the tutorial states.
Now in my view my using statements etc at the top, NOTE i didnt change my using model statement.
@model CSHM.ViewModels.TeacherIndexData
@using PagedList;
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
and then at the bottom to build my paged list I used the following and it seems to work. I haven't yet built in the functionality for current sort, showing related data, filters, etc but i dont think it will be that difficult.
Page @ViewBag.PageNumber of @ViewBag.TotalPages
@Html.PagedListPager((IPagedList)ViewBag.OnePageofTeachers, page => Url.Action("Index", new { page }))
Hope that works for you. Let me know if it works!!
--- Shameless plug ---
I have added this function to a library I created
vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------
Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.
If you don't use jQuery
then the script would be something like this:
function posY(elm) {
var test = elm, top = 0;
while(!!test && test.tagName.toLowerCase() !== "body") {
top += test.offsetTop;
test = test.offsetParent;
}
return top;
}
function viewPortHeight() {
var de = document.documentElement;
if(!!window.innerWidth)
{ return window.innerHeight; }
else if( de && !isNaN(de.clientHeight) )
{ return de.clientHeight; }
return 0;
}
function scrollY() {
if( window.pageYOffset ) { return window.pageYOffset; }
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}
function checkvisible( elm ) {
var vpH = viewPortHeight(), // Viewport Height
st = scrollY(), // Scroll Top
y = posY(elm);
return (y > (vpH + st));
}
Using jQuery is a lot easier:
function checkVisible( elm, evalType ) {
evalType = evalType || "visible";
var vpH = $(window).height(), // Viewport Height
st = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
if (evalType === "above") return ((y < (vpH + st)));
}
This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.
See in action: http://jsfiddle.net/RJX5N/2/
I hope this answers your question.
-- IMPROVED VERSION--
This is a lot shorter and should do it as well:
function checkVisible(elm) {
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}
with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/
And a version with threshold
and mode
included:
function checkVisible(elm, threshold, mode) {
threshold = threshold || 0;
mode = mode || 'visible';
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
var above = rect.bottom - threshold < 0;
var below = rect.top - viewHeight + threshold >= 0;
return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}
and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/
The best way to generate the unique random number is
<?php
echo md5(uniqid(mt_rand(), true).microtime(true));
?>
You can use Expressions windows: while debugging, menu window -> Show View -> Expressions, then it has place to type variables of which you need to see contents
Xom has a Canonicalizer utility which turns your DOMs into a regular form, which you can then stringify and compare. So regardless of whitespace irregularities or attribute ordering, you can get regular, predictable comparisons of your documents.
This works especially well in IDEs that have dedicated visual String comparators, like Eclipse. You get a visual representation of the semantic differences between the documents.
Just adding this answer to help Google save some punter the hours I have spent to get here. I used ILMerge on my .Net 4.0 project, without the /targetplatform option set, assuming it would be detected correctly from my main assembly. I then had complaints from users only on Windows XP aka WinXP. This now makes sense as XP will never have > .Net 4.0 installed whereas most newer OSes will. So if your XP users are having issues, see the fixes above.
What I liked in the IDE was that I was able to write a few variables like:
private int id;
private string name;
private string version;
private string description;
private string status;
private string symbol;
Notice, that the variable names start with small letters, and then select the whole block, and press Ctrl+R, Ctrl+E, Apply. The properties are generated with the capital letter:
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
etc.
Don't waste your time, use this one line command to run command line as administrator:
echo createobject("shell.application").shellexecute "cmd.exe",,,"runas",1 > runas.vbs & start /wait runas.vbs & del /f runas.vbs
if you want to start any application with administrator privilege you will just write the hole path for this application like this notepad++ in my program files for example :
echo createobject("shell.application").shellexecute "%programfiles%\Notepad++\notepad++.exe",,,"runas",1 > runas.vbs & start /wait runas.vbs
You could use the INDIRECT function. This takes a string and converts it into a range
More info here
=INDIRECT("K"&A2)
But it's preferable to use INDEX as it is less volatile.
=INDEX(K:K,A2)
This returns a value or the reference to a value from within a table or range
More info here
Put either function into cell B2 and fill down.
What are the backgrounds for a switch-case to not accept this operator?
Because case
requires constant expression as its value. And since an ||
expression is not a compile time constant, it is not allowed.
From JLS Section 14.11:
Switch label should have following syntax:
SwitchLabel:
case ConstantExpression :
case EnumConstantName :
default :
The reason behind allowing just constant expression with cases can be understood from the JVM Spec Section 3.10 - Compiling Switches:
Compilation of switch statements uses the tableswitch and lookupswitch instructions. The tableswitch instruction is used when the cases of the switch can be efficiently represented as indices into a table of target offsets. The default target of the switch is used if the value of the expression of the switch falls outside the range of valid indices.
So, for the cases label to be used by tableswitch
as a index into the table of target offsets, the value of the case should be known at compile time. That is only possible if the case value is a constant expression. And ||
expression will be evaluated at runtime, and the value will only be available at that time.
From the same JVM section, the following switch-case
:
switch (i) {
case 0: return 0;
case 1: return 1;
case 2: return 2;
default: return -1;
}
is compiled to:
0 iload_1 // Push local variable 1 (argument i)
1 tableswitch 0 to 2: // Valid indices are 0 through 2 (NOTICE This instruction?)
0: 28 // If i is 0, continue at 28
1: 30 // If i is 1, continue at 30
2: 32 // If i is 2, continue at 32
default:34 // Otherwise, continue at 34
28 iconst_0 // i was 0; push int constant 0...
29 ireturn // ...and return it
30 iconst_1 // i was 1; push int constant 1...
31 ireturn // ...and return it
32 iconst_2 // i was 2; push int constant 2...
33 ireturn // ...and return it
34 iconst_m1 // otherwise push int constant -1...
35 ireturn // ...and return it
So, if the case
value is not a constant expressions, compiler won't be able to index it into the table of instruction pointers, using tableswitch
instruction.
I did some searching on the web, and this are some ways that I found:
The easiest way is using curve without predefined function
curve(x^2, from=1, to=50, , xlab="x", ylab="y")
You can also use curve when you have a predfined function
eq = function(x){x*x}
curve(eq, from=1, to=50, xlab="x", ylab="y")
If you want to use ggplot,
library("ggplot2")
eq = function(x){x*x}
ggplot(data.frame(x=c(1, 50)), aes(x=x)) +
stat_function(fun=eq)
The answer is CTRL + P (NOT CTRL + Q)
Someone else posted this answer on JetBrains forum: The idea is a different IDE. Try to discover its features and try to make the best of it, rather than trying to emulate whatever you used before. For the most part, Idea has very high usability (much better than Eclipse IMHO) and is streamlined for supporting code editing as best as possible (rather than relying on wizards too much for example).
... plus many more shortcuts to navigate in code and different idea views.
I think it rather nice that you can see just the specific bit of information you are interested in with a simple keystroke. Have a look at the menus which will also show the possibly modified shortcuts for your keymap.
0 Avatar Jens Voß Created June 12, 2008, 09:26 And, elsandros, in addition to what Stephen writes: Since you seem to be interested in IDEA's keyboard shortcuts, I highly recommend the "Key Promoter" plugin which helps you memorize the relevant shortcuts quickly.
Also very useful is the "Goto Action" feature, invoked by Ctrl-Shift-A. In the popup, you can enter a keyword (e.g. "Javadoc"), and the IDE tells you the available actions matching your search, along with keyboard shortcuts and the containing action groups (which often also give you a clue about how to navigate to the action using the menu).
Using of fgrep or adding -F option to grep could help. But for faster calculations you could use Awk.
You could try one of these Awk methods:
http://www.linuxquestions.org/questions/programming-9/grep-for-huge-files-826030/#post4066219
From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.
To execute more Maven builds from one script you shall use the Windows call function in the following way:
call mvn install:install-file -DgroupId=gdata -DartifactId=base -Dversion=1.0 -Dfile=gdata-base-1.0.jar -Dpackaging=jar -DgeneratePom=true
call mvn install:install-file -DgroupId=gdata -DartifactId=blogger -Dversion=2.0 -Dfile=gdata-blogger-2.0.jar -Dpackaging=jar -DgeneratePom=true
call mvn install:install-file -DgroupId=gdata -DartifactId=blogger-meta -Dversion=2.0 -Dfile=gdata-blogger-meta-2.0.jar -Dpackaging=jar -DgeneratePom=true
If you want just the Class names:
ActiveRecord::Base.descendants.map {|f| puts f}
Just run it in Rails console, nothing more. Good luck!
EDIT: @sj26 is right, you need to run this first before you can call descendants:
Rails.application.eager_load!
Break any number of loops by just one bool
variable see below :
bool check = true;
for (unsigned int i = 0; i < 50; i++)
{
for (unsigned int j = 0; j < 50; j++)
{
for (unsigned int k = 0; k < 50; k++)
{
//Some statement
if (condition)
{
check = false;
break;
}
}
if (!check)
{
break;
}
}
if (!check)
{
break;
}
}
In this code we break;
all the loops.
Here's the extension method way of doing it.
public static class Extensions
{
public static string ToDigitsOnly(this string input)
{
Regex digitsOnly = new Regex(@"[^\d]");
return digitsOnly.Replace(input, "");
}
}
Additionally if you want to know which extensions are available on your server: SELECT * FROM pg_available_extensions
Goto Windows Features on or Off . Enable All Features under Application Development Features and Refresh the IIS. Its Working
Old style using Resultset
@Transactional(readOnly=true)
public void accessUser() {
EntityManager em = this.getEntityManager();
org.hibernate.Session session = em.unwrap(org.hibernate.Session.class);
session.doWork(new Work() {
@Override
public void execute(Connection con) throws SQLException {
try (PreparedStatement stmt = con.prepareStatement(
"SELECT u.username, u.name, u.email, 'blabla' as passe, login_type as loginType FROM users u")) {
ResultSet rs = stmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.print(rsmd.getColumnName(i) + " (" + rsmd.getColumnTypeName(i) + ") / ");
}
System.out.println("");
while (rs.next()) {
System.out.println("Found username " + rs.getString("USERNAME") + " name " + rs.getString("NAME") + " email " + rs.getString("EMAIL") + " passe " + rs.getString("PASSE") + " email " + rs.getInt("LOGIN_TYPE"));
}
}
}
});
}
I am not a coder, but you could save a few lines:
<div>
<select onchange="if(selectedIndex!=0)document.getElementById('less_is_more').innerHTML=options[selectedIndex].value;">
<option value="">hire me for real estate</option>
<option value="me!!!">Who is a good Broker? </option>
<option value="yes!!!">Can I buy a house with no down payment</option>
<option value="send me a note!">Get my contact info?</option>
</select>
</div>
<div id="less_is_more"></div>
Here is demo.
This code works fine. There is definitely some other problem:
>>> str1 = "3158 reviews"
>>> print (re.findall('\d+', str1 ))
['3158']
If you want filter for one field:
label>Any: <input ng-model="search.color"></label> <br>
<tr ng-repeat="friendObj in friends | filter:search:strict">
If you want filter for all field:
label>Any: <input ng-model="search.$"></label> <br>
<tr ng-repeat="friendObj in friends | filter:search:strict">
and https://docs.angularjs.org/api/ng/filter/filter good for you
\d+
\d
represents any digit, +
for one or more. If you want to catch negative numbers as well you can use -?\d+
.
Note that as a string, it should be represented in C# as "\\d+"
, or @"\d+"
You can do this:
var $html = $('<iframe width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>'); _x000D_
var str = $html.prop('outerHTML');_x000D_
console.log(str);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
_x000D_
This worked for me
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(tag.equalsIgnoreCase("dashboard")){
DashboardFragment dashboardFragment = (DashboardFragment)
fragmentManager.findFragmentByTag("dashboard");
if(dashboardFragment!=null) ft.show(dashboardFragment);
ShowcaseFragment showcaseFragment = (ShowcaseFragment)
fragmentManager.findFragmentByTag("showcase");
if(showcaseFragment!=null) ft.hide(showcaseFragment);
} else if(tag.equalsIgnoreCase("showcase")){
DashboardFragment dashboardFragment = (DashboardFragment)
fragmentManager.findFragmentByTag("dashboard");
if(dashboardFragment!=null) ft.hide(dashboardFragment);
ShowcaseFragment showcaseFragment = (ShowcaseFragment)
fragmentManager.findFragmentByTag("showcase");
if(showcaseFragment!=null) ft.show(showcaseFragment);
}
ft.commit();
To increase uploading file's size limit we have two ways
1. IIS6 or lower
By default, in ASP.Net the maximum size of a file to be uploaded to the server is around 4MB. This value can be increased by modifying the maxRequestLength attribute in web.config.
Remember : maxRequestLenght is in KB
Example: if you want to restrict uploads to 15MB, set maxRequestLength to “15360” (15 x 1024).
<system.web>
<!-- maxRequestLength for asp.net, in KB -->
<httpRuntime maxRequestLength="15360" ></httpRuntime>
</system.web>
2. IIS7 or higher
A slight different way used here to upload files.IIS7 has introduced request filtering module.Which executed before ASP.Net.Means the way pipeline works is that the IIS value(maxAllowedContentLength) checked first then ASP.NET value(maxRequestLength) is checked.The maxAllowedContentLength attribute defaults to 28.61 MB.This value can be increased by modifying both attribute in same web.config.
Remember : maxAllowedContentLength is in bytes
Example : if you want to restrict uploads to 15MB, set maxRequestLength to “15360” and maxAllowedContentLength to "15728640" (15 x 1024 x 1024).
<system.web>
<!-- maxRequestLength for asp.net, in KB -->
<httpRuntime maxRequestLength="15360" ></httpRuntime>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- maxAllowedContentLength, for IIS, in bytes -->
<requestLimits maxAllowedContentLength="15728640" ></requestLimits>
</requestFiltering>
</security>
</system.webServer>
MSDN Reference link : https://msdn.microsoft.com/en-us/library/e1f13641(VS.80).aspx
What I do is to recognize everything, and when I have the text, I take out all the characters except numbers
//This replaces all except numbers from 0 to 9
recognizedText = recognizedText.replaceAll("[^0-9]+", " ");
This works pretty well for me.
A Magento Module is a group of directories containing blocks, controllers, helpers, and models that are needed to create a specific store feature. It is the unit of customization in the Magento platform. Magento Modules can be created to perform multiple functions with supporting logic to influence user experience and storefront appearance. It has a life cycle that allows them to be installed, deleted, or disabled. From the perspective of both merchants and extension developers, modules are the central unit of the Magento platform.
Declaration of Module
We have to declare the module by using the configuration file. As Magento 2 search for configuration module in etc directory of the module. So now we will create configuration file module.xml.
The code will look like this:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Cloudways_Mymodule" setup_version="1.0.0"></module> </config>
Registration of Module The module must be registered in the Magento 2 system by using Magento Component Registrar class. Now we will create the file registration.php in the module root directory:
app/code/Cloudways/Mymodule/registration.php
The Code will look like this:
?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Cloudways_Mymodule',
__DIR__
);
Check Module Status After following the steps above, we would have created a simple module. Now we are going to check the status of the module and whether it is enabled or disabled by using the following command line:
php bin/magento module:status
php bin/magento module:enable Cloudways_Mymodule
Share your feedback once you have gone through complete process
It works fine for me: http://jsfiddle.net/qwertynl/htb9h/
My javascript:
var app = angular.module("myApp", [])
app.controller("MyCtrl", ['$scope', function($scope) {
$scope.telephone = []; // << remember to set this
}]);
package-lock.json
: It contains the exact version details that is currently installed for your Application.
As explained in crti.o file missing , it's better to use "gcc -print-search-dirs" to find out all the search path. Then create a link as explain above "sudo ln -s" to point to the location of crt1.o
Maybe this would help:
String[] some_array = getResources().getStringArray(R.array.your_string_array)
So you get the array-list as a String[] and then choose any i, some_array[i].
Late GraveDig ... Just constrain your byte array to the file size.
FileInputStream fis = new FileInputStream( file );
byte[] byteArray= new byte[(int) file.length()];
I had same issue on 27 Sep 2019.
My API is in Dot net core Targeting to .net framework. edmx is in a different class library which is in .net framework only.
I observed that when I try to call that edmx from API .. for some reason I got that error.
What I did is, go to the obj folder of API and delete everything. then clean the API project and try again and that worked for me.
try
{
$conn = new PDO("sqlsrv:Server=$server_name;Database=$db_name;ConnectionPooling=0", "", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$e->getMessage();
}
\r
can do the work here for you.
Dive into python has a bit where he talks about what he calls the and-or trick, which seems like an effective way to cram complex logic into a single line.
Basically, it simulates the ternary operater in c, by giving you a way to test for truth and return a value based on that. For example:
>>> (1 and ["firstvalue"] or ["secondvalue"])[0]
"firstvalue"
>>> (0 and ["firstvalue"] or ["secondvalue"])[0]
"secondvalue"
I really needed this in C# and found Center MessageBox C#
Here's a nicely formatted version
using System;
using System.Windows.Forms;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;
public class MessageBoxEx
{
private static IWin32Window _owner;
private static HookProc _hookProc;
private static IntPtr _hHook;
public static DialogResult Show(string text)
{
Initialize();
return MessageBox.Show(text);
}
public static DialogResult Show(string text, string caption)
{
Initialize();
return MessageBox.Show(text, caption);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons)
{
Initialize();
return MessageBox.Show(text, caption, buttons);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon, defButton);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon, defButton, options);
}
public static DialogResult Show(IWin32Window owner, string text)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text);
}
public static DialogResult Show(IWin32Window owner, string text, string caption)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon, defButton);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options)
{
_owner = owner;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon,
defButton, options);
}
public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);
public const int WH_CALLWNDPROCRET = 12;
public enum CbtHookAction : int
{
HCBT_MOVESIZE = 0,
HCBT_MINMAX = 1,
HCBT_QS = 2,
HCBT_CREATEWND = 3,
HCBT_DESTROYWND = 4,
HCBT_ACTIVATE = 5,
HCBT_CLICKSKIPPED = 6,
HCBT_KEYSKIPPED = 7,
HCBT_SYSCOMMAND = 8,
HCBT_SETFOCUS = 9
}
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);
[DllImport("user32.dll")]
private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("User32.dll")]
public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);
[DllImport("User32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll")]
public static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll")]
public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
[DllImport("user32.dll")]
public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
[StructLayout(LayoutKind.Sequential)]
public struct CWPRETSTRUCT
{
public IntPtr lResult;
public IntPtr lParam;
public IntPtr wParam;
public uint message;
public IntPtr hwnd;
} ;
static MessageBoxEx()
{
_hookProc = new HookProc(MessageBoxHookProc);
_hHook = IntPtr.Zero;
}
private static void Initialize()
{
if (_hHook != IntPtr.Zero)
{
throw new NotSupportedException("multiple calls are not supported");
}
if (_owner != null)
{
_hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, _hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId());
}
}
private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode < 0)
{
return CallNextHookEx(_hHook, nCode, wParam, lParam);
}
CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
IntPtr hook = _hHook;
if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE)
{
try
{
CenterWindow(msg.hwnd);
}
finally
{
UnhookWindowsHookEx(_hHook);
_hHook = IntPtr.Zero;
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
private static void CenterWindow(IntPtr hChildWnd)
{
Rectangle recChild = new Rectangle(0, 0, 0, 0);
bool success = GetWindowRect(hChildWnd, ref recChild);
int width = recChild.Width - recChild.X;
int height = recChild.Height - recChild.Y;
Rectangle recParent = new Rectangle(0, 0, 0, 0);
success = GetWindowRect(_owner.Handle, ref recParent);
Point ptCenter = new Point(0, 0);
ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);
Point ptStart = new Point(0, 0);
ptStart.X = (ptCenter.X - (width / 2));
ptStart.Y = (ptCenter.Y - (height / 2));
ptStart.X = (ptStart.X < 0) ? 0 : ptStart.X;
ptStart.Y = (ptStart.Y < 0) ? 0 : ptStart.Y;
int result = MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width,
height, false);
}
}
yes you can use MapView in v2... for further details you can get help from this
https://gist.github.com/joshdholtz/4522551
SomeFragment.java
public class SomeFragment extends Fragment implements OnMapReadyCallback{
MapView mapView;
GoogleMap map;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.some_layout, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return v;
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
/*
//in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
*/
// Updates the location and zoom of the MapView
/*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);*/
map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(43.1, -87.9)));
}
@Override
public void onResume() {
mapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<permission
android:name="com.example.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your_key"/>
<activity
android:name=".HomeActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
some_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.gms.maps.MapView android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
just follow below steps:
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = false;
I was experiencing this error on Android 5.1.1
devices sending network requests using okhttp/4.0.0-RC1
. Setting header Content-Length: <sizeof response>
on the server side resolved the issue.