Inline
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" >
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<ul class="list-inline">
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li>
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">G+</a></li>
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">T</a></li>
</ul>
_x000D_
and learn more about https://getbootstrap.com/docs/4.0/content/typography/#inline
As in Oleg's answer, I believe the correct variable to set is CMAKE_RUNTIME_OUTPUT_DIRECTORY. We use the following in our root CMakeLists.txt:
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
You can also specify the output directories on a per-target basis:
set_target_properties( targets...
PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
In both cases you can append _[CONFIG]
to the variable/property name to make the output directory apply to a specific configuration (the standard values for configuration are DEBUG
, RELEASE
, MINSIZEREL
and RELWITHDEBINFO
).
Please note: for Bootstrap 4+ users, please consider Christophe's solution (Bootstrap 4 introduced flexbox, which provides for a more elegant CSS-only solution). The following will work for earlier versions of Bootstrap...
See http://jsfiddle.net/jhfrench/bAHfj/ for a working solution.
//for each element that is classed as 'pull-down', set its margin-top to the difference between its own height and the height of its parent
$('.pull-down').each(function() {
var $this = $(this);
$this.css('margin-top', $this.parent().height() - $this.height())
});
On the plus side:
pull-down
.Now the bad news:
You could try removing any alphanumeric characters and space. And then use -n
will give you the line number. Try following:
grep -vn "^[a-zA-Z0-9 ]*$" application.log
I finally solved the problem!!! You should first set the jre path to system variables by navigating to::
control panel > System and Security > System > Advanced system settings
Under System variables click on new
Variable name: KEY_PATH
Variable value: C:\Program Files (x86)\Java\jre1.8.0_171\bin
Where Variable value should be the path to your JDK's bin folder.
Then open command prompt and Change directory to the same JDK's bin folder like this
C:\Program Files (x86)\Java\jre1.8.0_171\bin
then paste,
keytool -list -v -keystore "C:\Users\user\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
NOTE: People are confusing jre and jdk. All I did applied strictly to jre
Here is an example that works with multibyte ( UTF-8 ) strings.
$str = 'äbcd';
// PHP 5.4.8 allows null as the third argument of mb_strpos() function
do {
$arr[] = mb_substr( $str, 0, 1, 'utf-8' );
} while ( $str = mb_substr( $str, 1, mb_strlen( $str ), 'utf-8' ) );
It can be also done with preg_split()
( preg_split( '//u', $str, null, PREG_SPLIT_NO_EMPTY )
), but unlike the above example, that runs almost as fast regardless of the size of the string, preg_split()
is fast with small strings, but a lot slower with large ones.
Just incase it helps anyone, I was getting this error because I forgot to unserialize a serialized array. That's definitely something I would check if it applies to your case.
I increase max memory to start node-chrome with -Xmx3g
, and it's work for me
Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)
public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:
Using ImageLocation property of the PictureBox like:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.ImageLocation = "../SamuderaJayaMotor.png";
pb1.SizeMode = PictureBoxSizeMode.AutoSize;
}
Using an image from the web like:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico";
pb1.SizeMode = PictureBoxSizeMode.AutoSize;
}
And please, be sure that "../SamuderaJayaMotor.png" is the correct path of the image that you are using.
You can assign an iterable to side_effect
, and the mock will return the next value in the sequence each time it is called:
>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'
Quoting the Mock()
documentation:
If side_effect is an iterable then each call to the mock will return the next value from the iterable.
Or in XML:
android:divider="@drawable/list_item_divider"
android:dividerHeight="1dp"
You can use a color for the drawable (e.g. #ff112233), but be aware, that pre-cupcake releases have a bug in which the color cannot be set. Instead a 9-patch or a image must be used..
A similar option to what was posted above by janderson would be so simply use the .GetAttribute method in selenium 2. Using this, you can grab any item that has a specific value or label that you are looking for. This can be used to determine if an element has a label, style, value, etc. A common way to do this is to loop through the items in the drop down until you find the one that you want and select it. In C#
int items = driver.FindElement(By.XPath("//path_to_drop_Down")).Count();
for(int i = 1; i <= items; i++)
{
string value = driver.FindElement(By.XPath("//path_to_drop_Down/option["+i+"]")).GetAttribute("Value1");
if(value.Conatains("Label_I_am_Looking_for"))
{
driver.FindElement(By.XPath("//path_to_drop_Down/option["+i+"]")).Click();
//Clicked on the index of the that has your label / value
}
}
Go to directory of your project
mkdir TestProject
cd TestProject
Make this directory a root of your project (this will create a default package.json
file)
npm init --yes
Install required npm module and save it as a project dependency (it will appear in package.json
)
npm install request --save
Create a test.js
file in project directory with code from package example
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body); // Print the google web page.
}
});
Your project directory should look like this
TestProject/
- node_modules/
- package.json
- test.js
Now just run node inside your project directory
node test.js
DECLARE @MyList TABLE (Value INT)
INSERT INTO @MyList VALUES (1)
INSERT INTO @MyList VALUES (2)
INSERT INTO @MyList VALUES (3)
INSERT INTO @MyList VALUES (4)
SELECT *
FROM MyTable
WHERE MyColumn IN (SELECT Value FROM @MyList)
In this Yahoo Developer Network (archived link) article it is suggested that if you absolutely must use a background-image instead of img element and alt attribute, use ARIA attributes as follows:
<div role="img" aria-label="adorable puppy playing on the grass">
...
</div>
The use case in the article describes how Flickr chose to use background images because performance was greatly improved on mobile devices.
First off, in a real application, you would never get database connection info in a servlet; you would configure it in your app server.
There are ways, however, of testing Servlets without having a container running. One is to use mock objects. Spring provides a set of very useful mocks for things like HttpServletRequest, HttpServletResponse, HttpServletSession, etc:
Using these mocks, you could test things like
What happens if username is not in the request?
What happens if username is in the request?
etc
You could then do stuff like:
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
public class MyServletTest {
private MyServlet servlet;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@Before
public void setUp() {
servlet = new MyServlet();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}
@Test
public void correctUsernameInRequest() throws ServletException, IOException {
request.addParameter("username", "scott");
request.addParameter("password", "tiger");
servlet.doPost(request, response);
assertEquals("text/html", response.getContentType());
// ... etc
}
}
At the place of uniqueIntNo
put unique integer number like this:
mNotificationManager.notify(uniqueIntNo, builder.build());
Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable
whereas
PHP FastCGI Process Manager (PHP-FPM) is an alternative FastCGI daemon for PHP that allows a website to handle strenuous loads. PHP-FPM maintains pools (workers that can respond to PHP requests) to accomplish this. PHP-FPM is faster than traditional CGI-based methods, such as SUPHP, for multi-user PHP environments
However, there are pros and cons to both and one should choose as per their specific use case.
I found info on this link for fastcgi vs fpm quite helpful in choosing which handler to use in my scenario.
string WordInBetween(string sentence, string wordOne, string wordTwo)
{
int start = sentence.IndexOf(wordOne) + wordOne.Length + 1;
int end = sentence.IndexOf(wordTwo) - start - 1;
return sentence.Substring(start, end);
}
Try it the other way:
var start_date = $("#fit_start_time").val(); //05-09-2013
var end_date = $("#fit_end_time").val(); //10-09-2013
var format='dd-MM-y';
var result= compareDates(start_date,format,end_date,format);
if(result==1)/// end date is less than start date
{
alert('End date should be greater than Start date');
}
OR:
if(new Date(start_date) >= new Date(end_date))
{
alert('End date should be greater than Start date');
}
Check out the documentation for numpy.sum
, paying particular attention to the axis
parameter. To sum over columns:
>>> import numpy as np
>>> a = np.arange(12).reshape(4,3)
>>> a.sum(axis=0)
array([18, 22, 26])
Or, to sum over rows:
>>> a.sum(axis=1)
array([ 3, 12, 21, 30])
Other aggregate functions, like numpy.mean
, numpy.cumsum
and numpy.std
, e.g., also take the axis
parameter.
From the Tentative Numpy Tutorial:
Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the
ndarray
class. By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying theaxis
parameter you can apply an operation along the specified axis of an array:
I've tied together a couple of the great examples above (thank you as always to Mr. Skeet and Mr. Karlsen) to include a couple of different Observables and utilized an interface to keep track of them in the Observer and allowed the Observer to to "observe" any number of Observables via an internal list:
namespace ObservablePattern
{
using System;
using System.Collections.Generic;
internal static class Program
{
private static void Main()
{
var observable = new Observable();
var anotherObservable = new AnotherObservable();
using (IObserver observer = new Observer(observable))
{
observable.DoSomething();
observer.Add(anotherObservable);
anotherObservable.DoSomething();
}
Console.ReadLine();
}
}
internal interface IObservable
{
event EventHandler SomethingHappened;
}
internal sealed class Observable : IObservable
{
public event EventHandler SomethingHappened;
public void DoSomething()
{
var handler = this.SomethingHappened;
Console.WriteLine("About to do something.");
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
internal sealed class AnotherObservable : IObservable
{
public event EventHandler SomethingHappened;
public void DoSomething()
{
var handler = this.SomethingHappened;
Console.WriteLine("About to do something different.");
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
internal interface IObserver : IDisposable
{
void Add(IObservable observable);
void Remove(IObservable observable);
}
internal sealed class Observer : IObserver
{
private readonly Lazy<IList<IObservable>> observables =
new Lazy<IList<IObservable>>(() => new List<IObservable>());
public Observer()
{
}
public Observer(IObservable observable) : this()
{
this.Add(observable);
}
public void Add(IObservable observable)
{
if (observable == null)
{
return;
}
lock (this.observables)
{
this.observables.Value.Add(observable);
observable.SomethingHappened += HandleEvent;
}
}
public void Remove(IObservable observable)
{
if (observable == null)
{
return;
}
lock (this.observables)
{
observable.SomethingHappened -= HandleEvent;
this.observables.Value.Remove(observable);
}
}
public void Dispose()
{
for (var i = this.observables.Value.Count - 1; i >= 0; i--)
{
this.Remove(this.observables.Value[i]);
}
}
private static void HandleEvent(object sender, EventArgs args)
{
Console.WriteLine("Something happened to " + sender);
}
}
}
Most likely npm package is missing. And sometimes npm install does not fix the problem.
I have faced the same and I have solved this issue by deleting the node_modules
folder and then npm install
In short: I don't think you can, but there seems to be a workaround:.
If you take a look into the Android Resource here:
http://developer.android.com/guide/topics/resources/string-resource.html
You see than under the array section (string array, at least), the "RESOURCE REFERENCE" (as you get from an XML) does not specify a way to address the individual items. You can even try in your XML to use "@array/yourarrayhere". I know that in design time you will get the first item. But that is of no practical use if you want to use, let's say... the second, of course.
HOWEVER, there is a trick you can do. See here:
Referencing an XML string in an XML Array (Android)
You can "cheat" (not really) the array definition by addressing independent strings INSIDE the definition of the array. For example, in your strings.xml:
<string name="earth">Earth</string>
<string name="moon">Moon</string>
<string-array name="system">
<item>@string/earth</item>
<item>@string/moon</item>
</string-array>
By using this, you can use "@string/earth" and "@string/moon" normally in your "android:text" and "android:title" XML fields, and yet you won't lose the ability to use the array definition for whatever purposes you intended in the first place.
Seems to work here on my Eclipse. Why don't you try and tell us if it works? :-)
A simple example to demonstrate the difference in speed when using String
concatenation vs StringBuilder
:
System.Diagnostics.Stopwatch time = new Stopwatch();
string test = string.Empty;
time.Start();
for (int i = 0; i < 100000; i++)
{
test += i;
}
time.Stop();
System.Console.WriteLine("Using String concatenation: " + time.ElapsedMilliseconds + " milliseconds");
Result:
Using String concatenation: 15423 milliseconds
StringBuilder test1 = new StringBuilder();
time.Reset();
time.Start();
for (int i = 0; i < 100000; i++)
{
test1.Append(i);
}
time.Stop();
System.Console.WriteLine("Using StringBuilder: " + time.ElapsedMilliseconds + " milliseconds");
Result:
Using StringBuilder: 10 milliseconds
As a result, the first iteration took 15423 ms while the second iteration using StringBuilder
took 10 ms.
It looks to me that using StringBuilder
is faster, a lot faster.
If you query a database and need the result set in JSON format it can be done like this:
<?php
$db = mysqli_connect("localhost","root","","mylogs");
//MSG
$query = "SELECT * FROM logs LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$rows[] = $row;
}
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);
mysqli_close($db);
?>
For help in parsing the result using jQuery take a look at this tutorial.
shift
can be used in places where you want to get the first element (index=0
) of an array and chain with other array methods.
example:
const comps = [{}, {}, {}]
const specComp = comps
.map(fn1)
.filter(fn2)
.shift()
Remember shift
mutates the array, which is very different from accessing via an indexer.
Use text-align:center !important
. There may be othertext-align
css rules so the !important
is important.
table,_x000D_
th,_x000D_
td {_x000D_
color: black !important;_x000D_
border-collapse: collapse;_x000D_
background-color: yellow !important;_x000D_
border: 1px solid black;_x000D_
padding: 10px;_x000D_
text-align: center !important;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<th>_x000D_
Center aligned text_x000D_
</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Center aligned text</td>_x000D_
<td>Center aligned text</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Just try
var file = $("#uploadedfile").prop("files")[0];
var fileName = file.name;
var fileSize = file.size;
alert("Uploading: "+fileName+" @ "+fileSize+"bytes");
It worked for me
Well, there's always the low tech solution of adding logging of the size of your maps when you modify them, then search the logs for which maps are growing beyond a reasonable size.
If you look at the inheritance tree (in version 2.6), HTMLParser
inherits from SGMLParser
which inherits from ParserBase
which doesn't inherits from object
. I.e. HTMLParser is an old-style class.
About your checking with isinstance
, I did a quick test in ipython:
In [1]: class A: ...: pass ...: In [2]: isinstance(A, object) Out[2]: True
Even if a class is old-style class, it's still an instance of object
.
For ASP.Net Core there is an easy solution if want to use the param directly in the controller method: Use the [FromHeader] annotation.
public JsonResult SendAsync([FromHeader] string myParam)
{
if(myParam == null) //Param not set in request header
{
return null;
}
return doSomething();
}
Additional Info: In my case the "myParam" had to be a string, int was always 0.
is only the matter of finding the dom where you want to insert the the text.
DEMO jsfiddle
$().text();
Use the Figure.savefig()
method, like so:
ax = s.hist() # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')
It doesn't have to end in pdf
, there are many options. Check out the documentation.
Alternatively, you can use the pyplot
interface and just call the savefig
as a function to save the most recently created figure:
import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf') # saves the current figure
/*This code will use gridview sum inside data list*/
SumOFdata(grd_DataDetail);
private void SumOFEPFWages(GridView grd)
{
Label lbl_TotAmt = (Label)grd.FooterRow.FindControl("lblTotGrossW");
/*Sum of the total Amount of the day*/
foreach (GridViewRow gvr in grd.Rows)
{
Label lbl_Amount = (Label)gvr.FindControl("lblGrossS");
lbl_TotAmt.Text = (Convert.ToDouble(lbl_Amount.Text) + Convert.ToDouble(lbl_TotAmt.Text)).ToString();
}
}
Short definition:
grep
: search for specific terms in a file
#usage
$ grep This file.txt
Every line containing "This"
Every line containing "This"
Every line containing "This"
Every line containing "This"
$ cat file.txt
Every line containing "This"
Every line containing "This"
Every line containing "That"
Every line containing "This"
Every line containing "This"
Now awk
and sed
are completly different than grep
.
awk
and sed
are text processors. Not only do they have the ability to find what you are looking for in text, they have the ability to remove, add and modify the text as well (and much more).
awk
is mostly used for data extraction and reporting. sed
is a stream editor
Each one of them has its own functionality and specialties.
Example
Sed
$ sed -i 's/cat/dog/' file.txt
# this will replace any occurrence of the characters 'cat' by 'dog'
Awk
$ awk '{print $2}' file.txt
# this will print the second column of file.txt
Basic awk
usage:
Compute sum/average/max/min/etc. what ever you may need.
$ cat file.txt
A 10
B 20
C 60
$ awk 'BEGIN {sum=0; count=0; OFS="\t"} {sum+=$2; count++} END {print "Average:", sum/count}' file.txt
Average: 30
I recommend that you read this book: Sed & Awk: 2nd Ed.
It will help you become a proficient sed/awk user on any unix-like environment.
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
All of the Func delegates take at least one parameter
That's not true. They all take at least one type argument, but that argument determines the return type.
So Func<T>
accepts no parameters and returns a value. Use Action
or Action<T>
when you don't want to return a value.
I had a similar issue and solved it with a patch to ec2.py and adding some configuration parameters to ec2.ini. The patch takes the value of ec2_key_name, prefixes it with the ssh_key_path, and adds the ssh_key_suffix to the end, and writes out ansible_ssh_private_key_file as this value.
The following variables have to be added to ec2.ini in a new 'ssh' section (this is optional if the defaults match your environment):
[ssh]
# Set the path and suffix for the ssh keys
ssh_key_path = ~/.ssh
ssh_key_suffix = .pem
Here is the patch for ec2.py:
204a205,206
> 'ssh_key_path': '~/.ssh',
> 'ssh_key_suffix': '.pem',
422a425,428
> # SSH key setup
> self.ssh_key_path = os.path.expanduser(config.get('ssh', 'ssh_key_path'))
> self.ssh_key_suffix = config.get('ssh', 'ssh_key_suffix')
>
1490a1497
> instance_vars["ansible_ssh_private_key_file"] = os.path.join(self.ssh_key_path, instance_vars["ec2_key_name"] + self.ssh_key_suffix)
When you installed XE.... it automatically created a database called "XE". You can use your login "system" and password that you set to login.
Key info
server: (you defined)
port: 1521
database: XE
username: system
password: (you defined)
Also Oracle is being difficult and not telling you easily create another database. You have to use SQL or another tool to create more database besides "XE".
I had the same problem and found it was caused by permission problems creating the user profile in C:\Users. I gave ApplicationPoolIdentity full permissions to the C:\Users folder, started the site and everything worked, the profile must have been created properly, and my site worked as it should. I then removed access to C:\Users from ApplicationPoolIdentity.
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
The below code snippet will help evaluate primitive type holding NaN.
double dbl = Double.NaN;
Double.valueOf(dbl).isNaN() ? true : false;
My question is: Why is not calling
return
faster
It’s faster because return
is a (primitive) function in R, which means that using it in code incurs the cost of a function call. Compare this to most other programming languages, where return
is a keyword, but not a function call: it doesn’t translate to any runtime code execution.
That said, calling a primitive function in this way is pretty fast in R, and calling return
incurs a minuscule overhead. This isn’t the argument for omitting return
.
or better, and thus preferable?
Because there’s no reason to use it.
Because it’s redundant, and it doesn’t add useful redundancy.
To be clear: redundancy can sometimes be useful. But most redundancy isn’t of this kind. Instead, it’s of the kind that adds visual clutter without adding information: it’s the programming equivalent of a filler word or chartjunk).
Consider the following example of an explanatory comment, which is universally recognised as bad redundancy because the comment merely paraphrases what the code already expresses:
# Add one to the result
result = x + 1
Using return
in R falls in the same category, because R is a functional programming language, and in R every function call has a value. This is a fundamental property of R. And once you see R code from the perspective that every expression (including every function call) has a value, the question then becomes: “why should I use return
?” There needs to be a positive reason, since the default is not to use it.
One such positive reason is to signal early exit from a function, say in a guard clause:
f = function (a, b) {
if (! precondition(a)) return() # same as `return(NULL)`!
calculation(b)
}
This is a valid, non-redundant use of return
. However, such guard clauses are rare in R compared to other languages, and since every expression has a value, a regular if
does not require return
:
sign = function (num) {
if (num > 0) {
1
} else if (num < 0) {
-1
} else {
0
}
}
We can even rewrite f
like this:
f = function (a, b) {
if (precondition(a)) calculation(b)
}
… where if (cond) expr
is the same as if (cond) expr else NULL
.
Finally, I’d like to forestall three common objections:
Some people argue that using return
adds clarity, because it signals “this function returns a value”. But as explained above, every function returns something in R. Thinking of return
as a marker of returning a value isn’t just redundant, it’s actively misleading.
Relatedly, the Zen of Python has a marvellous guideline that should always be followed:
Explicit is better than implicit.
How does dropping redundant return
not violate this? Because the return value of a function in a functional language is always explicit: it’s its last expression. This is again the same argument about explicitness vs redundancy.
In fact, if you want explicitness, use it to highlight the exception to the rule: mark functions that don’t return a meaningful value, which are only called for their side-effects (such as cat
). Except R has a better marker than return
for this case: invisible
. For instance, I would write
save_results = function (results, file) {
# … code that writes the results to a file …
invisible()
}
But what about long functions? Won’t it be easy to lose track of what is being returned?
Two answers: first, not really. The rule is clear: the last expression of a function is its value. There’s nothing to keep track of.
But more importantly, the problem in long functions isn’t the lack of explicit return
markers. It’s the length of the function. Long functions almost (?) always violate the single responsibility principle and even when they don’t they will benefit from being broken apart for readability.
From the api docs http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
Use the before_validation
method in your model, it gives you the options of creating specific initialisation for create and update calls
e.g. in this example (again code taken from the api docs example) the number field is initialised for a credit card. You can easily adapt this to set whatever values you want
class CreditCard < ActiveRecord::Base
# Strip everything but digits, so the user can specify "555 234 34" or
# "5552-3434" or both will mean "55523434"
before_validation(:on => :create) do
self.number = number.gsub(%r[^0-9]/, "") if attribute_present?("number")
end
end
class Subscription < ActiveRecord::Base
before_create :record_signup
private
def record_signup
self.signed_up_on = Date.today
end
end
class Firm < ActiveRecord::Base
# Destroys the associated clients and people when the firm is destroyed
before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" }
before_destroy { |record| Client.destroy_all "client_of = #{record.id}" }
end
Surprised that his has not been suggested here
A single css code on hover can do the trick:
box-shadow: inset 100px 0 0 0 #e0e0e0;
A complete demo can be found in my fiddle:
For me this solution works:
edittext.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
You can't.. You would have to know:
Maybe, just maybe if the object was optically tagged with for example a QR code, and you have a code-to-loc map...
You could extend the javascript Date object like this
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + parseInt(days));
return this;
};
and in your javascript code you could call
var currentDate = new Date();
// to add 4 days to current date
currentDate.addDays(4);
The following worked for me
const conString = "postgres://YourUserName:YourPassword@YourHostname:5432/YourDatabaseName";
If the optimizer says they are the same then consider the human factor. I prefer to see NOT EXISTS :)
sudo find / -name "pg_config" -print
The answer is /Library/PostgreSQL/9.1/bin/pg_config in my configuration (MAC Maverick)
A simple method of creating the service, adding headers and reading the JSON response,
private static void WebRequest()
{
const string WEBSERVICE_URL = "<<Web Service URL>>";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
Console.WriteLine(String.Format("Response: {0}", jsonResponse));
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
split doesn't work that way in groovy. you have to use tokenize...
See the docs:
<ListView android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:scrollbars="vertical"/>
You don't need to copy a Python string. They are immutable, and the copy
module always returns the original in such cases, as do str()
, the whole string slice, and concatenating with an empty string.
Moreover, your 'hello'
string is interned (certain strings are). Python deliberately tries to keep just the one copy, as that makes dictionary lookups faster.
One way you could work around this is to actually create a new string, then slice that string back to the original content:
>>> a = 'hello'
>>> b = (a + '.')[:-1]
>>> id(a), id(b)
(4435312528, 4435312432)
But all you are doing now is waste memory. It is not as if you can mutate these string objects in any way, after all.
If all you wanted to know is how much memory a Python object requires, use sys.getsizeof()
; it gives you the memory footprint of any Python object.
For containers this does not include the contents; you'd have to recurse into each container to calculate a total memory size:
>>> import sys
>>> a = 'hello'
>>> sys.getsizeof(a)
42
>>> b = {'foo': 'bar'}
>>> sys.getsizeof(b)
280
>>> sys.getsizeof(b) + sum(sys.getsizeof(k) + sys.getsizeof(v) for k, v in b.items())
360
You can then choose to use id()
tracking to take an actual memory footprint or to estimate a maximum footprint if objects were not cached and reused.
A new proposal to enhance SUDO for CygWin from GitHub in this thread, named TOUACExt:
Still in Pre-Beta, but seems to be working.
You can't.
function(){
function my_fun(){
/.. some operations ../
}
}
That is a closure. my_fun()
is defined only inside of that anonymous function. You can only call my_fun()
if you declare it at the correct level of scope, i.e., globally.
$(function () {/* something */})
is an IIFE, meaning it executes immediately when the DOM is ready. By declaring my_fun()
inside of that anonymous function, you prevent the rest of the script from "seeing" it.
Of course, if you want to run this function when the DOM has fully loaded, you should do the following:
function my_fun(){
/* some operations */
}
$(function(){
my_fun(); //run my_fun() ondomready
});
// just js
function js_fun(){
my_fun(); //== call my_fun() again
}
I use the following way to handle the many-to-many relationship where only foreign keys are involved.
So for inserting:
public void InsertStudentClass (long studentId, long classId)
{
using (var context = new DatabaseContext())
{
Student student = new Student { StudentID = studentId };
context.Students.Add(student);
context.Students.Attach(student);
Class class = new Class { ClassID = classId };
context.Classes.Add(class);
context.Classes.Attach(class);
student.Classes = new List<Class>();
student.Classes.Add(class);
context.SaveChanges();
}
}
For deleting,
public void DeleteStudentClass(long studentId, long classId)
{
Student student = context.Students.Include(x => x.Classes).Single(x => x.StudentID == studentId);
using (var context = new DatabaseContext())
{
context.Students.Attach(student);
Class classToDelete = student.Classes.Find(x => x.ClassID == classId);
if (classToDelete != null)
{
student.Classes.Remove(classToDelete);
context.SaveChanges();
}
}
}
If you want to get current directory path within a file for that you can magic constants __FILE__
and __DIR__
with plugin_dir_path()
function as:
$dir_path = plugin_dir_path( __FILE__ );
CurrentDirectory Path:
/home/user/var/www/wordpress_site/wp-content/plugins/custom-plugin/
__FILE__
magic constant returns current directory path.
If you want to one level up from the current directory. You should use __DIR__
magic constant as:
Current Path:
/home/user/var/www/wordpress_site/wp-content/plugins/custom-plugin/
$dir = plugin_dir_path( __DIR__ );
One level up path:
/home/user/var/www/wordpress_site/wp-content/plugins/
__DIR__
magic constant returns one level up directory path.
Boomerang may also be worth checking out.
Another open source tool for this is Cloud Query https://docs.cloudquery.io/
XAMPP only offers MySQL (Database Server) & Apache (Webserver) in one setup and you can manage them with the xampp starter.
After the successful installation navigate to your xampp folder and execute the xampp-control.exe
Press the start Button at the mysql row.
Now you've successfully started mysql. Now there are 2 different ways to administrate your mysql server and its databases.
But at first you have to set/change the MySQL Root password. Start the Apache server and type localhost
or 127.0.0.1
in your browser's address bar. If you haven't deleted anything from the htdocs folder the xampp status page appears. Navigate to security settings and change your mysql root password.
Now, you can browse to your phpmyadmin under http://localhost/phpmyadmin
or download a windows mysql client for example navicat lite or mysql workbench. Install it and log in to your mysql server with your new root password.
I totally chose another way for this method.
app.component.ts
import { Router } from '@angular/router';
export class AppComponent {
constructor(
private router: Router,
) {}
routerComment() {
this.router.navigateByUrl('/marketing/social/comment');
}
}
app.component.html
<button (click)="routerComment()">Router Link </button>
UPDATE: I am leaving this answer here as an example of how to use mouse events to use range/slider interactions in desktop (but not mobile) browsers. However, I have now also written a completely different and, I believe, better answer elsewhere on this page that uses a different approach to providing a cross-browser desktop-and-mobile solution to this problem.
Original answer:
Summary: A cross-browser, plain JavaScript (i.e. no-jQuery) solution to allow reading range input values without using on('input'...
and/or on('change'...
which work inconsistently between browsers.
As of today (late Feb, 2016), there is still browser inconsistency so I'm providing a new work-around here.
The problem: When using a range input, i.e. a slider, on('input'...
provides continuously updated range values in Mac and Windows Firefox, Chrome and Opera as well as Mac Safari, while on('change'...
only reports the range value upon mouse-up. In contrast, in Internet Explorer (v11), on('input'...
does not work at all, and on('change'...
is continuously updated.
I report here 2 strategies to get identical continuous range value reporting in all browsers using vanilla JavaScript (i.e. no jQuery) by using the mousedown, mousemove and (possibly) mouseup events.
Strategy 1: Shorter but less efficient
If you prefer shorter code over more efficient code, you can use this 1st solution which uses mousesdown and mousemove but not mouseup. This reads the slider as needed, but continues firing unnecessarily during any mouse-over events, even when the user has not clicked and is thus not dragging the slider. It essentially reads the range value both after 'mousedown' and during 'mousemove' events, slightly delaying each using requestAnimationFrame
.
var rng = document.querySelector("input");_x000D_
_x000D_
read("mousedown");_x000D_
read("mousemove");_x000D_
read("keydown"); // include this to also allow keyboard control_x000D_
_x000D_
function read(evtType) {_x000D_
rng.addEventListener(evtType, function() {_x000D_
window.requestAnimationFrame(function () {_x000D_
document.querySelector("div").innerHTML = rng.value;_x000D_
rng.setAttribute("aria-valuenow", rng.value); // include for accessibility_x000D_
});_x000D_
});_x000D_
}
_x000D_
<div>50</div><input type="range"/>
_x000D_
Strategy 2: Longer but more efficient
If you need more efficient code and can tolerate longer code length, then you can use the following solution which uses mousedown, mousemove and mouseup. This also reads the slider as needed, but appropriately stops reading it as soon as the mouse button is released. The essential difference is that is only starts listening for 'mousemove' after 'mousedown', and it stops listening for 'mousemove' after 'mouseup'.
var rng = document.querySelector("input");_x000D_
_x000D_
var listener = function() {_x000D_
window.requestAnimationFrame(function() {_x000D_
document.querySelector("div").innerHTML = rng.value;_x000D_
});_x000D_
};_x000D_
_x000D_
rng.addEventListener("mousedown", function() {_x000D_
listener();_x000D_
rng.addEventListener("mousemove", listener);_x000D_
});_x000D_
rng.addEventListener("mouseup", function() {_x000D_
rng.removeEventListener("mousemove", listener);_x000D_
});_x000D_
_x000D_
// include the following line to maintain accessibility_x000D_
// by allowing the listener to also be fired for_x000D_
// appropriate keyboard events_x000D_
rng.addEventListener("keydown", listener);
_x000D_
<div>50</div><input type="range"/>
_x000D_
Demo: Fuller explanation of the need for, and implementation of, the above work-arounds
The following code more fully demonstrates numerous aspects of this strategy. Explanations are embedded in the demonstration:
var select, inp, listen, unlisten, anim, show, onInp, onChg, onDn1, onDn2, onMv1, onMv2, onUp, onMvCombo1, onDnCombo1, onUpCombo2, onMvCombo2, onDnCombo2;_x000D_
_x000D_
select = function(selctr) { return document.querySelector(selctr); };_x000D_
inp = select("input");_x000D_
listen = function(evtTyp, cb) { return inp. addEventListener(evtTyp, cb); };_x000D_
unlisten = function(evtTyp, cb) { return inp.removeEventListener(evtTyp, cb); };_x000D_
anim = function(cb) { return window.requestAnimationFrame(cb); };_x000D_
show = function(id) {_x000D_
return function() {_x000D_
select("#" + id + " td~td~td" ).innerHTML = inp.value;_x000D_
select("#" + id + " td~td~td~td").innerHTML = (Math.random() * 1e20).toString(36); // random text_x000D_
};_x000D_
};_x000D_
_x000D_
onInp = show("inp" ) ;_x000D_
onChg = show("chg" ) ;_x000D_
onDn1 = show("mdn1") ;_x000D_
onDn2 = function() {anim(show("mdn2")); };_x000D_
onMv1 = show("mmv1") ;_x000D_
onMv2 = function() {anim(show("mmv2")); };_x000D_
onUp = show("mup" ) ;_x000D_
onMvCombo1 = function() {anim(show("cmb1")); };_x000D_
onDnCombo1 = function() {anim(show("cmb1")); listen("mousemove", onMvCombo1);};_x000D_
onUpCombo2 = function() { unlisten("mousemove", onMvCombo2);};_x000D_
onMvCombo2 = function() {anim(show("cmb2")); };_x000D_
onDnCombo2 = function() {anim(show("cmb2")); listen("mousemove", onMvCombo2);};_x000D_
_x000D_
listen("input" , onInp );_x000D_
listen("change" , onChg );_x000D_
listen("mousedown", onDn1 );_x000D_
listen("mousedown", onDn2 );_x000D_
listen("mousemove", onMv1 );_x000D_
listen("mousemove", onMv2 );_x000D_
listen("mouseup" , onUp );_x000D_
listen("mousedown", onDnCombo1);_x000D_
listen("mousedown", onDnCombo2);_x000D_
listen("mouseup" , onUpCombo2);
_x000D_
table {border-collapse: collapse; font: 10pt Courier;}_x000D_
th, td {border: solid black 1px; padding: 0 0.5em;}_x000D_
input {margin: 2em;}_x000D_
li {padding-bottom: 1em;}
_x000D_
<p>Click on 'Full page' to see the demonstration properly.</p>_x000D_
<table>_x000D_
<tr><th></th><th>event</th><th>range value</th><th>random update indicator</th></tr>_x000D_
<tr id="inp" ><td>A</td><td>input </td><td>100</td><td>-</td></tr>_x000D_
<tr id="chg" ><td>B</td><td>change </td><td>100</td><td>-</td></tr>_x000D_
<tr id="mdn1"><td>C</td><td>mousedown </td><td>100</td><td>-</td></tr>_x000D_
<tr id="mdn2"><td>D</td><td>mousedown using requestAnimationFrame</td><td>100</td><td>-</td></tr>_x000D_
<tr id="mmv1"><td>E</td><td>mousemove </td><td>100</td><td>-</td></tr>_x000D_
<tr id="mmv2"><td>F</td><td>mousemove using requestAnimationFrame</td><td>100</td><td>-</td></tr>_x000D_
<tr id="mup" ><td>G</td><td>mouseup </td><td>100</td><td>-</td></tr>_x000D_
<tr id="cmb1"><td>H</td><td>mousedown/move combo </td><td>100</td><td>-</td></tr>_x000D_
<tr id="cmb2"><td>I</td><td>mousedown/move/up combo </td><td>100</td><td>-</td></tr>_x000D_
</table>_x000D_
<input type="range" min="100" max="999" value="100"/>_x000D_
<ol>_x000D_
<li>The 'range value' column shows the value of the 'value' attribute of the range-type input, i.e. the slider. The 'random update indicator' column shows random text as an indicator of whether events are being actively fired and handled.</li>_x000D_
<li>To see browser differences between input and change event implementations, use the slider in different browsers and compare A and B.</li>_x000D_
<li>To see the importance of 'requestAnimationFrame' on 'mousedown', click a new location on the slider and compare C (incorrect) and D (correct).</li>_x000D_
<li>To see the importance of 'requestAnimationFrame' on 'mousemove', click and drag but do not release the slider, and compare E (often 1 pixel behind) and F (correct).</li>_x000D_
<li>To see why an initial mousedown is required (i.e. to see why mousemove alone is insufficient), click and hold but do not drag the slider and compare E (incorrect), F (incorrect) and H (correct).</li>_x000D_
<li>To see how the mouse event combinations can provide a work-around for continuous update of a range-type input, use the slider in any manner and note whichever of A or B continuously updates the range value in your current browser. Then, while still using the slider, note that H and I provide the same continuously updated range value readings as A or B.</li>_x000D_
<li>To see how the mouseup event reduces unnecessary calculations in the work-around, use the slider in any manner and compare H and I. They both provide correct range value readings. However, then ensure the mouse is released (i.e. not clicked) and move it over the slider without clicking and notice the ongoing updates in the third table column for H but not I.</li>_x000D_
</ol>
_x000D_
-------------------------------------------------------------------------
| +- | Shared(dynamic) | Static Library (Linkages) |
-------------------------------------------------------------------------
|Pros: | less memory use | an executable, using own libraries|
| | | ,coming with the program, |
| | | doesn't need to worry about its |
| | | compilebility subject to libraries|
-------------------------------------------------------------------------
|Cons: | implementations of | bigger memory uses |
| | libraries may be altered | |
| | subject to OS and its | |
| | version, which may affect| |
| | the compilebility and | |
| | runnability of the code | |
-------------------------------------------------------------------------
C++ is compiled into machine code. So you have the pre-processor, the compiler, the optimizer, and finally the assembler, all of which have to run.
Java and C# are compiled into byte-code/IL, and the Java virtual machine/.NET Framework execute (or JIT compile into machine code) prior to execution.
Python is an interpreted language that is also compiled into byte-code.
I'm sure there are other reasons for this as well, but in general, not having to compile to native machine language saves time.
you can use getline from a file using this code. this code will take a whole line from the file. and then you can use a while loop to go all lines while (ins);
ifstream ins(filename);
string s;
std::getline (ins,s);
Use the serialize method:
$.ajax({
...
data: $("#registerSubmit").serialize(),
...
})
Docs: serialize()
All the answers here suggest to use ipairs but beware, it does not work all the time.
t = {[2] = 44, [4]=77, [6]=88}
--This for loop prints the table
for key,value in next,t,nil do
print(key,value)
end
--This one does not print the table
for key,value in ipairs(t) do
print(key,value)
end
string[,] myGridData = new string[dataGridView1.Rows.Count,3];
int i = 0;
foreach(DataRow row in dataGridView1.Rows)
{
myGridData[i][0] = row.Cells[0].Value.ToString();
myGridData[i][1] = row.Cells[1].Value.ToString();
myGridData[i][2] = row.Cells[2].Value.ToString();
i++;
}
Hope this helps....
DataFrames and Series always have an index. Although it displays alongside the column(s), it is not a column, which is why del df['index']
did not work.
If you want to replace the index with simple sequential numbers, use df.reset_index()
.
To get a sense for why the index is there and how it is used, see e.g. 10 minutes to Pandas.
As Jon has the implementation details answer an other possible answer would be that the JVM doesn't want to handle write in record that have ended his activation.
Consider the use case where your lambdas instead of being apply, is stored in some place and run later.
I remember that in Smalltalk you would get an illegal store raised when you do such modification.
DateTime values should be inserted as if they are strings surrounded by single quotes
'20201231'
but in many cases they need to be casted explicitly to datetime CAST(N'20201231' AS DATETIME)
to avoid bad execution plans with CONVERSION_IMPLICIT warnings that affect negatively the performance. Hier is an example:
CREATE TABLE dbo.T(D DATETIME)
--wrong way
INSERT INTO dbo.T (D) VALUES ('20201231'), ('20201231')
--better way
INSERT INTO dbo.T (D) VALUES (CAST(N'20201231' AS DATETIME)), (CAST(N'20201231' AS DATETIME))
The full paramiko distribution ships with a lot of good demos.
In the demos subdirectory, demo.py
and interactive.py
have full interactive TTY examples which would probably be overkill for your situation.
In your example above ssh_stdin
acts like a standard Python file object, so ssh_stdin.write
should work so long as the channel is still open.
I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard stdin.write
method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the SSHClient.exec_command
method is implemented for all the gory details.
A really dumb answer (I'll vote myself down in a minute), but this worked for me:
After adding your pipe, if you're still getting the errors and are running your Angular site using "ng serve
", stop it... then start it up again.
For me, none of the other suggestions worked, but simply stopping, then restarting "ng serve
" was enough to make the error go away.
Strange.
This is the generic method that I use to convert any object that might be a DBNull.Value:
public static T ConvertDBNull<T>(object value, Func<object, T> conversionFunction)
{
return conversionFunction(value == DBNull.Value ? null : value);
}
usage:
var result = command.ExecuteScalar();
return result.ConvertDBNull(Convert.ToInt32);
shorter:
return command
.ExecuteScalar()
.ConvertDBNull(Convert.ToInt32);
I think you can use async void
for kicking off background operations as well, so long as you're careful to catch exceptions. Thoughts?
class Program {
static bool isFinished = false;
static void Main(string[] args) {
// Kick off the background operation and don't care about when it completes
BackgroundWork();
Console.WriteLine("Press enter when you're ready to stop the background operation.");
Console.ReadLine();
isFinished = true;
}
// Using async void to kickoff a background operation that nobody wants to be notified about when it completes.
static async void BackgroundWork() {
// It's important to catch exceptions so we don't crash the appliation.
try {
// This operation will end after ten interations or when the app closes. Whichever happens first.
for (var count = 1; count <= 10 && !isFinished; count++) {
await Task.Delay(1000);
Console.WriteLine($"{count} seconds of work elapsed.");
}
Console.WriteLine("Background operation came to an end.");
} catch (Exception x) {
Console.WriteLine("Caught exception:");
Console.WriteLine(x.ToString());
}
}
}
CountDownTimer waitTimer;
waitTimer = new CountDownTimer(60000, 300) {
public void onTick(long millisUntilFinished) {
//called every 300 milliseconds, which could be used to
//send messages or some other action
}
public void onFinish() {
//After 60000 milliseconds (60 sec) finish current
//if you would like to execute something when time finishes
}
}.start();
to stop the timer early:
if(waitTimer != null) {
waitTimer.cancel();
waitTimer = null;
}
<?php
exec('mysqldump --all-databases > /your/path/to/test.sql');
?>
You can extend the command with any options mysqldump takes ofcourse. Use man mysqldump
for more options (but I guess you knew that ;))
The raw_input() function reads a line from input (i.e. the user) and returns a string
Python v3.x as raw_input() was renamed to input()
PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).
You can also do it with a one liner with step support like this one:
((from, to, step) => ((add, arr, v) => add(arr, v, add))((arr, v, add) => v < to ? add(arr.concat([v]), v + step, add) : arr, [], from))(0, 10, 1)
The result is [0, 1, 2, 3, 4, 5, 6 ,7 ,8 ,9]
.
How about this
UPDATE table SET columnB = columnA;
This will update every row.
Acts like a spreadsheet as noted. Usually based on an event driven framework.
As with all "paradigms", it's newness is debatable.
From my experience of distributed flow networks of actors, it can easily fall prey to a general problem of state consistency across the network of nodes i.e. you end up with a lot of oscillation and trapping in strange loops.
This is hard to avoid as some semantics imply referential loops or broadcasting, and can be quite chaotic as the network of actors converges (or not) on some unpredictable state.
Similarly, some states may not be reached, despite having well-defined edges, because the global state steers away from the solution. 2+2 may or may not get to be 4 depending on when the 2's became 2, and whether they stayed that way. Spreadsheets have synchronous clocks and loop detection. Distributed actors generally don't.
All good fun :).
IPython has profiles for configuration, located at ~/.ipython/profile_*
. The default profile is called profile_default
. Within this folder there are two primary configuration files:
ipython_config.py
ipython_kernel_config.py
Add the inline option for matplotlib to ipython_kernel_config.py
:
c = get_config()
# ... Any other configurables you want to set
c.InteractiveShellApp.matplotlib = "inline"
Usage of %pylab
to get inline plotting is discouraged.
It introduces all sorts of gunk into your namespace that you just don't need.
%matplotlib
on the other hand enables inline plotting without injecting your namespace. You'll need to do explicit calls to get matplotlib and numpy imported.
import matplotlib.pyplot as plt
import numpy as np
The small price of typing out your imports explicitly should be completely overcome by the fact that you now have reproducible code.
with this code, the id will not appear on the link
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
You are not allowed to use the concatenation operator with the case statement. One possible solution is to use a variable within the process:
process(b0,b1,b2,b3)
variable bcat : std_logic_vector(0 to 3);
begin
bcat := b0 & b1 & b2 & b3;
case bcat is
when "0000" => x <= 1;
when others => x <= 2;
end case;
end process;
export PGPASSWORD=<password>
psql -h <host> -d <database> -U <user_name> -p <port> -a -w -f <file>.sql
The ideal situation for resolving conflicts is when you know ahead of time which way you want to resolve them and can pass the -Xours
or -Xtheirs
recursive merge strategy options. Outside of this I can see three scenarious:
To address these three scenarios you can add the following lines to your .gitconfig
file (or equivalent):
[merge]
conflictstyle = diff3
[mergetool.getours]
cmd = git-checkout --ours ${MERGED}
trustExitCode = true
[mergetool.mergeours]
cmd = git-merge-file --ours ${LOCAL} ${BASE} ${REMOTE} -p > ${MERGED}
trustExitCode = true
[mergetool.keepours]
cmd = sed -i '' -e '/^<<<<<<</d' -e '/^|||||||/,/^>>>>>>>/d' ${MERGED}
trustExitCode = true
[mergetool.gettheirs]
cmd = git-checkout --theirs ${MERGED}
trustExitCode = true
[mergetool.mergetheirs]
cmd = git-merge-file --theirs ${LOCAL} ${BASE} ${REMOTE} -p > ${MERGED}
trustExitCode = true
[mergetool.keeptheirs]
cmd = sed -i '' -e '/^<<<<<<</,/^=======/d' -e '/^>>>>>>>/d' ${MERGED}
trustExitCode = true
The get(ours|theirs)
tool just keeps the respective version of the file and throws away all of the changes from the other version (so no merging occurs).
The merge(ours|theirs)
tool re-does the three way merge from the local, base, and remote versions of the file, choosing to resolve conflicts in the given direction. This has some caveats, specifically: it ignores the diff options that were passed to the merge command (such as algorithm and whitespace handling); does the merge cleanly from the original files (so any manual changes to the file are discarded, which could be good or bad); and has the advantage that it cannot be confused by diff markers that are supposed to be in the file.
The keep(ours|theirs)
tool simply edits out the diff markers and enclosed sections, detecting them by regular expression. This has the advantage that it preserves the diff options from the merge command and allows you to resolve some conflicts by hand and then automatically resolve the rest. It has the disadvantage that if there are other conflict markers in the file it could get confused.
These are all used by running git mergetool -t (get|merge|keep)(ours|theirs) [<filename>]
where if <filename>
is not supplied it processes all conflicted files.
Generally speaking, assuming you know there are no diff markers to confuse the regular expression, the keep*
variants of the command are the most powerful. If you leave the mergetool.keepBackup
option unset or true then after the merge you can diff the *.orig
file against the result of the merge to check that it makes sense. As an example, I run the following after the mergetool
just to inspect the changes before committing:
for f in `find . -name '*.orig'`; do vimdiff $f ${f%.orig}; done
Note: If the merge.conflictstyle
is not diff3
then the /^|||||||/
pattern in the sed
rule needs to be /^=======/
instead.
HTML:
<button onclick="scrollToTop(1000);"></button>
1# JavaScript (linear):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const totalScrollDistance = document.scrollingElement.scrollTop;
let scrollY = totalScrollDistance, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollY will be -Infinity
scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = scrollY;
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
2# JavaScript (ease in and out):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const cosParameter = document.scrollingElement.scrollTop / 2;
let scrollCount = 0, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollCount will be Infinity
scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
/*
Explanation:
- pi is the length/end point of the cosinus intervall (see below)
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
(for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
- newTimestamp - oldTimestamp equals the delta time
a * cos (bx + c) + d | c translates along the x axis = 0
= a * cos (bx) + d | d translates along the y axis = 1 -> only positive y values
= a * cos (bx) + 1 | a stretches along the y axis = cosParameter = window.scrollY / 2
= cosParameter + cosParameter * (cos bx) | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
= cosParameter + cosParameter * (cos scrollCount * x)
*/
Note:
3# Simple scrolling library on Github
Each cell in the array is treated as unsigned int:
private int unsignedIntFromByteArray(byte[] bytes) {
int res = 0;
if (bytes == null)
return res;
for (int i=0;i<bytes.length;i++){
res = res | ((bytes[i] & 0xff) << i*8);
}
return res;
}
Just as on FYI to others suddenly experiencing this on an otherwise (previously) working Laravel installation:
My Laravel environment is on a Ubuntu VirtualBox hosted on a Win-10 laptop.
I used my phone to share Internet via USB and suddenly started experiencing this issue. I changed to using the phone as wireless hotspot and the issue went away. This is a nameserver/networking issue and is not specific to Laravel or MySQL.
In my case I took the code from React Native Android Docs I added the
+ <uses-permission tools:node="remove" android:name="android.permission.READ_PHONE_STATE" />
+ <uses-permission tools:node="remove" android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+ <uses-permission tools:node="remove" android:name="android.permission.READ_EXTERNAL_STORAGE" />
but forgot the part I should add to manifest
xmlns:tools="http://schemas.android.com/tools"
After I add problem solved. Think that there is someone miss the same line like me.
Have a nice day!
Use MouseClick event instead of Click
The HttpWebRequest modifies the CookieContainer assigned to it. There is no need to process returned cookies. Simply assign your cookie container to every web request.
public class CookieAwareWebClient : WebClient
{
public CookieContainer CookieContainer { get; set; } = new CookieContainer();
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest request = base.GetWebRequest(uri);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = CookieContainer;
}
return request;
}
}
You can use the Like
operator with a wildcard to determine whether a given substring exists in a string, for example:
If cell.Value Like "*Word1*" Then
'...
ElseIf cell.Value Like "*Word2*" Then
'...
End If
In this example the *
character in "*Word1*"
is a wildcard character which matches zero or more characters.
NOTE: The Like
operator is case-sensitive, so "Word1" Like "word1"
is false, more information can be found on this MSDN page.
I found that these instructions were not enough. I also had to search through the code files for models, controllers, and views as well as the AppStart files to change the namespace.
Since I was copying my project not just renaming it, I also had to go into the applicationhost.config for IIS express and recreate the bindings using different port numbers and change the physical directory as well.
All other answers sounds good, I would like to cover my case, where I had to make an animated LaunchScreen, then after 3 to 4 seconds of animation the next task was to move to Home screen. I tried segues, but that created problem for destination view. So at the end I accessed AppDelegates's Window property and I assigned a new NavigationController screen to it,
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let homeVC = storyboard.instantiateViewController(withIdentifier: "HomePageViewController") as! HomePageViewController
//Below's navigationController is useful if u want NavigationController in the destination View
let navigationController = UINavigationController(rootViewController: homeVC)
appDelegate.window!.rootViewController = navigationController
If incase, u don't want navigationController in the destination view then just assign as,
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let homeVC = storyboard.instantiateViewController(withIdentifier: "HomePageViewController") as! HomePageViewController
appDelegate.window!.rootViewController = homeVC
Just a heads up, while some of the answers posted here are correct (in a sense) one thing that you may need to do is go back to the root folder to delve down into the folder holding the image you want to set as the background. In other words, this code is correct in accomplishing your goal:
body {
background-image:url('images/background.png');
background-repeat:no-repeat;
background-attachment:fixed;
}
But you may also need to add a little more to the code, like this:
body {
background-image:url('../images/background.png');
background-repeat:no-repeat;
background-attachment:fixed;
}
The difference, as you can see, is that you may need to add “../” in front of the “images/background.png” call. This same rule also applies in HTML5 web pages. So if you are trying the first sample code listed here and you are still not getting the background image, try adding the “../” in front of “images”. Hope this helps .
I just did this for fun
>>> s = 'a,b,c,d'
>>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
['a,b,c', 'd']
Caution: Refer to the first comment in below where this answer can go wrong.
As an alternative to guava
one can use kotlin-stdlib
private Map<String, Choice> nameMap(List<Choice> choices) {
return CollectionsKt.associateBy(choices, Choice::getName);
}
Only first part of Justin's answer is correct. Using "%.3g" will not work for all cases as .3 is not the precision, but total number of digits. Try it for numbers like 1000.123 and it breaks.
So, I would use what Justin is suggesting:
>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'
You can easily create your own extension method on IEnumerable or IQueryable:
public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
bool descending)
{
return descending ? source.OrderByDescending(keySelector)
: source.OrderBy(keySelector);
}
public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>
(this IQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector,
bool descending)
{
return descending ? source.OrderByDescending(keySelector)
: source.OrderBy(keySelector);
}
Yes, you lose the ability to use a query expression here - but frankly I don't think you're actually benefiting from a query expression anyway in this case. Query expressions are great for complex things, but if you're only doing a single operation it's simpler to just put that one operation:
var query = dataList.OrderByWithDirection(x => x.Property, direction);
Try
Html
<div class="responsive-container">
<div class="img-container">
<IMG HERE>
</div>
</div>
CSS
.img-container {
position: absolute;
top: 0;
left: 0;
height:0;
padding-bottom:100%;
}
.img-container img {
width:100%;
}
I case that someone need a solution for this, this is one:
if you use a dynamic USE statement all your query need to be dynamic, because it need to be everything in the same context.
You can try with SYNONYM, is basically an ALIAS to a specific Table, this SYNONYM is inserted into the sys.synonyms table so you have access to it from any context
Look this static statement:
CREATE SYNONYM MASTER_SCHEMACOLUMNS FOR Master.INFORMATION_SCHEMA.COLUMNS
SELECT * FROM MASTER_SCHEMACOLUMNS
Now dynamic:
DECLARE @SQL VARCHAR(200)
DECLARE @CATALOG VARCHAR(200) = 'Master'
IF EXISTS(SELECT * FROM sys.synonyms s WHERE s.name = 'CURRENT_SCHEMACOLUMNS')
BEGIN
DROP SYNONYM CURRENT_SCHEMACOLUMNS
END
SELECT @SQL = 'CREATE SYNONYM CURRENT_SCHEMACOLUMNS FOR '+ @CATALOG +'.INFORMATION_SCHEMA.COLUMNS';
EXEC sp_sqlexec @SQL
--Your not dynamic Code
SELECT * FROM CURRENT_SCHEMACOLUMNS
Now just change the value of @CATALOG and you will be able to list the same table but from different catalog.
You can also use a callable in the default field, such as:
b = models.CharField(max_length=7, default=foo)
And then define the callable:
def foo():
return 'bar'
This feature has been added in dplyr v0.3. You can now pass a named character vector to the by
argument in left_join
(and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:
left_join(test_data, kantrowitz, by = c("first_name" = "name"))
If you style as list
I guess putting the second line in would also work, but requires human thinking for the content to flow properly, and, of course, hard line breaks (which don't bother me, per se).
You have to declare your functions before main()
(or declare the function prototypes before main()
)
As it is, the compiler sees my_print (my_string);
in main()
as a function declaration.
Move your functions above main()
in the file, or put:
void my_print (char *);
void my_print2 (char *);
Above main()
in the file.
Datetime is a module that allows for handling of dates, times and datetimes (all of which are datatypes). This means that datetime
is both a top-level module as well as being a type within that module. This is confusing.
Your error is probably based on the confusing naming of the module, and what either you or a module you're using has already imported.
>>> import datetime
>>> datetime
<module 'datetime' from '/usr/lib/python2.6/lib-dynload/datetime.so'>
>>> datetime.datetime(2001,5,1)
datetime.datetime(2001, 5, 1, 0, 0)
But, if you import datetime.datetime:
>>> from datetime import datetime
>>> datetime
<type 'datetime.datetime'>
>>> datetime.datetime(2001,5,1) # You shouldn't expect this to work
# as you imported the type, not the module
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
>>> datetime(2001,5,1)
datetime.datetime(2001, 5, 1, 0, 0)
I suspect you or one of the modules you're using has imported like this:
from datetime import datetime
.
You are reading the file right but the problem seems to be with the default encoding of System.out
. Try this to print the UTF-8
string-
PrintStream out = new PrintStream(System.out, true, "UTF-8");
out.println(str);
In code, you could do
ed_ins.setInputType(InputType.TYPE_CLASS_NUMBER);
Sounds like a job for set
with a custom IFS
.
IFS=-
set $STR
var1=$1
var2=$2
(You will want to do this in a function with a local IFS
so you don't mess up other parts of your script where you require IFS
to be what you expect.)
What I do is create a vertical block for the shadow, and place it next to where my block element should be. The two blocks are then wrapped into another block:
<div id="wrapper">
<div id="shadow"></div>
<div id="content">CONTENT</div>
</div>
<style>
div#wrapper {
width:200px;
height:258px;
}
div#wrapper > div#shadow {
display:inline-block;
width:1px;
height:100%;
box-shadow: -3px 0px 5px 0px rgba(0,0,0,0.8)
}
div#wrapper > div#content {
display:inline-block;
height:100%;
vertical-align:top;
}
</style>
jsFiddle example here.
Packages are just .xar archives with a different extension and a specified file hierarchy. Unfortunately, part of that file hierarchy is a cpio.gz archive of the actual installables, and usually that's what you want to edit. And there's also a Bom file that includes information on the files inside that cpio archive, and a PackageInfo file that includes summary information.
If you really do just need to edit one of the info files, that's simple:
mkdir Foo
cd Foo
xar -xf ../Foo.pkg
# edit stuff
xar -cf ../Foo-new.pkg *
But if you need to edit the installable files:
mkdir Foo
cd Foo
xar -xf ../Foo.pkg
cd foo.pkg
cat Payload | gunzip -dc |cpio -i
# edit Foo.app/*
rm Payload
find ./Foo.app | cpio -o | gzip -c > Payload
mkbom Foo.app Bom # or edit Bom
# edit PackageInfo
rm -rf Foo.app
cd ..
xar -cf ../Foo-new.pkg
I believe you can get mkbom (and lsbom) for most linux distros. (If you can get ditto, that makes things even easier, but I'm not sure if that's nearly as ubiquitously available.)
Which is better, a or b?
From a performance perspective, you'd have to measure it. (And in my opinion, if you can measure a difference, the compiler isn't very good).
From a maintenance perspective, b is better. Declare and initialize variables in the same place, in the narrowest scope possible. Don't leave a gaping hole between the declaration and the initialization, and don't pollute namespaces you don't need to.
try this:
select SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', '[email protected]' )),3,32)
You could use LINQ:
var checkedButton = container.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked);
Note that this requires that all of the radio buttons be directly in the same container (eg, Panel or Form), and that there is only one group in the container. If that is not the case, you could make List<RadioButton>
s in your constructor for each group, then write list.FirstOrDefault(r => r.Checked)
.
If you mess something up within a git rebase, e.g. git rebase --abort
, while you have uncommitted files, they will be lost and git reflog
will not help. This happened to me and you will need to think outside the box here. If you are lucky like me and use IntelliJ Webstorm then you can right-click->local history
and can revert to a previous state of your file/folders no matter what mistakes you have done with versioning software. It is always good to have another failsafe running.
Might help some else - I came here because I missed putting two // after http:. This is what I had:
http:/abc.my.domain.com:55555/update
Here's another way to do it. Some people will prefer this as the code is a bit cleaner. There are no %s
and a RESET
color to end the coloration.
#include <stdio.h>
#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"
#define RESET "\x1B[0m"
int main() {
printf(RED "red\n" RESET);
printf(GRN "green\n" RESET);
printf(YEL "yellow\n" RESET);
printf(BLU "blue\n" RESET);
printf(MAG "magenta\n" RESET);
printf(CYN "cyan\n" RESET);
printf(WHT "white\n" RESET);
return 0;
}
This program gives the following output:
This way, it's easy to do something like:
printf("This is " RED "red" RESET " and this is " BLU "blue" RESET "\n");
This line produces the following output:
You can do this by this way:
AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//set the text of TextView
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
yourSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
yourSpinner.setOnItemSelectedListener(listener);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
At first I create a listener and attributed to a variable callback; then i create a second listener anonymous and when this is called at a first time, this change the listener =]
Both ways:
Epoch to ISO time:
isoTime = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(epochTime))
ISO time to Epoch:
epochTime = time.mktime(time.strptime(isoTime, '%Y-%m-%dT%H:%M:%SZ'))
In Idea 17eap:
sout
: Prints
System.out.println();
soutm
: Prints current class and method names to System.out
System.out.println("$CLASS_NAME$.$METHOD_NAME$");
soutp
: Prints method parameter names and values to System.out
System.out.println($FORMAT$);
soutv
: Prints a value to System.out
System.out.println("$EXPR_COPY$ = " + $EXPR$);
The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.
If you want a list of columns of a certain type, you can use groupby
:
>>> df = pd.DataFrame([[1, 2.3456, 'c', 'd', 78]], columns=list("ABCDE"))
>>> df
A B C D E
0 1 2.3456 c d 78
[1 rows x 5 columns]
>>> df.dtypes
A int64
B float64
C object
D object
E int64
dtype: object
>>> g = df.columns.to_series().groupby(df.dtypes).groups
>>> g
{dtype('int64'): ['A', 'E'], dtype('float64'): ['B'], dtype('O'): ['C', 'D']}
>>> {k.name: v for k, v in g.items()}
{'object': ['C', 'D'], 'int64': ['A', 'E'], 'float64': ['B']}
You can by hardcoding the sequence, like so:
li, li + li + li, li + li + li + li + li {
background-color: black;
}
li + li, li + li + li + li {
background-color: white;
}
Similar to Bass, I had to also set the overflow-y. That could actually be done in the CSS
$('#myModal').on('show.bs.modal', function () {
$('.modal .modal-body').css('overflow-y', 'auto');
$('.modal .modal-body').css('max-height', $(window).height() * 0.7);
});
As of Json.NET 4.0 Release 1, there is native dynamic support.
You don't need to declare a class, just use dynamic
:
dynamic jsonDe = JsonConvert.DeserializeObject(json);
All the fields will be available:
foreach (string typeStr in jsonDe.Type[0])
{
// Do something with typeStr
}
string t = jsonDe.t;
bool a = jsonDe.a;
object[] data = jsonDe.data;
string[][] type = jsonDe.Type;
With dynamic you don't need to create a specific class to hold your data.
Dictionary<string, string> source
//
//functional programming - do not modify state - only create new state
Dictionary<string, string> result = source
.Where(kvp => string.Compare(kvp.Value, "two", true) != 0)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
//
// or you could modify state
List<string> keys = source
.Where(kvp => string.Compare(kvp.Value, "two", true) == 0)
.Select(kvp => kvp.Key)
.ToList();
foreach(string theKey in keys)
{
source.Remove(theKey);
}
can use it too
function getWindowSize()
{
var fontSize = parseInt($("body").css("fontSize"), 10);
var h = ($(window).height() / fontSize).toFixed(4);
var w = ($(window).width() / fontSize).toFixed(4);
var size = {
"height": h
,"width": w
};
return size;
}
function startResizeObserver()
{
//---------------------
var colFunc = {
"f10" : function(){ alert(10); }
,"f50" : function(){ alert(50); }
,"f100" : function(){ alert(100); }
,"f500" : function(){ alert(500); }
,"f1000" : function(){ alert(1000);}
};
//---------------------
$(window).resize(function() {
var sz = getWindowSize();
if(sz.width > 10){colFunc['f10']();}
if(sz.width > 50){colFunc['f50']();}
if(sz.width > 100){colFunc['f100']();}
if(sz.width > 500){colFunc['f500']();}
if(sz.width > 1000){colFunc['f1000']();}
});
}
$(document).ready(function()
{
startResizeObserver();
});
Looking at the screen from the top, you get x and z axis.
Looking at the screen from the side, you get y and z axis.
Calculate the focal lengths of the top and side views, using trigonometry, which is the distance between the eye and the middle of the screen, which is determined by the field of view of the screen. This makes the shape of two right triangles back to back.
hw = screen_width / 2
hh = screen_height / 2
fl_top = hw / tan(?/2)
fl_side = hh / tan(?/2)
Then take the average focal length.
fl_average = (fl_top + fl_side) / 2
Now calculate the new x and new y with basic arithmetic, since the larger right triangle made from the 3d point and the eye point is congruent with the smaller triangle made by the 2d point and the eye point.
x' = (x * fl_top) / (z + fl_top)
y' = (y * fl_top) / (z + fl_top)
Or you can simply set
x' = x / (z + 1)
and
y' = y / (z + 1)
I know the answers were correct at the time of asking the question - but since people (like me this minute) still happen to find them wondering why their WildFly 10 was behaving differently, I'd like to give an update for the current Hibernate 5.x version:
In the Hibernate 5.2 User Guide it is stated in chapter 11.2. Applying fetch strategies:
The Hibernate recommendation is to statically mark all associations lazy and to use dynamic fetching strategies for eagerness. This is unfortunately at odds with the JPA specification which defines that all one-to-one and many-to-one associations should be eagerly fetched by default. Hibernate, as a JPA provider, honors that default.
So Hibernate as well behaves like Ashish Agarwal stated above for JPA:
OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER
(see JPA 2.1 Spec)
For what it's worth, I had the same problem but it wasn't because of an extra semicolon, it was because I'd forgotten a semicolon on the previous statement.
My situation was something like
mynamespace::MyObject otherObject
for (const auto& element: otherObject.myVector) {
// execute arbitrary code on element
//...
//...
}
From this code, my compiler kept telling me:
error: expected unqualified-id before for (const auto& element: otherObject.myVector) {
etc...
which I'd taken to mean I'd writtten the for loop wrong. Nope! I'd simply forgotten a ;
after declaring otherObject
.
The theoretical limit may be 2,147,483,647, but the practical limit is nowhere near that. Since no single object in a .NET program may be over 2GB and the string type uses UTF-16 (2 bytes for each character), the best you could do is 1,073,741,823, but you're not likely to ever be able to allocate that on a 32-bit machine.
This is one of those situations where "If you have to ask, you're probably doing something wrong."
try this:
SELECT
COUNT(program_name) AS [Count],program_type AS [Type]
FROM (SELECT DISTINCT program_name,program_type
FROM cm_production
WHERE push_number=@push_number
) dt
GROUP BY program_type
You also have JFileUpload with SFTP add-on (Java too): http://www.jfileupload.com/products/sftp/index.html
To add on Tzot's and gns answers, here's an alternative way of copying files and folders recursively. (Python 3.X)
import os, shutil
root_src_dir = r'C:\MyMusic' #Path/Location of the source directory
root_dst_dir = 'D:MusicBackUp' #Path to the destination folder
for src_dir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for file_ in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file)
shutil.copy(src_file, dst_dir)
Should it be your first time and you have no idea how to copy files and folders recursively, I hope this helps.
I tried find similiar as topic first post.
For my needs I find this
http://answers.oreilly.com/topic/217-how-to-match-whole-words-with-a-regular-expression/
"\b[a-zA-Z0-9]{3}\b"
3 char words only "iokldöajf asd alkjwnkmd asd kja wwda da aij ednm <.jkakla "
I would suggest doing this in a more functional style :P
function CreateMessageboard(BoardMessages) {
var htmlMessageboardString = BoardMessages
.map(function(BoardMessage) {
return MessageToHTMLString(BoardMessage);
})
.join('');
}
Try this
<input type="radio" name="ans3" value="help">
<input type="radio" name="ans3" value="help1">
<input type="radio" name="ans3" value="help2">
<input type="radio" name="ans2" value="test">
<input type="radio" name="ans2" value="test1">
<input type="radio" name="ans2" value="test2">
<script type="text/javascript">
var ans3 = jq("input[name='ans3']:checked").val()
var ans2 = jq("input[name='ans2']:checked").val()
</script>
Try this code
select (DATEDIFF(DD,'2014-08-01','2014-08-14')+1)- (DATEDIFF(WK,'2014-08-01','2014-08-14')* 2)
I think you are confused about how the compiler puts things together. When you use -c
flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o
files thus don't mix with -c
, and compiler warns you about that. Symbols from object file are not moved to other object files like that.
All object files should be on the final linker invocation, which is not the case here, so linker (called via g++
front-end) complains about missing symbols.
Here's a small example (calling g++
explicitly for clarity):
PROG ?= myprog
OBJS = worker.o main.o
all: $(PROG)
.cpp.o:
g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<
$(PROG): $(OBJS)
g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)
There's also makedepend
utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M
gcc
option for building make
rules.
Why hasn't anyone suggested Activator.CreateInstance
?
http://msdn.microsoft.com/en-us/library/wccyzw83.aspx
T obj = (T)Activator.CreateInstance(typeof(T));
app.js
'use strict';
// Declare app level module which depends on filters, and services
var app= angular.module('myApp', ['ngRoute','angularUtils.directives.dirPagination','ngLoadingSpinner']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'loginCtrl'});
$routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'homeCtrl'});
$routeProvider.when('/salesnew', {templateUrl: 'partials/salesnew.html', controller: 'salesnewCtrl'});
$routeProvider.when('/salesview', {templateUrl: 'partials/salesview.html', controller: 'salesviewCtrl'});
$routeProvider.when('/users', {templateUrl: 'partials/users.html', controller: 'usersCtrl'});
$routeProvider.when('/forgot', {templateUrl: 'partials/forgot.html', controller: 'forgotCtrl'});
$routeProvider.otherwise({redirectTo: '/login'});
}]);
app.run(function($rootScope, $location, loginService){
var routespermission=['/home']; //route that require login
var salesnew=['/salesnew'];
var salesview=['/salesview'];
var users=['/users'];
$rootScope.$on('$routeChangeStart', function(){
if( routespermission.indexOf($location.path()) !=-1
|| salesview.indexOf($location.path()) !=-1
|| salesnew.indexOf($location.path()) !=-1
|| users.indexOf($location.path()) !=-1)
{
var connected=loginService.islogged();
connected.then(function(msg){
if(!msg.data)
{
$location.path('/login');
}
});
}
});
});
loginServices.js
'use strict';
app.factory('loginService',function($http, $location, sessionService){
return{
login:function(data,scope){
var $promise=$http.post('data/user.php',data); //send data to user.php
$promise.then(function(msg){
var uid=msg.data;
if(uid){
scope.msgtxt='Correct information';
sessionService.set('uid',uid);
$location.path('/home');
}
else {
scope.msgtxt='incorrect information';
$location.path('/login');
}
});
},
logout:function(){
sessionService.destroy('uid');
$location.path('/login');
},
islogged:function(){
var $checkSessionServer=$http.post('data/check_session.php');
return $checkSessionServer;
/*
if(sessionService.get('user')) return true;
else return false;
*/
}
}
});
sessionServices.js
'use strict';
app.factory('sessionService', ['$http', function($http){
return{
set:function(key,value){
return sessionStorage.setItem(key,value);
},
get:function(key){
return sessionStorage.getItem(key);
},
destroy:function(key){
$http.post('data/destroy_session.php');
return sessionStorage.removeItem(key);
}
};
}])
loginCtrl.js
'use strict';
app.controller('loginCtrl', ['$scope','loginService', function ($scope,loginService) {
$scope.msgtxt='';
$scope.login=function(data){
loginService.login(data,$scope); //call login service
};
}]);
Copy the .war file (E.g.: prj.war) to %CATALINA_HOME%\webapps
( E.g.: C:\tomcat\webapps )
Run %CATALINA_HOME%\bin\startup.bat
Your .war file will be extracted automatically to a folder that has the same name (without extension) (E.g.: prj)
Go to %CATALINA_HOME%\conf\server.xml
and take the port for the HTTP protocol. <Connector port="8080" ... />
. The default value is 8080.
Access the following URL:
[<protocol>://]localhost:<port>/folder/resourceName
(E.g.: localhost:8080/folder/resourceName
)
Don't try to access the URL without the resourceName
because it won't work if there is no file like index.html
, or if there is no url pattern like "/
" or "/*
" in web.xml.
The available main paths are here: [<protocol>://]localhost:<port>/manager/html
(E.g.: http://localhost:8080/manager/html
) and they have true
on the "Running" column.
Go to [<protocol>://]localhost:<port>/manager/html/
(usually localhost:8080/manager/html/
)
This is also achievable from [<protocol>://]localhost:<port>
> Manager App)
If you get:
403 Access Denied
go to %CATALINA_HOME%\conf\tomcat-users.xml
and check that you have enabled a line like this:
<user username="tomcat" password="tomcat" roles="tomcat,role1,manager-gui"/>
In the Deploy section, WAR file to deploy subsection, click on Browse....
Select the .war file (E.g.: prj.war) > click on Deploy.
try this
SET foreign_key_checks = 0;
ALTER TABLE sourcecodes_tags ADD FOREIGN KEY (sourcecode_id) REFERENCES sourcecodes (id) ON DELETE CASCADE ON UPDATE CASCADE
SET foreign_key_checks = 1;
Specifying the absolute path to the library should work fine:
g++ /my/dir/libfoo.so.0 ...
Did you remember to remove the -lfoo
once you added the absolute path?
Knowledge of high level programming languages (C/C++, Java, PHP, Python, Perl, etc.) would suggest to the layman that Bourne Again Shell (Bash) functions should work like they do in those other languages.
Instead, Bash functions work like shell commands and expect arguments to be passed to them in the same way one might pass an option to a shell command (e.g. ls -l
). In effect, function arguments in Bash are treated as positional parameters ($1, $2..$9, ${10}, ${11}
, and so on). This is no surprise considering how getopts
works. Do not use parentheses to call a function in Bash.
(Note: I happen to be working on OpenSolaris at the moment.)
# Bash style declaration for all you PHP/JavaScript junkies. :-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
function backupWebRoot ()
{
tar -cvf - "$1" | zip -n .jpg:.gif:.png "$2" - 2>> $errorlog &&
echo -e "\nTarball created!\n"
}
# sh style declaration for the purist in you. ;-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
backupWebRoot ()
{
tar -cvf - "$1" | zip -n .jpg:.gif:.png "$2" - 2>> $errorlog &&
echo -e "\nTarball created!\n"
}
# In the actual shell script
# $0 $1 $2
backupWebRoot ~/public/www/ webSite.tar.zip
Want to use names for variables? Just do something this.
local filename=$1 # The keyword declare can be used, but local is semantically more specific.
Be careful, though. If an argument to a function has a space in it, you may want to do this instead! Otherwise, $1
might not be what you think it is.
local filename="$1" # Just to be on the safe side. Although, if $1 was an integer, then what? Is that even possible? Humm.
Want to pass an array to a function?
callingSomeFunction "${someArray[@]}" # Expands to all array elements.
Inside the function, handle the arguments like this.
function callingSomeFunction ()
{
for value in "$@" # You want to use "$@" here, not "$*" !!!!!
do
:
done
}
Need to pass a value and an array, but still use "$@" inside the function?
function linearSearch ()
{
local myVar="$1"
shift 1 # Removes $1 from the parameter list
for value in "$@" # Represents the remaining parameters.
do
if [[ $value == $myVar ]]
then
echo -e "Found it!\t... after a while."
return 0
fi
done
return 1
}
linearSearch $someStringValue "${someArray[@]}"
If you have to use a distutils setup.py
script, there are some commandline options for forcing an installation destination. See http://docs.python.org/install/index.html#alternate-installation. If this problem repeats, you can setup a distutils configuration file, see http://docs.python.org/install/index.html#inst-config-files.
Setting the PYTHONPATH variable is described in tihos post.
No need to use static in this case as thoroughly explained. You might as well initialise your property without GetItem()
method, example of both below:
namespace MyNamespace
{
using System;
public class MyType
{
public string MyProperty { get; set; } = new string();
public static string MyStatic { get; set; } = "I'm static";
}
}
Consuming:
using MyType;
public class Somewhere
{
public void Consuming(){
// through instance of your type
var myObject = new MyType();
var alpha = myObject.MyProperty;
// through your type
var beta = MyType.MyStatic;
}
}
The server.contextPath or server.context-path works if
in pom.xml
Add following dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Tomcat/TC server -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
In eclipse, right click on project --> Run as --> Spring Boot App.
What's wrong with UNIX commands ? (given you're not working on Windows) :
ls | xargs cat | tee output.txt
does the job ( you can call it from python with subprocess if you want)
You can also use pathlib
.
from pathlib2 import Path
path = Path(file_to_search)
text = path.read_text()
text = text.replace(text_to_search, replacement_text)
path.write_text(text)
While I was having trouble join those two tables, I got away with doing exactly what I wanted by opening both remote databases at the same time. MySQL 5.6 (php 7.1) and the other MySQL 5.1 (php 5.6)
//Open a new connection to the MySQL server
$mysqli1 = new mysqli('server1','user1','password1','database1');
$mysqli2 = new mysqli('server2','user2','password2','database2');
//Output any connection error
if ($mysqli1->connect_error) {
die('Error : ('. $mysqli1->connect_errno .') '. $mysqli1->connect_error);
} else {
echo "DB1 open OK<br>";
}
if ($mysqli2->connect_error) {
die('Error : ('. $mysqli2->connect_errno .') '. $mysqli2->connect_error);
} else {
echo "DB2 open OK<br><br>";
}
If you get those two OKs on screen, then both databases are open and ready. Then you can proceed to do your querys.
$results = $mysqli1->query("SELECT * FROM video where video_id_old is NULL");
while($row = $results->fetch_array()) {
$theID = $row[0];
echo "Original ID : ".$theID." <br>";
$doInsert = $mysqli2->query("INSERT INTO video (...) VALUES (...)");
$doGetVideoID = $mysqli2->query("SELECT video_id, time_stamp from video where user_id = '".$row[13]."' and time_stamp = ".$row[28]." ");
while($row = $doGetVideoID->fetch_assoc()) {
echo "New video_id : ".$row["video_id"]." user_id : ".$row["user_id"]." time_stamp : ".$row["time_stamp"]."<br>";
$sql = "UPDATE video SET video_id_old = video_id, video_id = ".$row["video_id"]." where user_id = '".$row["user_id"]."' and video_id = ".$theID.";";
$sql .= "UPDATE video_audio SET video_id = ".$row["video_id"]." where video_id = ".$theID.";";
// Execute multi query if you want
if (mysqli_multi_query($mysqli1, $sql)) {
// Query successful do whatever...
}
}
}
// close connection
$mysqli1->close();
$mysqli2->close();
I was trying to do some joins but since I got those two DBs open, then I can go back and forth doing querys by just changing the connection $mysqli1
or $mysqli2
It worked for me, I hope it helps... Cheers
Once I had this problem after renaming a file. I renamed the file from within Xcode, but afterwards Xcode couldn't find the function in the file. Even a clean rebuild didn't fix the problem, but closing and then re-opening the project got the build to work.
There are good answers, but, in case that you have a ton of branches, deleting them one by one locally and remotely, would be a tedious tasks. You can use this script to automate these tasks.
branch_not_delete=( "master" "develop" "our-branch-1" "our-branch-2")
for branch in `git branch -a | grep remotes | grep -v HEAD | grep -v master`; do
# Delete prefix remotes/origin/ from branch name
branch_name="$(awk '{gsub("remotes/origin/", "");print}' <<< $branch)"
if ! [[ " ${branch_not_delete[*]} " == *" $branch_name "* ]]; then
# Delete branch remotly and locally
git push origin :$branch_name
fi
done
Source: Removing Git branches at once
Read line by line, not the whole file:
for line in open(file_name, 'rb'):
# process line here
Even better use with
for automatically closing the file:
with open(file_name, 'rb') as f:
for line in f:
# process line here
The above will read the file object using an iterator, one line at a time.
For the Single line and double line break here are the following codes.
Single break: %0D0A
Double break: %0D0A%0D0A
If you really do want to use wildcards to identify specific variables, then you can use a combination of ls()
and grep()
as follows:
l = ls()
vars.with.result <- l[grep("result", l)]
<ul class="icons-ul">
<li><i class="icon-play-sign"></i> <a>option</a></li>
<li><i class="icon-play-sign"></i> <a>option</a></li>
<li><i class="icon-play-sign"></i> <a>option</a></li>
<li><i class="icon-play-sign"></i> <a>option</a></li>
<li><i class="icon-play-sign"></i> <a>option</a></li>
</ul>
All the font awesome icons comes default with Bootstrap.
In C Pi is defined in math.h: #define M_PI 3.14159265358979323846
The standard MIME type is application/pdf
. The assignment is defined in RFC 3778, The application/pdf Media Type, referenced from the MIME Media Types registry.
MIME types are controlled by a standards body, The Internet Assigned Numbers Authority (IANA). This is the same organization that manages the root name servers and the IP address space.
The use of x-pdf
predates the standardization of the MIME type for PDF. MIME types in the x-
namespace are considered experimental, just as those in the vnd.
namespace are considered vendor-specific. x-pdf
might be used for compatibility with old software.
apt-get update
in the newly opened terminal.apt-get install
nano this will install nanocd ../opt/lampp/phpmyadmin
nano config.inc.php
and save.
In Bash (and ksh, zsh, dash, etc.), you can use parameter expansion with %
which will remove characters from the end of the string or #
which will remove characters from the beginning of the string. If you use a single one of those characters, the smallest matching string will be removed. If you double the character, the longest will be removed.
$ a='hello:world'
$ b=${a%:*}
$ echo "$b"
hello
$ a='hello:world:of:tomorrow'
$ echo "${a%:*}"
hello:world:of
$ echo "${a%%:*}"
hello
$ echo "${a#*:}"
world:of:tomorrow
$ echo "${a##*:}"
tomorrow
let arr1: boolean[] = [];
console.log(arr1[1]);
arr1.push(true);
To solve this issue you need to run your application by increasing the memory limit by using the option --max_old_space_size
. By default the memory limit of Node.js is 512 mb.
node --max_old_space_size=2000 server.js
Just use Instant
of java.time
.
System.out.println(Instant.now());
This just printed:
2018-01-27T09:35:23.179612Z
Instant.toString
always gives UTC time.
The output is usually sortable, but there are unfortunate exceptions. toString
gives you enough groups of three decimals to render the precision it holds. On the Java 9 on my Mac the precision of Instant.now()
seems to be microseconds, but we should expect that in approximately one case out of a thousand it will hit a whole number of milliseconds and print only three decimals. Strings with unequal numbers of decimals will be sorted in the wrong order (unless you write a custom comparator to take this into account).
Instant
is one of the classes in java.time
, the modern Java date and time API, which I warmly recommend that you use instead of the outdated Date
class. java.time
is built into Java 8 and later and has also been backported to Java 6 and 7.
if you don't like the double brackets or you don't want to write a function, you can just use a variable.
$path = Test-Path C:\Code
if (!$path) {
write "it doesn't exist!"
}
In Scala it is very comfortable with https://github.com/lloydmeta/enumeratum
Project is really good with examples and documentation
Just this example from their docs should makes you interested in
import enumeratum._
sealed trait Greeting extends EnumEntry
object Greeting extends Enum[Greeting] {
/*
`findValues` is a protected method that invokes a macro to find all `Greeting` object declarations inside an `Enum`
You use it to implement the `val values` member
*/
val values = findValues
case object Hello extends Greeting
case object GoodBye extends Greeting
case object Hi extends Greeting
case object Bye extends Greeting
}
// Object Greeting has a `withName(name: String)` method
Greeting.withName("Hello")
// => res0: Greeting = Hello
Greeting.withName("Haro")
// => java.lang.IllegalArgumentException: Haro is not a member of Enum (Hello, GoodBye, Hi, Bye)
// A safer alternative would be to use `withNameOption(name: String)` method which returns an Option[Greeting]
Greeting.withNameOption("Hello")
// => res1: Option[Greeting] = Some(Hello)
Greeting.withNameOption("Haro")
// => res2: Option[Greeting] = None
// It is also possible to use strings case insensitively
Greeting.withNameInsensitive("HeLLo")
// => res3: Greeting = Hello
Greeting.withNameInsensitiveOption("HeLLo")
// => res4: Option[Greeting] = Some(Hello)
// Uppercase-only strings may also be used
Greeting.withNameUppercaseOnly("HELLO")
// => res5: Greeting = Hello
Greeting.withNameUppercaseOnlyOption("HeLLo")
// => res6: Option[Greeting] = None
// Similarly, lowercase-only strings may also be used
Greeting.withNameLowercaseOnly("hello")
// => res7: Greeting = Hello
Greeting.withNameLowercaseOnlyOption("hello")
// => res8: Option[Greeting] = Some(Hello)
The problem with information_schema is that it can be terribly slow. It is faster to use the SHOW commands.
After you select the database you first send the query SHOW TABLES. And then you do SHOW COLUMNS for each of the tables.
In PHP that would look something like
$res = mysqli_query("SHOW TABLES"); while($row = mysqli_fetch_array($res)) { $rs2 = mysqli_query("SHOW COLUMNS FROM ".$row[0]); while($rw2 = mysqli_fetch_array($rs2)) { if($rw2[0] == $target) .... } }
A "quick and dirty" way is to use the find function and activate regular expressions.
Then just search for : \s for highlighting spaces \t for tabs \n for new-lines etc.
To clear only certain parameters, you can use:
[:param1, :param2, :param3].each { |k| session.delete(k) }
If CURLOPT_FAILONERROR
is false
, http errors will not trigger curl
errors.
<?php
if (@$_GET['curl']=="yes") {
header('HTTP/1.1 503 Service Temporarily Unavailable');
} else {
$ch=curl_init($url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."?curl=yes");
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$response=curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errno= curl_errno($ch);
if ($http_status==503)
echo "HTTP Status == 503 <br/>";
echo "Curl Errno returned $curl_errno <br/>";
}
One of the shortest ways is this, however as mentioned previously it can return the wrong cookie if there's similar names (MyCookie vs AnotherMyCookie):
var regex = /MyCookie=(.[^;]*)/ig;
var match = regex.exec(document.cookie);
var value = match[1];
I use this in a chrome extension so I know the name I'm setting, and I can make sure there won't be a duplicate, more or less.
The existing answers explain the problem well but if including your script files using or before requireJS is not an easy option due to legacy code a slightly hacky workaround is to remove require from the window scope before your script tag and then reinstate it afterwords. In our project this is wrapped behind a server-side function call but effectively the browser sees the following:
<script>
window.__define = window.define;
window.__require = window.require;
window.define = undefined;
window.require = undefined;
</script>
<script src="your-script-file.js"></script>
<script>
window.define = window.__define;
window.require = window.__require;
window.__define = undefined;
window.__require = undefined;
</script>
Not the neatest but seems to work and has saved a lot of refractoring.
You shouldn't. a Collection
avoids talking about indexes specifically because it might not make sense for the specific collection. For example, a List
implies some form of ordering, but a Set
does not.
Collection<String> myCollection = new HashSet<String>();
myCollection.add("Hello");
myCollection.add("World");
for (String elem : myCollection) {
System.out.println("elem = " + elem);
}
System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);
gives me:
elem = World
elem = Hello
myCollection.toArray()[0] = World
whilst:
myCollection = new ArrayList<String>();
myCollection.add("Hello");
myCollection.add("World");
for (String elem : myCollection) {
System.out.println("elem = " + elem);
}
System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);
gives me:
elem = Hello
elem = World
myCollection.toArray()[0] = Hello
Why do you want to do this? Could you not just iterate over the collection?
You can try one more thing.
Go to C:\Program Files (x86)\Android\android-sdk\tools>
, run adb kill-server
and then adb start-server
. This worked for me, and I do not know the reason :-).
Another Solution to isolate a character in a string
package main
import "fmt"
func main() {
var word string = "ZbjTS"
// P R I N T
fmt.Println(word)
yo := string([]rune(word)[0])
fmt.Println(yo)
//I N D E X
x :=0
for x < len(word){
yo := string([]rune(word)[x])
fmt.Println(yo)
x+=1
}
}
for string arrays also:
fmt.Println(string([]rune(sArray[0])[0]))
// = commented line
One way to do that is to use a counter:
ArrayList<Integer> list = new ArrayList<Integer>();
...
int size = list.size();
for (Integer i : list) {
...
if (--size == 0) {
// Last item.
...
}
}
Edit
Anyway, as Tom Hawtin said, it is sometimes better to use the "old" syntax when you need to get the current index information, by using a for
loop or the iterator
, as everything you win when using the Java5 syntax will be lost in the loop itself...
for (int i = 0; i < list.size(); i++) {
...
if (i == (list.size() - 1)) {
// Last item...
}
}
or
for (Iterator it = list.iterator(); it.hasNext(); ) {
...
if (!it.hasNext()) {
// Last item...
}
}
It can be done very easily in one step. You don't have to touch AndroidManifest. Instead do the following:
You could run the Dotnet CLI with full diagnostic verbosity to help find the issue.
dotnet run --verbosity diagnostic >> full_build.log
Once the build is complete you can search through the log file (full_build.log) for the error. Searching for "a conflict" for example, should take you right to the problem.
Following on from Sergey's answer, I think this more generic version is more in line with Fowler's Range
idea, and resolves some of the issues with that answer such as being able to have the Includes
methods within a generic class by constraining T
as IComparable<T>
. It's also immutable like what you would expect with types that extend the functionality of other value types like DateTime
.
public struct Range<T> where T : IComparable<T>
{
public Range(T start, T end)
{
Start = start;
End = end;
}
public T Start { get; }
public T End { get; }
public bool Includes(T value) => Start.CompareTo(value) <= 0 && End.CompareTo(value) >= 0;
public bool Includes(Range<T> range) => Start.CompareTo(range.Start) <= 0 && End.CompareTo(range.End) >= 0;
}
Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.
In contrast, JSTL works entirely with scoped attributes, either at page
, request
or session
scope. You need to rework your scriptlet to fish test
out as an attribute:
<c:set var="test" value="test1"/>
<%
String resp = "abc";
String test = pageContext.getAttribute("test");
resp = resp + test;
pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>
If you look at the docs for <c:set>
, you'll see you can specify scope
as page
, request
or session
, and it defaults to page
.
Better yet, don't use scriptlets at all: they make the baby jesus cry.
You can use File.ReadAllBytes()
method to read any file into byte array. To write byte array into file, just use File.WriteAllBytes()
method.
Hope this helps.
You can find more information and sample code here.
No need for external libs to bloat things - especially when working with Android. Here is a native solution that does the trick. This is a pice of code from an app that stores a byte array as an image file.
// Byte array with image data.
final byte[] imageData = params[0];
// Write bytes to tmp file.
final File tmpImageFile = new File(ApplicationContext.getInstance().getCacheDir(), "scan.jpg");
FileOutputStream tmpOutputStream = null;
try {
tmpOutputStream = new FileOutputStream(tmpImageFile);
tmpOutputStream.write(imageData);
Log.d(TAG, "File successfully written to tmp file");
}
catch (FileNotFoundException e) {
Log.e(TAG, "FileNotFoundException: " + e);
return null;
}
catch (IOException e) {
Log.e(TAG, "IOException: " + e);
return null;
}
finally {
if(tmpOutputStream != null)
try {
tmpOutputStream.close();
} catch (IOException e) {
Log.e(TAG, "IOException: " + e);
}
}
Perhaps you are looking for a context manager?
>>> class Foo(object):
... def __init__(self):
... self.bar = None
... def __enter__(self):
... if self.bar != 'open':
... print 'opening the bar'
... self.bar = 'open'
... def __exit__(self, type_, value, traceback):
... if self.bar != 'closed':
... print 'closing the bar', type_, value, traceback
... self.bar = 'close'
...
>>>
>>> with Foo() as f:
... # oh no something crashes the program
... sys.exit(0)
...
opening the bar
closing the bar <type 'exceptions.SystemExit'> 0 <traceback object at 0xb7720cfc>
Since .NET 3.0, you can simply use *yourElement*.TranslatePoint(new Point(0, 0), *theContainerOfYourChoice*)
.
This will give you the point 0, 0 of your button, but towards the container. (You can also give an other point that 0, 0)
Question: search for 'loom' excluding 'gloom'.
Answer:
grep -w 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp)
git commit -a -m "Your commit message here"
will quickly commit all changes with the commit message. Git commit "title" and "description" (as you call them) are nothing more than just the first line, and the rest of the lines in the commit message, usually separated by a blank line, by convention. So using this command will just commit the "title" and no description.
If you want to commit a longer message, you can do that, but it depends on which shell you use.
In bash the quick way would be:
git commit -a -m $'Commit title\n\nRest of commit message...'
A quick reset of the form fields is possible with this jQuery reset function.
$(selector)[0].reset();
I use package hyphenat
and then write compound words like Finnish word Internet-yhteys (Eng. Internet connection) as Internet\hyp yhteys
. Looks goofy but seems to be the most elegant way I've found.
I find this one useful in Oracle:
SELECT
obj.object_name,
atc.column_name,
atc.data_type,
atc.data_length
FROM
all_tab_columns atc,
(SELECT
*
FROM
all_objects
WHERE
object_name like 'GL_JE%'
AND owner = 'GL'
AND object_type in ('TABLE','VIEW')
) obj
WHERE
atc.table_name = obj.object_name
ORDER BY
obj.object_name,
atc.column_name;
What worked for me was using the $setSubmitted
function, which first shows up in the angular docs in version 1.3.20.
In the click event where I wanted to trigger the validation, I did the following:
vm.triggerSubmit = function() {
vm.homeForm.$setSubmitted();
...
}
That was all it took for me. According to the docs it "Sets the form to its submitted state." It's mentioned here.