Using the BaseName in Get-ChildItem displays the name of the file and and using Name displays the file name with the extension.
$filepath = Get-ChildItem "E:\Test\Basic-English-Grammar-1.pdf"
$filepath.BaseName
Basic-English-Grammar-1
$filepath.Name
Basic-English-Grammar-1.pdf
You can use FutureBuilder widget instead. This takes an argument which must be a Future. Then you can use a snapshot which is the state at the time being of the async call when loging in, once it ends the state of the async function return will be updated and the future builder will rebuild itself so you can then ask for the new state.
FutureBuilder(
future: myFutureFunction(),
builder: (context, AsyncSnapshot<List<item>> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
} else {
//Send the user to the next page.
},
);
Here you have an example on how to build a Future
Future<void> myFutureFunction() async{
await callToApi();}
Another thing to check is that if you have an "Entitlements" plist file for your debug mode (possibly because you're doing stuff with the Keychain), make sure that plist file has the "get-task-allow" = YES row. Without it, debugging and logging will be broken.
See this example in the MDN.
If you need to define multiple Errors (test the code here!):
function createErrorType(name, initFunction) {
function E(message) {
this.message = message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
else
this.stack = (new Error()).stack;
initFunction && initFunction.apply(this, arguments);
}
E.prototype = Object.create(Error.prototype);
E.prototype.name = name;
E.prototype.constructor = E;
return E;
}
var InvalidStateError = createErrorType(
'InvalidStateError',
function (invalidState, acceptedStates) {
this.message = 'The state ' + invalidState + ' is invalid. Expected ' + acceptedStates + '.';
});
var error = new InvalidStateError('foo', 'bar or baz');
function assert(condition) { if (!condition) throw new Error(); }
assert(error.message);
assert(error instanceof InvalidStateError);
assert(error instanceof Error);
assert(error.name == 'InvalidStateError');
assert(error.stack);
error.message;
Code is mostly copied from: What's a good way to extend Error in JavaScript?
In any sql server version you could use a variable for the total of all grades like this:
declare @countOfAll decimal(18, 4)
select @countOfAll = COUNT(*) from Grades
select
Grade, COUNT(*) / @countOfAll * 100
from Grades
group by Grade
You have a dictionary within a list. You must first extract the dictionary from the list and then process the items in the dictionary.
If your list contained multiple dictionaries and you wanted the value from each dictionary stored in a list as you have shown do this:
result_list = [[int(v) for k,v in d.items()] for d in qs]
Which is the same as:
result_list = []
for d in qs:
result_list.append([int(v) for k,v in d.items()])
The above will keep the values from each dictionary in their own separate list. If you just want all the values in one big list you can do this:
result_list = [int(v) for d in qs for k,v in d.items()]
Html.Hidden('name', 'value') creates a hidden tag with name = 'name' and value = 'value'.
Html.HiddenFor(x => x.nameProp) creates a hidden tag with a name = 'nameProp' and value = x.nameProp.
At face value these appear to do similar things, with one just more convenient than the other. But its actual value is for model binding. When MVC tries to associate the html to the model, it needs to have the name of the property, and for Html.Hidden, we chose 'name', and not 'nameProp', and thus the binding wouldn't work. You'd have to have a custom binding object, or get the values from the form data. If you are redisplaying the page, you'd have to set the model to the values again.
So you can use Html.Hidden, but if you get the name wrong, or if you change the property name in the model, the auto binding will fail when you submit the form. But by using a type checked expression, you'll get code completion, and when you change the property name, you will get a compile time error. And then you are guaranteed to have the correct name in the form.
One of the better features of MVC.
How about SymPy? Their solver looks like what you need. Have a look at their source code if you want to build the library yourself…
forever might be of interest to you. It will run your .js-File 24/7 with logging options. Here are two snippets from the help text:
[Long Running Process] The forever process will continue to run outputting log messages to the console. ex. forever -o out.log -e err.log my-script.js
and
[Daemon] The forever process will run as a daemon which will make the target process start in the background. This is extremely useful for remote starting simple node.js scripts without using nohup. It is recommended to run start with -o -l, & -e. ex. forever start -l forever.log -o out.log -e err.log my-daemon.js forever stop my-daemon.js
Actually this is better way to do that. If height: 100%
is used, the content goes off the border, but when it is 95%
everything is in order:
div#scrollable {
overflow-y: scroll;
height: 95%;
}
Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
First off, it's not JSON: JSON mandates that all keys must be strings.
Secondly, regular arrays do what you want:
var Game = {
status: [
[
"val",
"val",
"val"
],
[
"val",
"val",
"val"
]
}
will work, if you use Game.status[0][0]
. You cannot use numbers with the dot notation (.0
).
Alternatively, you can quote the numbers (i.e. { "0": "val" }...
); you will have plain objects instead of Arrays, but the same syntax will work.
In my application,above javascript function didnt work,because i had many procrosses inside one page.so following code worked for me hope it helps you guys.
function redirection()
{
<?php $send=$_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
window.location = redirect_to;
}
You can use CSS selectors in a way similar to the following:
p + ul {
margin-top: -10px;
}
This could be helpful because p + ul
means select any <ul>
element after a <p>
element.
You'll have to adapt this to how much padding or margin you have on your <p>
tags generally.
Original answer to original question:
p, ul {
padding: 0;
margin: 0;
}
That will take any EXTRA white space away.
p, ul {
display: inline;
}
That will make all the elements inline instead of blocks. (So, for instance, the <p>
won't cause a line break before and after it.)
In your destination field you want to use VLOOKUP like so:
=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)
VLOOKUP Arguments:
Autossh is best option - checking process is not working in all cases (e.g. zombie process, network related problems)
example:
autossh -M 2323 -c arcfour -f -N -L 8088:localhost:80 host2
textarea {
width: 700px;
height: 100px;
resize: none; }
assign your required width and height for the textarea and then use. resize: none ; css property which will disable the textarea's stretchable property.
if (CommonMethod.isNetworkAvailable(MainActivity.this)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
//showing dialog to select image
callFacebook();
Log.e("permission", "granted MarshMallow");
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}, 1);
}
} else {
Log.e("permission", "Not Required Less than MarshMallow Version");
callFacebook();
}
} else {
CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);
}
Isn't this the normal way to free the memory associated with an object?
This is a common way of managing dynamically allocated memory, but it's not a good way to do so. This sort of code is brittle because it is not exception-safe: if an exception is thrown between when you create the object and when you delete it, you will leak that object.
It is far better to use a smart pointer container, which you can use to get scope-bound resource management (it's more commonly called resource acquisition is initialization, or RAII).
As an example of automatic resource management:
void test()
{
std::auto_ptr<Object1> obj1(new Object1);
} // The object is automatically deleted when the scope ends.
Depending on your use case, auto_ptr
might not provide the semantics you need. In that case, you can consider using shared_ptr
.
As for why your program crashes when you delete the object, you have not given sufficient code for anyone to be able to answer that question with any certainty.
Among many others already covered in the many answers, I would highlight that SOAP enables to define a contract, the WSDL, which define the operations supported, complex types, etc. SOAP is oriented to operations, but REST is oriented at resources. Personally I would select SOAP for complex interfaces between internal enterprise applications, and REST for public, simpler, stateless interfaces with the outside world.
The problem is not in your code but in your json:
{"Compemployes":[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]}
this represents an object which contains a property Compemployes which is a list of Employee. In that case you should create that object like:
class EmployeList{
private List<Employe> compemployes;
(with getter an setter)
}
and to deserialize the json simply do:
EmployeList employeList = mapper.readValue(jsonString,EmployeList.class);
If your json should directly represent a list of employees it should look like:
[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]
Last remark:
List<Employee> list2 = mapper.readValue(jsonString,
TypeFactory.collectionType(List.class, Employee.class));
TypeFactory.collectionType
is deprecated you should now use something like:
List<Employee> list = mapper.readValue(jsonString,
TypeFactory.defaultInstance().constructCollectionType(List.class,
Employee.class));
I get this error whenever I mistakenly create a Python class using def
instead of class
:
def Foo():
def __init__(self, x):
self.x = x
# python thinks we're calling a function Foo which takes 0 args
a = Foo(x)
TypeError: Foo() takes 0 positional arguments but 1 was given
Oops!
just change these things in the .env file of your root folder.
DB_DATABASE=your_db_name
DB_USERNAME=your_db_user_name
DB_PASSWORD='your_db_password'
It worked for me.
This seems to take care of business pretty well. A fidde is here:
<label for="upload-file">A proper input label</label>
<div class="upload-button">
<div class="upload-cover">
Upload text or whatevers
</div>
<!-- this is later in the source so it'll be "on top" -->
<input name="upload-file" type="file" />
</div> <!-- .upload-button -->
/* first things first - get your box-model straight*/
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
label {
/* just positioning */
float: left;
margin-bottom: .5em;
}
.upload-button {
/* key */
position: relative;
overflow: hidden;
/* just positioning */
float: left;
clear: left;
}
.upload-cover {
/* basically just style this however you want - the overlaying file upload should spread out and fill whatever you turn this into */
background-color: gray;
text-align: center;
padding: .5em 1em;
border-radius: 2em;
border: 5px solid rgba(0,0,0,.1);
cursor: pointer;
}
.upload-button input[type="file"] {
display: block;
position: absolute;
top: 0; left: 0;
margin-left: -75px; /* gets that button with no-pointer-cursor off to the left and out of the way */
width: 200%; /* over compensates for the above - I would use calc or sass math if not here*/
height: 100%;
opacity: .2; /* left this here so you could see. Make it 0 */
cursor: pointer;
border: 1px solid red;
}
.upload-button:hover .upload-cover {
background-color: #f06;
}
The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:
var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
The code above depends on the nuget package RestSharp, which you can easily install.
You need to have the file /root/test/devenv/openstack-rhel/pom.xml
This file need to have the followings elements:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.openstack</groupId>
<artifactId>openstack-rhel-rpms</artifactId>
<version>2012.1-SNAPSHOT</version>
<packaging>pom</packaging>
</project>
Create your custom object and implement Serializable. Next, you can use intent.putExtra("package.name.example", <your-serializable-object>)
.
In the second activity, you read it using getIntent().getSerializableExtra("package.name.example")
This usually works as well :)
navigateUpTo(new Intent(getBaseContext(), MainActivity.class));
I think you can leverage the [Zip File System Provider][1] to achieve this. When using FileSystems.newFileSystem
it looks like you can treat the objects in that ZIP as a "regular" file.
In the linked documentation above:
Specify the configuration options for the zip file system in the java.util.Map object passed to the
FileSystems.newFileSystem
method. See the [Zip File System Properties][2] topic for information about the provider-specific configuration properties for the zip file system.Once you have an instance of a zip file system, you can invoke the methods of the [
java.nio.file.FileSystem
][3] and [java.nio.file.Path
][4] classes to perform operations such as copying, moving, and renaming files, as well as modifying file attributes.
The documentation for the jdk.zipfs
module in [Java 11 states][5]:
The zip file system provider treats a zip or JAR file as a file system and provides the ability to manipulate the contents of the file. The zip file system provider can be created by [
FileSystems.newFileSystem
][6] if installed.
Here is a contrived example I did using your example resources. Note that a .zip
is a .jar
, but you could adapt your code to instead use classpath resources:
Setup
cd /tmp
mkdir -p x/y/z
touch x/y/z/{a,b,c}.html
echo 'hello world' > x/y/z/d
zip -r example.zip x
Java
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.Collections;
import java.util.stream.Collectors;
public class MkobitZipRead {
public static void main(String[] args) throws IOException {
final URI uri = URI.create("jar:file:/tmp/example.zip");
try (
final FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.emptyMap());
) {
Files.walk(zipfs.getPath("/")).forEach(path -> System.out.println("Files in zip:" + path));
System.out.println("-----");
final String manifest = Files.readAllLines(
zipfs.getPath("x", "y", "z").resolve("d")
).stream().collect(Collectors.joining(System.lineSeparator()));
System.out.println(manifest);
}
}
}
Output
Files in zip:/
Files in zip:/x/
Files in zip:/x/y/
Files in zip:/x/y/z/
Files in zip:/x/y/z/c.html
Files in zip:/x/y/z/b.html
Files in zip:/x/y/z/a.html
Files in zip:/x/y/z/d
-----
hello world
In java 8, it's convenient to use the new date lib and getEpochSecond
method to get the timestamp (it's in second)
Instant.now().getEpochSecond();
The code below was tested on iPhone, iPad (iOS13), Safari (Catalina). It was able to autoplay the YouTube video on all devices. Make sure the video is muted and the playsinline parameter is on. Those are the magic parameters that make it work.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
</head>
<body>
<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
width: '100%',
videoId: 'osz5tVY97dQ',
playerVars: { 'autoplay': 1, 'playsinline': 1 },
events: {
'onReady': onPlayerReady
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.mute();
event.target.playVideo();
}
</script>
</body>
</html>
Check for applicationIdSuffix
in your app's build.gradle file. See if it is concatenating any text to your applicationId
. If so, remove it.
I think this does a good job of explaining.
The following is a UNION query that uses an ORDER BY clause:
select supplier_id, supplier_name
from suppliers
where supplier_id > 2000
UNION
select company_id, company_name
from companies
where company_id > 1000
ORDER BY 2;
Since the column names are different between the two "select" statements, it is more advantageous to reference the columns in the ORDER BY clause by their position in the result set.
In this example, we've sorted the results by supplier_name
/ company_name
in ascending order, as denoted by the "ORDER BY 2".
The supplier_name
/ company_name
fields are in position #2 in the
result set.
Taken from here: http://www.techonthenet.com/sql/union.php
I'm using this function that find all images in my letter and attaches it to the message.
Parameters: Takes your HTML (which you want to send);
Return: The necessary HTML and headers, which you can use in mail()
;
Example usage:
define("DEFCALLBACKMAIL", "[email protected]"); // WIll be shown as "from".
$final_msg = preparehtmlmail($html); // give a function your html*
mail('[email protected]', 'your subject', $final_msg['multipart'], $final_msg['headers']);
// send email with all images from html attached to letter
function preparehtmlmail($html) {
preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
$i = 0;
$paths = array();
foreach ($matches[1] as $img) {
$img_old = $img;
if(strpos($img, "http://") == false) {
$uri = parse_url($img);
$paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
$content_id = md5($img);
$html = str_replace($img_old,'cid:'.$content_id,$html);
$paths[$i++]['cid'] = $content_id;
}
}
$boundary = "--".md5(uniqid(time()));
$headers .= "MIME-Version: 1.0\n";
$headers .="Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
$headers .= "From: ".DEFCALLBACKMAIL."\r\n";
$multipart = '';
$multipart .= "--$boundary\n";
$kod = 'utf-8';
$multipart .= "Content-Type: text/html; charset=$kod\n";
$multipart .= "Content-Transfer-Encoding: Quot-Printed\n\n";
$multipart .= "$html\n\n";
foreach ($paths as $path) {
if(file_exists($path['path']))
$fp = fopen($path['path'],"r");
if (!$fp) {
return false;
}
$imagetype = substr(strrchr($path['path'], '.' ),1);
$file = fread($fp, filesize($path['path']));
fclose($fp);
$message_part = "";
switch ($imagetype) {
case 'png':
case 'PNG':
$message_part .= "Content-Type: image/png";
break;
case 'jpg':
case 'jpeg':
case 'JPG':
case 'JPEG':
$message_part .= "Content-Type: image/jpeg";
break;
case 'gif':
case 'GIF':
$message_part .= "Content-Type: image/gif";
break;
}
$message_part .= "; file_name = \"$path\"\n";
$message_part .= 'Content-ID: <'.$path['cid'].">\n";
$message_part .= "Content-Transfer-Encoding: base64\n";
$message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
$message_part .= chunk_split(base64_encode($file))."\n";
$multipart .= "--$boundary\n".$message_part."\n";
}
$multipart .= "--$boundary--\n";
return array('multipart' => $multipart, 'headers' => $headers);
}
preferredLayoutAttributesFittingAttributes
renamed to preferredLayoutAttributesFitting
and use auto sizing
systemLayoutSizeFittingSize
renamed to systemLayoutSizeFitting
After seeing my GitHub solution break under iOS 9 I finally got the time to investigate the issue fully. I have now updated the repo to include several examples of different configurations for self sizing cells. My conclusion is that self sizing cells are great in theory but messy in practice. A word of caution when proceeding with self sizing cells.
TL;DR
Check out my GitHub project
Self sizing cells are only supported with flow layout so make sure thats what you are using.
There are two things you need to setup for self sizing cells to work.
estimatedItemSize
on UICollectionViewFlowLayout
Flow layout will become dynamic in nature once you set the estimatedItemSize
property.
self.flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
This comes in 2 flavours; Auto-Layout or custom override of preferredLayoutAttributesFittingAttributes
.
I won't go to in to detail about this as there's a brilliant SO post about configuring constraints for a cell. Just be wary that Xcode 6 broke a bunch of stuff with iOS 7 so, if you support iOS 7, you will need to do stuff like ensure the autoresizingMask is set on the cell's contentView and that the contentView's bounds is set as the cell's bounds when the cell is loaded (i.e. awakeFromNib
).
Things you do need to be aware of is that your cell needs to be more seriously constrained than a Table View Cell. For instance, if you want your width to be dynamic then your cell needs a height constraint. Likewise, if you want the height to be dynamic then you will need a width constraint to your cell.
preferredLayoutAttributesFittingAttributes
in your custom cellWhen this function is called your view has already been configured with content (i.e. cellForItem
has been called). Assuming your constraints have been appropriately set you could have an implementation like this:
//forces the system to do one layout pass
var isHeightCalculated: Bool = false
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
//Exhibit A - We need to cache our calculation to prevent a crash.
if !isHeightCalculated {
setNeedsLayout()
layoutIfNeeded()
let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
var newFrame = layoutAttributes.frame
newFrame.size.width = CGFloat(ceilf(Float(size.width)))
layoutAttributes.frame = newFrame
isHeightCalculated = true
}
return layoutAttributes
}
NOTE On iOS 9 the behaviour changed a bit that could cause crashes on your implementation if you are not careful (See more here). When you implement preferredLayoutAttributesFittingAttributes
you need to ensure that you only change the frame of your layout attributes once. If you don't do this the layout will call your implementation indefinitely and eventually crash. One solution is to cache the calculated size in your cell and invalidate this anytime you reuse the cell or change its content as I have done with the isHeightCalculated
property.
At this point you should have 'functioning' dynamic cells in your collectionView. I haven't yet found the out-of-the box solution sufficient during my tests so feel free to comment if you have. It still feels like UITableView
wins the battle for dynamic sizing IMHO.
Be very mindful that if you are using prototype cells to calculate the estimatedItemSize - this will break if your XIB uses size classes. The reason for this is that when you load your cell from a XIB its size class will be configured with Undefined
. This will only be broken on iOS 8 and up since on iOS 7 the size class will be loaded based on the device (iPad = Regular-Any, iPhone = Compact-Any). You can either set the estimatedItemSize without loading the XIB, or you can load the cell from the XIB, add it to the collectionView (this will set the traitCollection), perform the layout, and then remove it from the superview. Alternatively you could also make your cell override the traitCollection
getter and return the appropriate traits. It's up to you.
Let me know if I missed anything, hope I helped and good luck coding
It is better to remove NodeJS and its modules manually because installation leaves a lot of files, links and modules behind and later this creates problems when we reconfigure another version of NodeJS and its modules.
To remove the files, run the following commands:
sudo rm -rf /usr/local/bin/npm
sudo rm -rf /usr/local/share/man/man1/node*
sudo rm -rf /usr/local/lib/dtrace/node.d
rm -rf ~/.npm
rm -rf ~/.node-gyp
sudo rm -rf /opt/local/bin/node
sudo rm -rf /opt/local/include/node
sudo rm -rf /opt/local/lib/node_modules
sudo rm -rf /usr/local/lib/node*
sudo rm -rf /usr/local/include/node*
sudo rm -rf /usr/local/bin/node*
I have posted a step by step guide with commands on my blog: AMCOS IT Support For Windows and Linux: To completely uninstall node js from Ubuntu.
In Python 2.x, it is not guaranteed at all:
>>> False = 5
>>> 0 == False
False
So it could change. In Python 3.x, True, False, and None are reserved words, so the above code would not work.
In general, with booleans you should assume that while False will always have an integer value of 0 (so long as you don't change it, as above), True could have any other value. I wouldn't necessarily rely on any guarantee that True==1
, but on Python 3.x, this will always be the case, no matter what.
The simplest way is:
const { exec } = require("child_process")
exec('yourApp').unref()
unref is necessary to end your process without waiting for "yourApp"
Here are the exec docs
If you are sure there are no leading spaces, you can use bash parameter substitution:
$ string="word1 word2"
$ echo ${string/%\ */}
word1
Watch out for escaping the single space. See here for more examples of substitution patterns. If you have bash > 3.0, you could also use regular expression matching to cope with leading spaces - see here:
$ string=" word1 word2"
$ [[ ${string} =~ \ *([^\ ]*) ]]
$ echo ${BASH_REMATCH[1]}
word1
SELECT * FROM (
SELECT
Row_Number() Over (Order by (Select 1)) as RawKey,
*
FROM [Alzh].[dbo].[DM_THD_TRANS_FY14]
) AS foo
WHERE RawKey between 17210400 and 17210500
I had a similar issue where the SelectedItem never got updated.
My problem was that the selected item was not the same instance as the item contained in the list. So I simply had to override the Equals() method in my MyCustomObject and compare the IDs of those two instances to tell the ComboBox that it's the same object.
public override bool Equals(object obj)
{
return this.Id == (obj as MyCustomObject).Id;
}
If you're using Spring, the 3.x release has what your looking for: http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/http/HttpStatus.html
http://www.c-sharpcorner.com/UploadFile/psingh/PDFFileGenerator12062005235236PM/PDFFileGenerator.aspx is open source and may be a good starting point for you.
Tomcat is primarily an application server, which serves requests to custom-built Java servlets or JSP files on your server. It is usually used in conjunction with the Apache HTTP server (at least in my experience). Use it to manually process incoming requests.
The HTTP server, by itself, is best for serving up static content... html files, images, etc.
I had a similar problem - maybe my solution will help. I just installed MSSQL EX 2012 (default install) and tried to connect with VS2012 EX. No joy. I then looked at the services, confirmed that SQL Server (SQLEXPRESS) was, indeed running.
However, I saw another interesting service called SQL Server Browser that was disabled. I enabled it, fired it and was then able to retrieve the server name in a new connection in VS2012 EX and connect.
Odd that they would disable a service required for VS to connect.
You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read
public class MyClass implements MyInterface {
public void find(int x) throws A_Exception, B_Exception{
----
----
---
}
}
Then an interface would look like this
public interface MyInterface {
void find(int x) throws A_Exception, B_Exception;
}
The answer is right in the MYSQL manual itself.
"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"
If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:
CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);
At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345"
) instead of a fractional value (e.g. "12345.0"
). Note that setCellType
is available in interface Cell
(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase
. Obviously, it would be nicer either to have getRawValue
in the Cell
interface or at least to be able use getStringCellValue
on non STRING cell types. Unfortunately, all replacements of setCellType
mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).
assuming that no other closing square bracket is allowed within, /FOO\[([^\]]*)\]/
Look at the r.status_code
attribute:
if r.status_code == 404:
# A 404 was issued.
Demo:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
If you want requests
to raise an exception for error codes (4xx or 5xx), call r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
if r:
# successful response
If you want to be more explicit, use if r.ok:
.
If I remember C++ syntax well, you can add a label to break
statements, just like for goto
. So what you want would be easily written:
while(true) {
switch(msg->state) {
case MSGTYPE: // ...
break;
// ... more stuff ...
case DONE:
break outofloop; // **HERE, I want to break out of the loop itself**
}
}
outofloop:
// rest of your code here
Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):
function searcharray($value, $key, $array) {
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
return $k;
}
}
return null;
}
Usage: $results = searcharray('searchvalue', searchkey, $array);
Simple. Just change the image orientation flag.
UIImage *oldImage = [UIImage imageNamed:@"whatever.jpg"];
UIImageOrientation newOrientation;
switch (oldImage.imageOrientation) {
case UIImageOrientationUp:
newOrientation = UIImageOrientationLandscapeLeft;
break;
case UIImageOrientationLandscapeLeft:
newOrientation = UIImageOrientationDown;
break;
case UIImageOrientationDown:
newOrientation = UIImageOrientationLandscapeRight;
break;
case UIImageOrientationLandscapeRight:
newOrientation = UIImageOrientationUp;
break;
// you can also handle mirrored orientations similarly ...
}
UIImage *rotatedImage = [UIImage imageWithCGImage:oldImage.CGImage scale:1.0f orientation:newOrientation];
<input type="text" formControlName="gsm" (input)="formatGsm($event.target.value)">
formatGsm(inputValue: String): String {
const value = inputValue.replace(/[^0-9]/g, ''); // remove except digits
let format = '(***) *** ** **'; // You can change format
for (let i = 0; i < value.length; i++) {
format = format.replace('*', value.charAt(i));
}
if (format.indexOf('*') >= 0) {
format = format.substring(0, format.indexOf('*'));
}
return format.trim();
}
Having problems connecting to SQL Server?
Try disconnecting firewall.
If you can connect with firewall disconnected, may be you miss some input rules like "sql service broker", add this input rules to your firewall:
"SQL ADMIN CONNECTION" TCP PORT 1434
"SQL ADMIN CONNECTION" UDP PORT 1434
"SQL ANALYSIS SERVICE" TCP PORT 2383
"SQL BROWSE ANALYSIS SERVICE" TCP PORT 2382
"SQL DEBUGGER/RPC" TCP PORT 135
"SQL SERVER" TCP PORT 1433 and others if you have dinamic ports
"SQL SERVICE BROKER" TCP PORT 4022
Getting only the instance attributes is easy.
But getting also the class attributes without the functions is a bit more tricky.
If you only have to list instance attributes just use
for attribute, value in my_instance
.__dict__
.items()
>>> from __future__ import (absolute_import, division, print_function)
>>> class MyClass(object):
... def __init__(self):
... self.a = 2
... self.b = 3
... def print_instance_attributes(self):
... for attribute, value in self.__dict__.items():
... print(attribute, '=', value)
...
>>> my_instance = MyClass()
>>> my_instance.print_instance_attributes()
a = 2
b = 3
>>> for attribute, value in my_instance.__dict__.items():
... print(attribute, '=', value)
...
a = 2
b = 3
To get also the class attributes without the functions, the trick is to use callable()
.
But static methods are not always callable
!
Therefore, instead of using callable(value)
use
callable
(getattr
(MyClass, attribute))
from __future__ import (absolute_import, division, print_function)
class MyClass(object):
a = "12"
b = "34" # class attributes
def __init__(self, c, d):
self.c = c
self.d = d # instance attributes
@staticmethod
def mystatic(): # static method
return MyClass.b
def myfunc(self): # non-static method
return self.a
def print_instance_attributes(self):
print('[instance attributes]')
for attribute, value in self.__dict__.items():
print(attribute, '=', value)
def print_class_attributes(self):
print('[class attributes]')
for attribute in self.__dict__.keys():
if attribute[:2] != '__':
value = getattr(self, attribute)
if not callable(value):
print(attribute, '=', value)
v = MyClass(4,2)
v.print_class_attributes()
v.print_instance_attributes()
Note: print_class_attributes()
should be @staticmethod
but not in this stupid and simple example.
$ python2 ./print_attributes.py
[class attributes]
a = 12
b = 34
[instance attributes]
c = 4
d = 2
$ python3 ./print_attributes.py
[class attributes]
b = 34
a = 12
[instance attributes]
c = 4
d = 2
You need to create Object
for the class.
$obj = new Functions();
$var = $obj->filter($_GET['params']);
looks like outerWidth is broken in the latest version of jquery.
The discrepancy happens when
the outer div is floated, the inner div has the width set (smaller than the outer div) the inner div has style="margin:auto"
As everyone here said, that's not possible directly.
The method I prefer and is rather clean, is to use an Object Mapper like AutoMapper.
It will do the task of copying properties from one instance to another (Not necessarily the same type) automatically.
Assuming that the user you are using in phpmyadmin has the necessary privileges, you can run this query to change the root password:
UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
FLUSH PRIVILEGES;
I faced this problem today and resolved it by checking the mapping class. I had a class which had 5 properties to which 5 columns returned from stored procedure were being mapped. Those properties were non-nullable and due to which i was getting the error. I made them nullable and the issue resolved.
public int? Pause { get; set; }
public int? Delay { get; set; }
public int? Transition { get; set; }
public int? TransitionTime { get; set; }
public int? TransitionResolution { get; set; }
Added "?" with data type to made them nullable.
Secondly i also added isNull check in the stored procedure as well as follows:
isnull(co_pivot.Pause, 0) as Pause,
isnull(co_pivot.Delay, 0) as Delay,
isnull(co_pivot.Transition, 0) as Transition,
isnull(co_pivot.TransitionTime, 0) as TransitionTime,
isnull(co_pivot.TransitionResolution, 0) as TransitionResolution
Hope this helps someone.
I played with JMeter. One think it could not not test was ASP.NET Webforms. The viewstate broke my tests. I am not shure why, but there are a couple of tools out there that dont handle viewstate right. My current project is ASP.NET MVC and JMeter works well with it.
Here is a hopefully helpful pointer, in a code example. Note how the initializer function is only called once.
Also, if you invert the calls to StaticClass::initializeStStateArr()
and $st = new StaticClass()
you'll get the same result.
$ cat static.php
<?php
class StaticClass {
public static $stStateArr = NULL;
public function __construct() {
if (!isset(self::$stStateArr)) {
self::initializeStStateArr();
}
}
public static function initializeStStateArr() {
if (!isset(self::$stStateArr)) {
self::$stStateArr = array('CA' => 'California', 'CO' => 'Colorado',);
echo "In " . __FUNCTION__. "\n";
}
}
}
print "Starting...\n";
StaticClass::initializeStStateArr();
$st = new StaticClass();
print_r (StaticClass::$stStateArr);
Which yields :
$ php static.php
Starting...
In initializeStStateArr
Array
(
[CA] => California
[CO] => Colorado
)
See mozilla.org's write-up on how CORS works.
You'll need your server to send back the proper response headers, something like:
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization
Bear in mind you can use "*"
for Access-Control-Allow-Origin
that will only work if you're trying to pass Authentication data. In that case, you need to explicitly list the origin domains you want to allow. To allow multiple domains, see this post
This might be overkill - but be careful doing anything which relies on the extension of PHP files being .php
- what if someone comes along later and adds handlers for .php4
or even .html
so they're handled by PHP. You might be better off serving files out of those directories from a different instance of Apache or something, which only serves static content.
If your count(distinct(x))
is significantly slower than count(x)
then you can speed up this query by maintaining x value counts in different table, for example table_name_x_counts (x integer not null, x_count int not null)
, using triggers. But your write performance will suffer and if you update multiple x
values in single transaction then you'd need to do this in some explicit order to avoid possible deadlock.
For responsive images. You can add the picture and source tags within the figure tag.
<figure>
<picture>
<source media="(min-width: 750px)" srcset="images/image_2x.jpg"/>
<source media="(min-width: 500px)" srcset="images/image.jpg" />
<img src="images.jpg" alt="An image">
</picture>
<figcaption>Caption goes here</figcaption>
</figure>
If you want to alter the original objects, then a simple Array#forEach
will do:
rockets.forEach(function(rocket) {
rocket.launches += 10;
});
If you want to keep the original objects unaltered, then use Array#map
and copy the objects using Object#assign
:
var newRockets = rockets.forEach(function(rocket) {
var newRocket = Object.assign({}, rocket);
newRocket.launches += 10;
return newRocket;
});
/**
* Tests image load.
* @param {String} url
* @returns {Promise}
*/
function testImageUrl(url) {
return new Promise(function(resolve, reject) {
var image = new Image();
image.addEventListener('load', resolve);
image.addEventListener('error', reject);
image.src = url;
});
}
return testImageUrl(imageUrl).then(function imageLoaded(e) {
return imageUrl;
})
.catch(function imageFailed(e) {
return defaultImageUrl;
});
You could just use another non-regex based method. Someone gave the suggestion of using Substring, but you could also use Split:
string testString = "my-string";
string[] splitString = testString.Split("-");
string resultingString = splitString[0]; //my
See http://msdn.microsoft.com/en-US/library/ms228388%28v=VS.80%29.aspx for another good example.
Be explicit - then the compiler won't warn that you perhaps made a mistake.
while ( (list = list->next) != NULL )
or
while ( (list = list->next) )
Some day you'll be glad the compiler told you, people do make that mistake ;)
Map
is an interface; HashMap
is a particular implementation of that interface.
HashMap uses a collection of hashed key values to do its lookup. TreeMap will use a red-black tree as its underlying data store.
Easy Way To Delete Item From state array in react:
when any data delete from database and update list without API calling that time you pass deleted id to this function and this function remove deleted recored from list
export default class PostList extends Component {_x000D_
this.state = {_x000D_
postList: [_x000D_
{_x000D_
id: 1,_x000D_
name: 'All Items',_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'In Stock Items',_x000D_
}_x000D_
],_x000D_
}_x000D_
_x000D_
_x000D_
remove_post_on_list = (deletePostId) => {_x000D_
this.setState({_x000D_
postList: this.state.postList.filter(item => item.post_id != deletePostId)_x000D_
})_x000D_
}_x000D_
_x000D_
}
_x000D_
One way would be to create a variable that represents the first of the month (ie 5/1/2009), either pass it into the proc or build it (concatenate month/1/year). Then use the DateDiff function.
WHERE DateDiff(m,@Date,DateField) = 0
This will return anything with a matching month and year.
getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.TabColor)));
color.xml file:
<resources> <color name="TabColor">#11FF00</color> </resources>`
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
Excel Export Script works on IE7+ , Firefox and Chrome
===========================================================
function fnExcelReport()
{
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
tab = document.getElementById('headerTable'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text=tab_text+"</table>";
tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
}
else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
Just Create a blank iframe
enter code here
<iframe id="txtArea1" style="display:none"></iframe>
Call this function on
<button id="btnExport" onclick="fnExcelReport();"> EXPORT
</button>
I tried with the following script -
.selector {
background-image: url("img/image.jpg");
background-size: 100%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-repeat: no-repeat;
}
It worked for me!
Don't trust the Visual editor. Your code does work in the emu.
For this you can simply use the redirect
function that is included in flask
from flask import Flask, redirect
app = Flask(__name__)
@app.route('/')
def hello():
return redirect("https://www.exampleURL.com", code = 302)
if __name__ == "__main__":
app.run()
Another useful tip(as you're new to flask), is to add app.debug = True
after initializing the flask object as the debugger output helps a lot while figuring out what's wrong.
I did tests with buffer size, running this code
using (var stream = new BufferedStream(File.OpenRead(file), bufferSize))
{
SHA256Managed sha = new SHA256Managed();
byte[] checksum = sha.ComputeHash(stream);
return BitConverter.ToString(checksum).Replace("-", String.Empty).ToLower();
}
And I tested with a file of 29½ GB in size, the results were
I am running an i5 2500K CPU, 12 GB ram and a OCZ Vertex 4 256 GB SSD drive.
So I thought, what about a standard 2TB harddrive. And the results were like this
So I would recommend either no buffer or a buffer of max 1 mill.
You can just use File.AppendAllText() Method this will solve your problem. This method will take care of File Creation if not available, opening and closing the file.
var outputPath = @"E:\Example.txt";
var data = "Example Data";
File.AppendAllText(outputPath, data);
Another example with using Objective-C associated objects and computed properties for Swift 3 and Swift 4
import CoreLocation
extension CLLocation {
private struct AssociatedKeys {
static var originAddress = "originAddress"
static var destinationAddress = "destinationAddress"
}
var originAddress: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.originAddress) as? String
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.originAddress,
newValue as NSString?,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
}
var destinationAddress: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.destinationAddress) as? String
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.destinationAddress,
newValue as NSString?,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
}
}
See Pyperclip. Example (taken from Pyperclip site):
import pyperclip
pyperclip.copy('The text to be copied to the clipboard.')
spam = pyperclip.paste()
Also, see Xerox. But it appears to have more dependencies.
I would think this:
byte[] file = System.IO.File.ReadAllBytes(fileName);
Use a JSON library to parse the string and retrieve the value.
The following very basic example uses the built-in JSON parser from Android.
String jsonString = "{ \"name\" : \"John\", \"age\" : \"20\", \"address\" : \"some address\" }";
JSONObject jsonObject = new JSONObject(jsonString);
int age = jsonObject.getInt("age");
More advanced JSON libraries, such as jackson, google-gson, json-io or genson, allow you to convert JSON objects to Java objects directly.
Maybe your file contains CRLF terminator. Every lines followed by \r\n.
awk
recognizes the $2
actually $2\r
. The \r
means goto the start of the line.
{print $2\r$1}
will print $2
first, then return to the head, then print $1
. So the field 2 is overlaid by the field 1.
In this specific case, note that bash has a variable called PWD
that contains the current directory: $PWD
is equivalent to `pwd`
. (So do other shells, this is a standard feature.) So you can write your script like this:
#!/bin/bash
until [ "$PWD" = "/" ]; do
echo "$PWD"
ls && cd .. && ls
done
Note the use of double quotes around the variable references. They are necessary if the variable (here, the current directory) contains whitespace or wildcards (\[?*
), because the shell splits the result of variable expansions into words and performs globbing on these words. Always double-quote variable expansions "$foo"
and command substitutions "$(foo)"
(unless you specifically know you have not to).
In the general case, as other answers have mentioned already:
var=value
, not var = value
$
means “take the value of this variable”, so you don't use it when assigning: var=value
, not $var=value
Its fine to just do char **strings;
, char **strings = NULL
, or char **strings = {NULL}
but to initialize it you'd have to use malloc:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
// allocate space for 5 pointers to strings
char **strings = (char**)malloc(5*sizeof(char*));
int i = 0;
//allocate space for each string
// here allocate 50 bytes, which is more than enough for the strings
for(i = 0; i < 5; i++){
printf("%d\n", i);
strings[i] = (char*)malloc(50*sizeof(char));
}
//assign them all something
sprintf(strings[0], "bird goes tweet");
sprintf(strings[1], "mouse goes squeak");
sprintf(strings[2], "cow goes moo");
sprintf(strings[3], "frog goes croak");
sprintf(strings[4], "what does the fox say?");
// Print it out
for(i = 0; i < 5; i++){
printf("Line #%d(length: %lu): %s\n", i, strlen(strings[i]),strings[i]);
}
//Free each string
for(i = 0; i < 5; i++){
free(strings[i]);
}
//finally release the first string
free(strings);
return 0;
}
Surround it with an \mbox{}
I think you should consider using IO.binread("/path/to/file")
if you have a recent ruby interpreter (i.e. >= 1.9.2)
You could find IO
class documentation here http://www.ruby-doc.org/core-2.1.2/IO.html
Use Java's replaceAll(String regex, String replacement)
For example, Use a substitution char for the quotes and then replace that char with \"
String newstring = String.replaceAll("%","\"");
or replace all instances of \"
with \\\"
String newstring = String.replaceAll("\"","\\\"");
They are found on either one of the below locations depending on how chrome was installed
~/Users/<username>/Library/Application\ Support/Google/Chrome/Default/Extensions
/Library/Application\ Support/Google/Chrome/Default/Extensions
Above .net core 2.2 the method Main support args with WebHost.CreateDefaultBuilder(args)
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
You can build your project and go to bin
run command like this
dotnet <yours>.dll --urls=http://localhost:5001
or with multi-urls
dotnet <yours>.dll --urls="http://localhost:5001,https://localhost:5002"
Add this for JAVA:
public boolean CheckWifiConnection() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
in Manifest file add the following permissions:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
dplyr::as_data_frame(df, rownames = "your_row_name")
will give you even simpler result.
The solution:
particular_script || true
Example:
$ cat /tmp/1.sh
particular_script()
{
false
}
set -e
echo one
particular_script || true
echo two
particular_script
echo three
$ bash /tmp/1.sh
one
two
three
will be never printed.
Also, I want to add that when pipefail
is on,
it is enough for shell to think that the entire pipe has non-zero exit code
when one of commands in the pipe has non-zero exit code (with pipefail
off it must the last one).
$ set -o pipefail
$ false | true ; echo $?
1
$ set +o pipefail
$ false | true ; echo $?
0
What worked for me was to edit .git/config
and use
[remote "origin"]
url = https://<login>:<password>@gitlab.com(...).git
It goes without saying that this is an insecure way of storing your password but there are environments/cases where this may not be a problem.
One obvious and straightforward possibility is to use "if-else conditions". In that example
x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)
** For the additional question in the edit** Is that what you expect ?
> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
>
> w <- ifelse((d1 == "e") & (d2 == "e"), 1,
+ ifelse((d1=="a") & (d2 == "b"), 2,
+ ifelse((d1 == "e"), 3, 99)))
>
> data.frame(d1, d2, w)
d1 d2 w
1 e e 1
2 c a 99
3 a b 2
If you do not feel comfortable with the ifelse
function, you can also work with the if
and else
statements for such applications.
I have solved as plist file.
Although this question is answered a long time ago. I want to recommend to use the pathlib
module since this is a robust way to work on Windows and Unix OS.
So to get all paths in a specific directory including subdirectories:
from pathlib import Path
paths = list(Path('myhomefolder', 'folder').glob('**/*.txt'))
# all sorts of operations
file = paths[0]
file.name
file.stem
file.parent
file.suffix
etc.
Return false
to prevent the keystroke from continuing.
The os.makedirs
function does this. Try the following:
import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
The reason to add the try-except
block is to handle the case when the directory was created between the os.path.exists
and the os.makedirs
calls, so that to protect us from race conditions.
In Python 3.2+, there is a more elegant way that avoids the race condition above:
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
Assuming you have already set the client_max_body_size and various PHP settings (upload_max_filesize / post_max_size , etc) in the other answers, then restarted or reloaded NGINX and PHP without any result, run this...
nginx -T
This will give you any unresolved errors in your NGINX configs. In my case, I struggled with the 413 error for a whole day before I realized there were some other unresolved SSL errors in the NGINX config (wrong pathing for certs) that needed to be corrected. Once I fixed the unresolved issues I got from 'nginx -T', reloaded NGINX, and EUREKA!! That fixed it.
From Terminal:
Add Fish to /etc/shells
, which will require an administrative password:
sudo echo /usr/local/bin/fish >> /etc/shells
Make Fish your default shell with chsh
:
chsh -s /usr/local/bin/fish
From System Preferences:
User and Groups ? ctrl-click on Current User ? Advanced Options...
Change Login shell to /usr/local/bin/fish
Press OK, log out and in again
Arrays.fill(arrayName,value);
in java
int arrnum[] ={5,6,9,2,10};
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Arrays.fill(arrnum,0);
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Output
5 6 9 2 10
0 0 0 0 0
Try using a callback like this with the catch block.
document.getElementById("audio").play().catch(function() {
// do something
});
For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)
If Return = 0 And Level = 0 Then GoTo NextIteration
'Go to the next iteration
Else
End If
' This is how you make a line label in VBA - Do not use keyword or
' integer and end it in colon
NextIteration:
Next
@Column(nullable = false, updatable = false)
@CreationTimestamp
private Date created_at;
this worked for me. more info
Does it have something to do with preventing other events on the page from firing?
Yes.
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.
For more insight see: jQuery ajax success anonymous function scope
Eloquent uses the query builder internally, so you can do:
$users = User::orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();
Just for the record, since SQL 2012 you can use FORMAT, as simple as:
SELECT FORMAT(GETDATE(), 'ddMMyyyy')
(op question is specific about SQL 2008)
Firstobject's free XML editor for Windows is called foxe is a great tool.
Open or paste your XML into it and press F8 to indent (you may need to set the number of indent spaces as it may default to 0).
It looks simple, however it contains a custom written XML parser written in C++ that allows it to work efficiently with very large XML files easily (unlike some expensive "espionage" related tools I've used).
From the product page:
The full Visual C++ source code for this firstobject XML editor (including the CDataEdit gigabyte edit control MFC component) is available as part of the Advanced CMarkup Developer License. It allows developers to implement custom XML handling functions such as validation, transformation, beautify, and reporting for their own purposes.
A Kotlin-only solution that does not require to have changes in the XML Layouts:
//Function to call in onResume() of your activity
private fun centerToolbarText() {
val mTitleTextView = AppCompatTextView(this)
mTitleTextView.text = title
mTitleTextView.setSingleLine()//Remove it if you want to allow multiple lines in the toolbar
mTitleTextView.textSize = 25f
val layoutParams = android.support.v7.app.ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT
)
layoutParams.gravity = Gravity.CENTER
supportActionBar?.setCustomView(mTitleTextView,layoutParams)
supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
}
import re
s = "many fancy word \nhello \thi"
re.split('\s+', s)
using JSON.stringify(yourObj) or Object.toJSON(yourObj) last one is for using prototype.js, then send it using whatever you want, ajax or submit, and you use, as suggested, json_decode ( http://www.php.net/manual/en/function.json-decode.php ) to parse it in php. And then you can use it as an array.
Scanner
is used for parsing tokens from the contents of the stream while BufferedReader
just reads the stream and does not do any special parsing.
In fact you can pass a BufferedReader
to a scanner
as the source of characters to parse.
I prefer this - "Hello World".ToLower().Replace( "world", "csharp" );
I had the same problem with a Galaxy S3 mini (android 4.1.2) and I simply made my custom checkbox extend AppCompatCheckBox instead of CheckBox. Now it works perfectly.
I wanted to pass T.class to a method which make use of Generics
The method readFile reads a .csv file specified by the fileName with fullpath. There can be csv files with different contents hence i need to pass the model file class so that i can get the appropriate objects. Since this is reading csv file i wanted to do in a generic way. For some reason or other none of the above solutions worked for me. I need to use
Class<? extends T> type
to make it work. I use opencsv library for parsing the CSV files.
private <T>List<T> readFile(String fileName, Class<? extends T> type) {
List<T> dataList = new ArrayList<T>();
try {
File file = new File(fileName);
Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
Reader headerReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
CSVReader csvReader = new CSVReader(headerReader);
// create csv bean reader
CsvToBean<T> csvToBean = new CsvToBeanBuilder(reader)
.withType(type)
.withIgnoreLeadingWhiteSpace(true)
.build();
dataList = csvToBean.parse();
}
catch (Exception ex) {
logger.error("Error: ", ex);
}
return dataList;
}
This is how the readFile method is called
List<RigSurfaceCSV> rigSurfaceCSVDataList = readSurfaceFile(surfaceFileName, RigSurfaceCSV.class);
A clean way to do it would be to override all operators (+ and * in particular) and check for an overflow before performing the operations.
It's two steps but I like to do it this way:
First create a file with a particular date/time. In this case, the file is 2008-10-01 at midnight
touch -t 0810010000 /tmp/t
Now we can find all files that are newer or older than the above file (going by file modified date. You can also use -anewer for accessed and -cnewer file status changed).
find / -newer /tmp/t
find / -not -newer /tmp/t
You could also look at files between certain dates by creating two files with touch
touch -t 0810010000 /tmp/t1
touch -t 0810011000 /tmp/t2
This will find files between the two dates & times
find / -newer /tmp/t1 -and -not -newer /tmp/t2
This is bit tricky
Now a days most of website new techniques to save websites from scraping
1st Technique
Ctrl+U this will show you Page Source
2nd Technique
This one is small hack if the website has ajax like functionality.
Just Hover the mouse key on inspect element untill whole screen becomes just right click then and copy element
That's it you are good to go.
Actually, the entire approach would be cleaner if you only had to use one instance of StringBuffer, instead of creating one in every recursive call... I would go for:
private String getWhoozitYs(){
StringBuffer sb = new StringBuffer();
while (generator.nextBoolean()) {
sb.append("y");
}
return sb.toString();
}
Single LinearLayout
solution. Only adding a simple spacing view:
(No-one seemed to have mentioned this one, only more complicated multi-layout solutions.)
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textColor="#404040"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:layout_marginTop="9dp" />
<!------------------------- ADDED SPACER VIEW -------------------->
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1"
/>
<!------------------------- /ADDED SPACER VIEW -------------------->
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:background="@drawable/stitch_button"
android:layout_marginLeft="10dp"
android:text="@string/add"
android:layout_gravity="right"
android:layout_marginRight="15dp" />
</LinearLayout>
Note the "highlighted" View, I didn't modify anything else. Height=0 makes sure it's not visible. Width=0 is because the width is determined by the LinearLayout
based on weight=1. This means that the spacer view will stretch as much as possible in the direction (orientation) of the LinearLayout
.
Note that you should use android.widget.Space
or android.support.v4.widget.Space
instead of View
if your API level and/or dependencies allow it. Space
achieves the job in a cheaper way, because it only measures and doesn't try to draw anything like View
does; it's also more expressive conveying the intention.
I'm looking into using SSTJ for FFTs in Java. It can redirect via JNI to FFTW if the library is available or will use a pure Java implementation if not.
The MySQL documentation has information on mapping MySQL types to Java types. In general, for MySQL datetime and timestamps you should use java.sql.Timestamp
. A few resources include:
http://dev.mysql.com/doc/refman/5.1/en/datetime.html
http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion
How to store Java Date to Mysql datetime...?
EDIT:
As others have indicated, the suggestion of using strings may lead to issues.
Both functions use the os.path.split(path)
function to split the pathname path
into a pair; (head, tail)
.
The os.path.dirname(path)
function returns the head of the path.
E.g.: The dirname of '/foo/bar/item'
is '/foo/bar'
.
The os.path.basename(path)
function returns the tail of the path.
E.g.: The basename of '/foo/bar/item'
returns 'item'
From: http://docs.python.org/2/library/os.path.html#os.path.basename
This is probably not that fast, but has the added benefit of making sure your number is at least a certain value (e.g. 0), or at most a certain value:
Math.max(input, 0);
If you need to ensure a minimum value, usually you'd do
var number = Number(input);
if (number < 0) number = 0;
Math.max(..., 0)
saves you from writing two statements.
Try this one:
onsubmit="return f(this.'yourfieldname'.value);"
I hope this will help you.
There is an isConnected function in BluetoothDevice system API in https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth/BluetoothDevice.java
If you want to know if the a bounded(paired) device is currently connected or not, the following function works fine for me:
public static boolean isConnected(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("isConnected", (Class[]) null);
boolean connected = (boolean) m.invoke(device, (Object[]) null);
return connected;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
If you want to delete a commit you can do it as part of an interactive rebase. But do it with caution, so you don't end up messing up your repo.
In Sourcetree:
Check out this Atlassian blog post for more on interactive rebasing in Sourcetree.
I assume that with interface you mean a C++ class with only pure virtual methods (i.e. without any code), instead with abstract class you mean a C++ class with virtual methods that can be overridden, and some code, but at least one pure virtual method that makes the class not instantiable. e.g.:
class MyInterface
{
public:
// Empty virtual destructor for proper cleanup
virtual ~MyInterface() {}
virtual void Method1() = 0;
virtual void Method2() = 0;
};
class MyAbstractClass
{
public:
virtual ~MyAbstractClass();
virtual void Method1();
virtual void Method2();
void Method3();
virtual void Method4() = 0; // make MyAbstractClass not instantiable
};
In Windows programming, interfaces are fundamental in COM. In fact, a COM component exports only interfaces (i.e. pointers to v-tables, i.e. pointers to set of function pointers). This helps defining an ABI (Application Binary Interface) that makes it possible to e.g. build a COM component in C++ and use it in Visual Basic, or build a COM component in C and use it in C++, or build a COM component with Visual C++ version X and use it with Visual C++ version Y. In other words, with interfaces you have high decoupling between client code and server code.
Moreover, when you want to build DLL's with a C++ object-oriented interface (instead of pure C DLL's), as described in this article, it's better to export interfaces (the "mature approach") instead of C++ classes (this is basically what COM does, but without the burden of COM infrastructure).
I'd use an interface if I want to define a set of rules using which a component can be programmed, without specifying a concrete particular behavior. Classes that implement this interface will provide some concrete behavior themselves.
Instead, I'd use an abstract class when I want to provide some default infrastructure code and behavior, and make it possible to client code to derive from this abstract class, overriding the pure virtual methods with some custom code, and complete this behavior with custom code. Think for example of an infrastructure for an OpenGL application. You can define an abstract class that initializes OpenGL, sets up the window environment, etc. and then you can derive from this class and implement custom code for e.g. the rendering process and handling user input:
// Abstract class for an OpenGL app.
// Creates rendering window, initializes OpenGL;
// client code must derive from it
// and implement rendering and user input.
class OpenGLApp
{
public:
OpenGLApp();
virtual ~OpenGLApp();
...
// Run the app
void Run();
// <---- This behavior must be implemented by the client ---->
// Rendering
virtual void Render() = 0;
// Handle user input
// (returns false to quit, true to continue looping)
virtual bool HandleInput() = 0;
// <--------------------------------------------------------->
private:
//
// Some infrastructure code
//
...
void CreateRenderingWindow();
void CreateOpenGLContext();
void SwapBuffers();
};
class MyOpenGLDemo : public OpenGLApp
{
public:
MyOpenGLDemo();
virtual ~MyOpenGLDemo();
// Rendering
virtual void Render(); // implements rendering code
// Handle user input
virtual bool HandleInput(); // implements user input handling
// ... some other stuff
};
There is a method in Guava Sets
which can help here:
public static <E> boolean equals(Set<? extends E> set1, Set<? extends E> set2){
return Sets.symmetricDifference(set1,set2).isEmpty();
}
One of the answers in the question referred to by @Z.Bagley gave me the answer. I had to import Renderer2 from @angular/core into my component. Then:
const element = this.renderer.selectRootElement('#input1');
// setTimeout(() => element.focus, 0);
setTimeout(() => element.focus(), 0);
Thank you @MrBlaise for the solution!
You can pipe grep
result to head
in conjunction with stdbuf.
Note, that in order to ensure stopping after Nth match, you need to using stdbuf
to make sure grep
don't buffer its output:
stdbuf -oL grep -rl 'pattern' * | head -n1
stdbuf -oL grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/dir | head -n1
stdbuf -oL grep -nH -m 1 -R "django.conf.urls.defaults" * | head -n1
As soon as head
consumes 1 line, it terminated and grep
will receive SIGPIPE
because it still output something to pipe while head
was gone.
This assumed that no file names contain newline.
That's right. You could try it in the interpreter like this:
>>> a_set = set(['a', 'b', 'c'])
>>> 'a' in a_set
True
>>>'d' in a_set
False
Simply override the onBackPressed() method.
@Override
public void onBackPressed() { }
I have been working on Swagger equivalent documentation library called Springfox
nowadays and I found that in the Spring 5.0.8 (running at present), interface WebMvcConfigurer
has been implemented by class WebMvcConfigurationSupport
class which we can directly extend.
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
public class WebConfig extends WebMvcConfigurationSupport { }
And this is how I have used it for setting my resource handling mechanism as follows -
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
$this->db->where('accommodation BETWEEN '' . $sdate . '' AND '' . $edate . ''');
this is my solution
Try this before anything else - 'clear your cache'. I had the same issue. I was instructed to clear my cache. It worked.
Those using a buffer or tree navigation plugin, like Buffergator or NERDTree, will need to toggle these splits before destroying the current buffer - else you'll send your splits into wonkyville
I use:
"" Buffer Navigation
" Toggle left sidebar: NERDTree and BufferGator
fu! UiToggle()
let b = bufnr("%")
execute "NERDTreeToggle | BuffergatorToggle"
execute ( bufwinnr(b) . "wincmd w" )
execute ":set number!"
endf
map <silent> <Leader>w <esc>:call UiToggle()<cr>
Where "NERDTreeToggle
" in that list is the same as typing :NERDTreeToggle
. You can modify this function to integrate with your own configuration.
I'd use iloc
, which takes a row/column slice, both based on integer position and following normal python syntax. If you want every 5th row:
df.iloc[::5, :]
Accepted answer is right, however I had a trouble with that. When I add in my code, checking on debugger, I saw that it changes from
result.replace(/"/g,'"')
to
result.replace(/"/g,'"')
Instead of this I use that:
result.replace(/("\;)/g,"\"")
By this notation it works.
Dockerfile comments start with '#', just like Python. Here is a good example (kstaken/dockerfile-examples):
# Install a more-up-to date version of MongoDB than what is included in the default Ubuntu repositories.
FROM ubuntu
MAINTAINER Kimbro Staken
RUN apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
RUN echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" | tee -a /etc/apt/sources.list.d/10gen.list
RUN apt-get update
RUN apt-get -y install apt-utils
RUN apt-get -y install mongodb-10gen
#RUN echo "" >> /etc/mongodb.conf
CMD ["/usr/bin/mongod", "--config", "/etc/mongodb.conf"]
You can use date filter to convert in date and display in specific format.
In .ts file (typescript):
let dateString = '1968-11-16T00:00:00'
let newDate = new Date(dateString);
In HTML:
{{dateString | date:'MM/dd/yyyy'}}
Below are some formats which you can implement :
Backend:
public todayDate = new Date();
HTML :
<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option>
</select>
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
It should be like this
$(this).text($(this).text().replace('N/A, ', ''))
Below is an example of a script which implements try/catch/finally
in bash.
Like other answers to this question, exceptions must be caught after exiting a subprocess.
The example scripts start by creating an anonymous fifo, which is used to pass string messages from a command exception
or throw
to end of the closest try
block. Here the messages are removed from the fifo and placed in an array variable. The status is returned through return
and exit
commands and placed in a different variable. To enter a catch
block, this status must not be zero. Other requirements to enter a catch
block are passed as parameters. If the end of a catch
block is reached, then the status is set to zero. If the end of the finally
block is reached and the status is still nonzero, then an implicit throw containing the messages and status is executed. The script requires the calling of the function trycatchfinally
which contains an unhandled exception handler.
The syntax for the trycatchfinally
command is given below.
trycatchfinally [-cde] [-h ERR_handler] [-k] [-o debug_file] [-u unhandled_handler] [-v variable] fifo function
The -c
option adds the call stack to the exception messages.
The -d
option enables debug output.
The -e
option enables command exceptions.
The -h
option allows the user to substitute their own command exception handler.
The -k
option adds the call stack to the debug output.
The -o
option replaces the default output file which is /dev/fd/2
.
The -u
option allows the user to substitute their own unhandled exception handler.
The -v
option allows the user the option to pass back values though the use of Command Substitution.
The fifo
is the fifo filename.
The function function
is called by trycatchfinally
as a subprocess.
Note: The
cdko
options were removed to simplify the script.
The syntax for the catch
command is given below.
catch [[-enoprt] list ...] ...
The options are defined below. The value for the first list is the status. Subsquent values are the messages. If the there are more messages than lists, then the remaining messages are ignored.
-e
means [[ $value == "$string" ]]
(the value has to match at least one string in the list)
-n
means [[ $value != "$string" ]]
(the value can not match any of the strings in the list)
-o
means [[ $value != $pattern ]]
(the value can not match any of the patterns in the list)
-p
means [[ $value == $pattern ]]
(the value has to match at least one pattern in the list)
-r
means [[ $value =~ $regex ]]
(the value has to match at least one extended regular expression in the list)
-t
means [[ ! $value =~ $regex ]]
(the value can not match any of the extended regular expressions in the list)
The try/catch/finally
script is given below. To simplify the script for this answer, most of the error checking was removed. This reduced the size by 64%. A complete copy of this script can be found at my other answer.
shopt -s expand_aliases
alias try='{ common.Try'
alias yrt='EchoExitStatus; common.yrT; }'
alias catch='{ while common.Catch'
alias hctac='common.hctaC; done; }'
alias finally='{ common.Finally'
alias yllanif='common.yllaniF; }'
DefaultErrHandler() {
echo "Orginal Status: $common_status"
echo "Exception Type: ERR"
}
exception() {
let "common_status = 10#$1"
shift
common_messages=()
for message in "$@"; do
common_messages+=("$message")
done
}
throw() {
local "message"
if [[ $# -gt 0 ]]; then
let "common_status = 10#$1"
shift
for message in "$@"; do
echo "$message" >"$common_fifo"
done
elif [[ ${#common_messages[@]} -gt 0 ]]; then
for message in "${common_messages[@]}"; do
echo "$message" >"$common_fifo"
done
fi
chmod "0400" "$common_fifo"
exit "$common_status"
}
common.ErrHandler() {
common_status=$?
trap ERR
if [[ -w "$common_fifo" ]]; then
if [[ $common_options != *e* ]]; then
common_status="0"
return
fi
eval "${common_errHandler:-} \"${BASH_LINENO[0]}\" \"${BASH_SOURCE[1]}\" \"${FUNCNAME[1]}\" >$common_fifo <$common_fifo"
chmod "0400" "$common_fifo"
fi
if [[ common_trySubshell -eq BASH_SUBSHELL ]]; then
return
else
exit "$common_status"
fi
}
common.Try() {
common_status="0"
common_subshell="$common_trySubshell"
common_trySubshell="$BASH_SUBSHELL"
common_messages=()
}
common.yrT() {
local "status=$?"
if [[ common_status -ne 0 ]]; then
local "message=" "eof=TRY_CATCH_FINALLY_END_OF_MESSAGES_$RANDOM"
chmod "0600" "$common_fifo"
echo "$eof" >"$common_fifo"
common_messages=()
while read "message"; do
[[ $message != *$eof ]] || break
common_messages+=("$message")
done <"$common_fifo"
fi
common_trySubshell="$common_subshell"
}
common.Catch() {
[[ common_status -ne 0 ]] || return "1"
local "parameter" "pattern" "value"
local "toggle=true" "compare=p" "options=$-"
local -i "i=-1" "status=0"
set -f
for parameter in "$@"; do
if "$toggle"; then
toggle="false"
if [[ $parameter =~ ^-[notepr]$ ]]; then
compare="${parameter#-}"
continue
fi
fi
toggle="true"
while "true"; do
eval local "patterns=($parameter)"
if [[ ${#patterns[@]} -gt 0 ]]; then
for pattern in "${patterns[@]}"; do
[[ i -lt ${#common_messages[@]} ]] || break
if [[ i -lt 0 ]]; then
value="$common_status"
else
value="${common_messages[i]}"
fi
case $compare in
[ne]) [[ ! $value == "$pattern" ]] || break 2;;
[op]) [[ ! $value == $pattern ]] || break 2;;
[tr]) [[ ! $value =~ $pattern ]] || break 2;;
esac
done
fi
if [[ $compare == [not] ]]; then
let "++i,1"
continue 2
else
status="1"
break 2
fi
done
if [[ $compare == [not] ]]; then
status="1"
break
else
let "++i,1"
fi
done
[[ $options == *f* ]] || set +f
return "$status"
}
common.hctaC() {
common_status="0"
}
common.Finally() {
:
}
common.yllaniF() {
[[ common_status -eq 0 ]] || throw
}
caught() {
[[ common_status -eq 0 ]] || return 1
}
EchoExitStatus() {
return "${1:-$?}"
}
EnableThrowOnError() {
[[ $common_options == *e* ]] || common_options+="e"
}
DisableThrowOnError() {
common_options="${common_options/e}"
}
GetStatus() {
echo "$common_status"
}
SetStatus() {
let "common_status = 10#$1"
}
GetMessage() {
echo "${common_messages[$1]}"
}
MessageCount() {
echo "${#common_messages[@]}"
}
CopyMessages() {
if [[ ${#common_messages} -gt 0 ]]; then
eval "$1=(\"\${common_messages[@]}\")"
else
eval "$1=()"
fi
}
common.GetOptions() {
local "opt"
let "OPTIND = 1"
let "OPTERR = 0"
while getopts ":cdeh:ko:u:v:" opt "$@"; do
case $opt in
e) [[ $common_options == *e* ]] || common_options+="e";;
h) common_errHandler="$OPTARG";;
u) common_unhandled="$OPTARG";;
v) common_command="$OPTARG";;
esac
done
shift "$((OPTIND - 1))"
common_fifo="$1"
shift
common_function="$1"
chmod "0600" "$common_fifo"
}
DefaultUnhandled() {
local -i "i"
echo "-------------------------------------------------"
echo "TryCatchFinally: Unhandeled exception occurred"
echo "Status: $(GetStatus)"
echo "Messages:"
for ((i=0; i<$(MessageCount); i++)); do
echo "$(GetMessage "$i")"
done
echo "-------------------------------------------------"
}
TryCatchFinally() {
local "common_errHandler=DefaultErrHandler"
local "common_unhandled=DefaultUnhandled"
local "common_options="
local "common_fifo="
local "common_function="
local "common_flags=$-"
local "common_trySubshell=-1"
local "common_subshell"
local "common_status=0"
local "common_command="
local "common_messages=()"
local "common_handler=$(trap -p ERR)"
[[ -n $common_handler ]] || common_handler="trap ERR"
common.GetOptions "$@"
shift "$((OPTIND + 1))"
[[ -z $common_command ]] || common_command+="=$"
common_command+='("$common_function" "$@")'
set -E
set +e
trap "common.ErrHandler" ERR
try
eval "$common_command"
yrt
catch; do
"$common_unhandled" >&2
hctac
[[ $common_flags == *E* ]] || set +E
[[ $common_flags != *e* ]] || set -e
[[ $common_flags != *f* || $- == *f* ]] || set -f
[[ $common_flags == *f* || $- != *f* ]] || set +f
eval "$common_handler"
}
Below is an example, which assumes the above script is stored in the file named simple
. The makefifo
file contains the script described in this answer. The assumption is made that the file named 4444kkkkk
does not exist, therefore causing an exception to occur. The error message output from the ls 4444kkkkk
command is automatically suppressed until inside the appropriate catch
block.
#!/bin/bash
#
if [[ $0 != ${BASH_SOURCE[0]} ]]; then
bash "${BASH_SOURCE[0]}" "$@"
return
fi
source simple
source makefifo
MyFunction3() {
echo "entered MyFunction3" >&4
echo "This is from MyFunction3"
ls 4444kkkkk
echo "leaving MyFunction3" >&4
}
MyFunction2() {
echo "entered MyFunction2" >&4
value="$(MyFunction3)"
echo "leaving MyFunction2" >&4
}
MyFunction1() {
echo "entered MyFunction1" >&4
local "flag=false"
try
(
echo "start of try" >&4
MyFunction2
echo "end of try" >&4
)
yrt
catch "[1-3]" "*" "Exception\ Type:\ ERR"; do
echo 'start of catch "[1-3]" "*" "Exception\ Type:\ ERR"'
local -i "i"
echo "-------------------------------------------------"
echo "Status: $(GetStatus)"
echo "Messages:"
for ((i=0; i<$(MessageCount); i++)); do
echo "$(GetMessage "$i")"
done
echo "-------------------------------------------------"
break
echo 'end of catch "[1-3]" "*" "Exception\ Type:\ ERR"'
hctac >&4
catch "1 3 5" "*" -n "Exception\ Type:\ ERR"; do
echo 'start of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"'
echo "-------------------------------------------------"
echo "Status: $(GetStatus)"
[[ $(MessageCount) -le 1 ]] || echo "$(GetMessage "1")"
echo "-------------------------------------------------"
break
echo 'end of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"'
hctac >&4
catch; do
echo 'start of catch' >&4
echo "failure"
flag="true"
echo 'end of catch' >&4
hctac
finally
echo "in finally"
yllanif >&4
"$flag" || echo "success"
echo "leaving MyFunction1" >&4
} 2>&6
ErrHandler() {
echo "EOF"
DefaultErrHandler "$@"
echo "Function: $3"
while read; do
[[ $REPLY != *EOF ]] || break
echo "$REPLY"
done
}
set -u
echo "starting" >&2
MakeFIFO "6"
TryCatchFinally -e -h ErrHandler -o /dev/fd/4 -v result /dev/fd/6 MyFunction1 4>&2
echo "result=$result"
exec >&6-
The above script was tested using GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin17)
. The output, from running this script, is shown below.
starting
entered MyFunction1
start of try
entered MyFunction2
entered MyFunction3
start of catch "[1-3]" "*" "Exception\ Type:\ ERR"
-------------------------------------------------
Status: 1
Messages:
Orginal Status: 1
Exception Type: ERR
Function: MyFunction3
ls: 4444kkkkk: No such file or directory
-------------------------------------------------
start of catch
end of catch
in finally
leaving MyFunction1
result=failure
Another example which uses a throw
can be created by replacing function MyFunction3
with the script shown below.
MyFunction3() {
echo "entered MyFunction3" >&4
echo "This is from MyFunction3"
throw "3" "Orginal Status: 3" "Exception Type: throw"
echo "leaving MyFunction3" >&4
}
The syntax for the throw
command is given below. If no parameters are present, then status and messages stored in the variables are used instead.
throw [status] [message ...]
The output, from executing the modified script, is shown below.
starting
entered MyFunction1
start of try
entered MyFunction2
entered MyFunction3
start of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"
-------------------------------------------------
Status: 3
Exception Type: throw
-------------------------------------------------
start of catch
end of catch
in finally
leaving MyFunction1
result=failure
Since everyone else is posting their methods, I figured I'd post the extension method I usually use for this:
EDIT: added int/long variants...and fixed a copypasta typo...
public static class Ext
{
private const long OneKb = 1024;
private const long OneMb = OneKb * 1024;
private const long OneGb = OneMb * 1024;
private const long OneTb = OneGb * 1024;
public static string ToPrettySize(this int value, int decimalPlaces = 0)
{
return ((long)value).ToPrettySize(decimalPlaces);
}
public static string ToPrettySize(this long value, int decimalPlaces = 0)
{
var asTb = Math.Round((double)value / OneTb, decimalPlaces);
var asGb = Math.Round((double)value / OneGb, decimalPlaces);
var asMb = Math.Round((double)value / OneMb, decimalPlaces);
var asKb = Math.Round((double)value / OneKb, decimalPlaces);
string chosenValue = asTb > 1 ? string.Format("{0}Tb",asTb)
: asGb > 1 ? string.Format("{0}Gb",asGb)
: asMb > 1 ? string.Format("{0}Mb",asMb)
: asKb > 1 ? string.Format("{0}Kb",asKb)
: string.Format("{0}B", Math.Round((double)value, decimalPlaces));
return chosenValue;
}
}
Hiding the overflow and fixing the position does the trick however with my fluid design it would fix it past the browsers width, so a width:100% fixed that.
body.modal-open{overflow:hidden;position:fixed;width:100%}
The next link will bring you to a great tutorial, that helped me a lot!
I nearly used everything in that article to create the SQLite database for my own C# Application.
Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.
After you added the reference, refer to the dll from your code using the following line on top of your class:
using System.Data.SQLite;
You can find the dll's here:
You can find the NuGet way here:
Up next is the create script. Creating a database file:
SQLiteConnection.CreateFile("MyDatabase.sqlite");
SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
sql = "insert into highscores (name, score) values ('Me', 9001)";
command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
m_dbConnection.Close();
After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.
Example on how to use transactions:
using (TransactionScope tran = new TransactionScope())
{
//Insert create script here.
//Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
tran.Complete();
}
I have used this mapping template to provide Body, Headers, Method, Path, and URL Query String Parameters to the Lambda event. I wrote a blog post explaining the template in more detail: http://kennbrodhagen.net/2015/12/06/how-to-create-a-request-object-for-your-lambda-event-from-api-gateway/
Here is the Mapping Template you can use:
{
"method": "$context.httpMethod",
"body" : $input.json('$'),
"headers": {
#foreach($param in $input.params().header.keySet())
"$param": "$util.escapeJavaScript($input.params().header.get($param))" #if($foreach.hasNext),#end
#end
},
"queryParams": {
#foreach($param in $input.params().querystring.keySet())
"$param": "$util.escapeJavaScript($input.params().querystring.get($param))" #if($foreach.hasNext),#end
#end
},
"pathParams": {
#foreach($param in $input.params().path.keySet())
"$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end
#end
}
}
Base on kkubasik's answer, check if folder exists before remove, more robust
import shutil
def remove_folder(path):
# check if folder exists
if os.path.exists(path):
# remove if exists
shutil.rmtree(path)
else:
# throw your exception to handle this special scenario
raise XXError("your exception")
remove_folder("/folder_name")
You are probably looking for get_attribute()
. An example is shown here as well
def test_chart_renders_from_url(self):
url = 'http://localhost:8000/analyse/'
self.browser.get(url)
org = driver.find_element_by_id('org')
# Find the value of org?
val = org.get_attribute("attribute name")
My solution: If it is correct*, update the data and viewable items without re-drawing the whole list. Else notifyDataSetChanged.
Correct - oldData size == new data size, and old data IDs and their order == new data IDs and order
How:
/**
* A View can only be used (visible) once. This class creates a map from int (position) to view, where the mapping
* is one-to-one and on.
*
*/
private static class UniqueValueSparseArray extends SparseArray<View> {
private final HashMap<View,Integer> m_valueToKey = new HashMap<View,Integer>();
@Override
public void put(int key, View value) {
final Integer previousKey = m_valueToKey.put(value,key);
if(null != previousKey) {
remove(previousKey);//re-mapping
}
super.put(key, value);
}
}
@Override
public void setData(final List<? extends DBObject> data) {
// TODO Implement 'smarter' logic, for replacing just part of the data?
if (data == m_data) return;
List<? extends DBObject> oldData = m_data;
m_data = null == data ? Collections.EMPTY_LIST : data;
if (!updateExistingViews(oldData, data)) notifyDataSetChanged();
else if (DEBUG) Log.d(TAG, "Updated without notifyDataSetChanged");
}
/**
* See if we can update the data within existing layout, without re-drawing the list.
* @param oldData
* @param newData
* @return
*/
private boolean updateExistingViews(List<? extends DBObject> oldData, List<? extends DBObject> newData) {
/**
* Iterate over new data, compare to old. If IDs out of sync, stop and return false. Else - update visible
* items.
*/
final int oldDataSize = oldData.size();
if (oldDataSize != newData.size()) return false;
DBObject newObj;
int nVisibleViews = m_visibleViews.size();
if(nVisibleViews == 0) return false;
for (int position = 0; nVisibleViews > 0 && position < oldDataSize; position++) {
newObj = newData.get(position);
if (oldData.get(position).getId() != newObj.getId()) return false;
// iterate over visible objects and see if this ID is there.
final View view = m_visibleViews.get(position);
if (null != view) {
// this position has a visible view, let's update it!
bindView(position, view, false);
nVisibleViews--;
}
}
return true;
}
and of course:
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
final View result = createViewFromResource(position, convertView, parent);
m_visibleViews.put(position, result);
return result;
}
Ignore the last param to bindView (I use it to determine whether or not I need to recycle bitmaps for ImageDrawable).
As mentioned above, the total number of 'visible' views is roughly the amount that fits on the screen (ignoring orientation changes etc), so no biggie memory-wise.
//load css first, then print <link> to header, and execute callback
//just set var href above this..
$.ajax({
url: href,
dataType: 'css',
success: function(){
$('<link rel="stylesheet" type="text/css" href="'+href+'" />').appendTo("head");
//your callback
}
});
For Jquery 1.2.6 and above ( omitting the fancy attributes functions above ).
I am doing it this way because I think that this will ensure that your requested stylesheet is loaded by ajax before you try to stick it into the head. Therefore, the callback is executed after the stylesheet is ready.
ArrayIndexOutOfBoundsException in simple words is -> you have 10 students in your class (int array size 10) and you want to view the value of the 11th student (a student who does not exist)
if you make this int i[3] then i takes values i[0] i[1] i[2]
for your problem try this code structure
double[] array = new double[50];
for (int i = 0; i < 24; i++) {
}
for (int j = 25; j < 50; j++) {
}
You need to order them.
SELECT * FROM messages GROUP BY from_id ORDER BY timestamp DESC LIMIT 1
You want to try String.format("%f", d)
, which will print your double in decimal notation. Don't use BigDecimal
at all.
Regarding the precision issue: You are first storing 47.48
in the double c
, then making a new BigDecimal
from that double
. The loss of precision is in assigning to c
. You could do
BigDecimal b = new BigDecimal("47.48")
to avoid losing any precision.
I wanted to add to the discussion above but don't have the reputation to comment.
Python 3.8 is not quite released yet, but it will even include the reversed()
function on dictionaries (removing another difference from OrderedDict
.
Dict and dictviews are now iterable in reversed insertion order using reversed(). (Contributed by Rémi Lapeyre in bpo-33462.) See what's new in python 3.8
I don't see any mention of the equality operator or other features of OrderedDict
so they are still not entirely the same.
With HTTP v1 API it is different
Example:
{
"message":{
"topic":"news",
"notification":{
"body":"Very good news",
"title":"Good news"
},
"android":{
"notification":{
"body":"Very good news",
"title":"Good news",
"sound":"default"
}
}
}
}
@media only screen and (max-width: 1026px) {
#fadeshow1 {
display: none;
}
}
Any time the screen is less than 1026 pixels wide, anything inside the { }
will apply.
Some browsers don't support media queries. You can get round this using a javascript library like Respond.JS
I just used Midhat's answer but appended CopyToDataTable()
on the end.
The code below is an extension to the answer that I used to quickly enable some paging.
int pageNum = 1;
int pageSize = 25;
DataTable dtPage = dt.Rows.Cast<System.Data.DataRow>().Skip((pageNum - 1) * pageSize).Take(pageSize).CopyToDataTable();
I have tried a lot of the suggestions on SO but this is the one that actually worked for me:
sudo sh -c 'echo /usr/local/mysql/bin > /etc/paths.d/mysql'
then you type
mysql
It will prompt you to enter your password.
A side note regarding this topic...
There is a 50 request limit for protocols that are not registered.
In this discussion apple mention that for a specific version of an app you can only query the canOpenUrl
a limited number of times and will fail after 50 calls for undeclared schemes. I've also seen that if the protocol is added once you have entered this failing state it will still fail.
Be aware of this, could be useful to someone.
You could use the method
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target
withString:(NSString *)replacement
...to get a new string with a substring replaced (See NSString
documentation for others)
Example use
NSString *str = @"This is a string";
str = [str stringByReplacingOccurrencesOfString:@"string"
withString:@"duck"];
You need to install gcc-c++
package.
yum install gcc-c++
In case anyone is still looking for this functionality: I made an Android library that has this ability and much more, called ExpandableFab (https://github.com/nambicompany/expandable-fab).
The Material Design spec refers to this functionality as 'Speed Dial' and ExpandableFab implements it along with many additional features.
Nearly everything is customizable (colors, text, size, placement, margins, animations and more) and optional (don't need an Overlay, or FabOptions, or Labels, or icons, etc). Every property can be accessed or set through XML layouts or programmatically - whatever you prefer.
Written 100% in Kotlin but comes with full JavaDoc and KDoc (published API is well documented). Also comes with an example app so you can see different use cases with 0 coding.
Github: https://github.com/nambicompany/expandable-fab
Library website (w/ links to full documentation): https://nambicompany.github.io/expandable-fab/
In addition to pattern matching with 'like' keyword. You can also perform search by using fulltext feature as below;
SELECT * FROM clients WHERE MATCH (shipping_name, billing_name, email) AGAINST ('mary')
No need for the option, just make the preferred width of the last column the maximum and it will take all the extra space.
table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(Integer.MAX_INT);
When you define a variable outside the scope of a function, that variable's value is actually written into your executable file. This means you can only use a constant value. Since you don't know everything about the runtime environment at compile time (which classes are available, what is their structure, etc.), you cannot create objective c objects until runtime, with the exception of constant strings, which are given a specific structure and guaranteed to stay that way. What you should do is initialize the variable to nil and use +initialize
to create your image. initialize
is a class method which will be called before any other method is called on your class.
Example:
NSImage *imageSegment = nil;
+ (void)initialize {
if(!imageSegment)
imageSegment = [[NSImage alloc] initWithContentsOfFile:@"/User/asd.jpg"];
}
- (id)init {
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
The easiest way to do this in my experience is with the Cloudmersive free native PHP library, just call convertDocumentDocxToPdf:
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');
$apiInstance = new Swagger\Client\Api\ConvertDocumentApi(
new GuzzleHttp\Client(),
$config
);
$input_file = "/path/to/file.txt"; // \SplFileObject | Input file to perform the operation on.
try {
$result = $apiInstance->convertDocumentDocxToPdf($input_file);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ConvertDocumentApi->convertDocumentDocxToPdf: ', $e->getMessage(), PHP_EOL;
}
?>
Be sure to replace $input_file with the appropriate file path. You can also configure it to use a byte array if you prefer to do it that way. The result will be the bytes of the converted PDF file.
As explained above the real question being asked here is how to enable core dumps on a system where they are not enabled. That question is answered here.
If you've come here hoping to learn how to generate a core dump for a hung process, the answer is
gcore <pid>
if gcore is not available on your system then
kill -ABRT <pid>
Don't use kill -SEGV as that will often invoke a signal handler making it harder to diagnose the stuck process
I think the new hotness is to use a ScheduledThreadPoolExecutor. Like so:
private final ScheduledThreadPoolExecutor executor_ =
new ScheduledThreadPoolExecutor(1);
this.executor_.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
update();
}
}, 0L, kPeriod, kTimeUnit);
"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"
No need to use scan
, if we need only one result.
No need to use Python's match
, when we have Ruby's String[regexp,#]
.
See: http://ruby-doc.org/core/String.html#method-i-5B-5D
Note: str[regexp, capture] ? new_str or nil
All the cool kids are doing functional programming (hello React users) these days so I thought I would give the functional solution. In my view it's actually a lot nicer than the imperatival for
and each
loops that have been proposed thus far and with ES6 syntax it is quite elegant.
There's now a great way of doing this called findIndex
which takes a function that return true
/false
based on whether the array element matches (as always, check for browser compatibility though).
var index = peoples.findIndex(function(person) {
return person.attr1 == "john"
}
With ES6 syntax you get to write this:
var index = peoples.findIndex(p => p.attr1 == "john")
If you're looking for index
where peoples[index].attr1 == "john"
use:
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
Step 1
Use .map()
to get an array of values given a particular key:
var values = object_array.map(function(o) { return o.your_key; });
The line above takes you from here:
var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];
To here:
var values = [ "bob", "john", "larry" ];
Step 2
Now we just use .indexOf()
to find the index of the key we want (which is, of course, also the index of the object we're looking for):
var index = values.indexOf(your_value);
Solution
We combine all of the above:
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
Or, if you prefer ES6 syntax:
var index = peoples.map((o) => o.attr1).indexOf("john");
var peoples = [_x000D_
{ "attr1": "bob", "attr2": "pizza" },_x000D_
{ "attr1": "john", "attr2": "sushi" },_x000D_
{ "attr1": "larry", "attr2": "hummus" }_x000D_
];_x000D_
_x000D_
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");_x000D_
console.log("index of 'john': " + index);_x000D_
_x000D_
var index = peoples.map((o) => o.attr1).indexOf("larry");_x000D_
console.log("index of 'larry': " + index);_x000D_
_x000D_
var index = peoples.map(function(o) { return o.attr1; }).indexOf("fred");_x000D_
console.log("index of 'fred': " + index);_x000D_
_x000D_
var index = peoples.map((o) => o.attr2).indexOf("pizza");_x000D_
console.log("index of 'pizza' in 'attr2': " + index);
_x000D_
Most of these answers were written in Python version 2.x or earlier. In Python 3.x the syntax for the print function has changed to require parentheses, i.e. print().
So, this earlier high score answer from user13993 in Python 2.x:
import inspect, os
print inspect.getfile(inspect.currentframe()) # script filename (usually with path)
print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # script directory
Becomes in Python 3.x:
import inspect, os
print(inspect.getfile(inspect.currentframe())) # script filename (usually with path)
print(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) ) # script directory
I don't think you can its an operator and its suppose to return one or the other. It's not if else statement replacement although it can be use for that on certain case.
I had a similar problem (Universal project, Visual Studio 2015), I solved it with the following changes:
In App.xml.cs was (it was ok):
namespace Test.Main {
Wrong, old version of App.xml:
x:Class="Test.Main"
Good, new version of App.xml:
x:Class="Test.Main.App"
imgtag.group(0)
or imgtag.group()
. This returns the entire match as a string. You are not capturing anything else either.
HTML code:
<ul class="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
CSS code:
ul.list li{
width: auto;
float: left;
}
A simple way of "binarize" an image is to compare to a threshold: For example you can compare all elements in a matrix against a value with opencv in c++
cv::Mat img = cv::imread("image.jpg", CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat bw = img > 128;
In this way, all pixels in the matrix greater than 128 now are white, and these less than 128 or equals will be black
Optionally, and for me gave good results is to apply blur
cv::blur( bw, bw, cv::Size(3,3) );
Later you can save it as said before with:
cv::imwrite("image_bw.jpg", bw);
I recently ran into the similar issue with react-native application. iPhone OS version was 13.1 I uninstalled the application and tried to install the app and noticed both location and notification permissions were not prompted.
On checking the settings, I could see my application was enabled for location(from previous installation) however there was no corresponding entry against the notification Tried uninstalling and rebooting without setting the time, it didn't work. Btw, I also tried to download the Appstore app, still same behavior.
The issue was resolved only after setting the device time.
The verbose
configuration option might allow you to see what you want. There is an example in the documentation.
NOTE: Read the comments below: The verbose config options doesn't seem to be available anymore.
I don't see an obvious problem with the above.
It's possible your ldap.conf
is being overridden, but the command-line options will take precedence, ldapsearch
will ignore BINDDN
in the main ldap.conf
, so the only parameter that could be wrong is the URI.
(The order is ETCDIR/ldap.conf
then ~/ldaprc
or ~/.ldaprc
and then ldaprc
in the current directory, though there environment variables which can influence this too, see man ldapconf
.)
Try an explicit URI:
ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
or prevent defaults with:
LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd
binary for these):
make sure your slapd.conf
is being used and is correct (as root)
slapd -T test -f slapd.conf -d 65535
You may have a left-over or default slapd.d
configuration directory which takes preference over your slapd.conf
(unless you specify your config explicitly with -f
, slapd.conf
is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.
stop OpenLDAP, then manually start slapd
in a separate terminal/console with debug enabled (as root, ^C to quit)
slapd -h ldap://localhost -d 481
then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd
without the -u
/-g
options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap
)
if debug is enabled, then try also
ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
Before the closing body
tag add this (reference to jQuery library). Other hosted libraries can be found here
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
And this
<script>
//paste your code here
</script>
It should look something like this
<body>
........
........
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script> Your code </script>
</body>
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
You can use * for import all jars into a folder when adding in conf/spark-defaults.conf .
spark.driver.extraClassPath /fullpath/*
spark.executor.extraClassPath /fullpath/*
First of all, I wouldn't use a multi-dimensional array. Only ever seen bad things come of it.
Set up your variable like this:
IEnumerable<IEnumerable<string>> data = new[] {
new[]{"...", "...", "..."},
... etc ...
};
Then you'd simply go:
var firsts = data.Select(x => x.FirstOrDefault()).Where(x => x != null);
The Where makes sure it prunes any nulls if you have an empty list as an item inside.
Alternatively you can implement it as:
string[][] = new[] {
new[]{"...","...","..."},
new[]{"...","...","..."},
... etc ...
};
This could be used similarly to a [x,y]
array but it's used like this: [x][y]
The best solution to me is to create a client service that you'll instantiate with your token an use it to wrap axios
.
import axios from 'axios';
const client = (token = null) => {
const defaultOptions = {
headers: {
Authorization: token ? `Token ${token}` : '',
},
};
return {
get: (url, options = {}) => axios.get(url, { ...defaultOptions, ...options }),
post: (url, data, options = {}) => axios.post(url, data, { ...defaultOptions, ...options }),
put: (url, data, options = {}) => axios.put(url, data, { ...defaultOptions, ...options }),
delete: (url, options = {}) => axios.delete(url, { ...defaultOptions, ...options }),
};
};
const request = client('MY SECRET TOKEN');
request.get(PAGES_URL);
In this client, you can also retrieve the token from the localStorage / cookie, as you want.
This class was compiled with a JDK more recent than the one used for execution.
The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.
Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).
I find this way more readable:
$result = $mysqli->query('select count(*) as `c` from `table`');
$count = $result->fetch_object()->c;
echo "there are {$count} rows in the table";
Not that I have anything against arrays...
Sorry to re-post this. But I really haven't seen any other implementation that gives the quality I needed.
/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h, s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param {number} h The hue
* @param {number} s The saturation
* @param {number} l The lightness
* @return {Array} The RGB representation
*/
function hue2rgb($p, $q, $t){
if($t < 0) $t += 1;
if($t > 1) $t -= 1;
if($t < 1/6) return $p + ($q - $p) * 6 * $t;
if($t < 1/2) return $q;
if($t < 2/3) return $p + ($q - $p) * (2/3 - $t) * 6;
return $p;
}
function hslToRgb($h, $s, $l){
if($s == 0){
$r = $l;
$g = $l;
$b = $l; // achromatic
}else{
$q = $l < 0.5 ? $l * (1 + $s) : $l + $s - $l * $s;
$p = 2 * $l - $q;
$r = hue2rgb($p, $q, $h + 1/3);
$g = hue2rgb($p, $q, $h);
$b = hue2rgb($p, $q, $h - 1/3);
}
return array(round($r * 255), round($g * 255), round($b * 255));
}
/* Uncomment to test * /
for ($i=0;$i<360;$i++) {
$rgb=hslToRgb($i/360, 1, .9);
echo '<div style="background-color:rgb(' .$rgb[0] . ', ' . $rgb[1] . ', ' . $rgb[2] . ');padding:2px;"></div>';
}
/* End Test */
If you have problems like that, first of all your TC
folder put in to the C:..drive.
after completing installation open turbo c blue screen.
there is a OPTIONS > Directories
..in that you can see for option to set up path..
C:\TC\INCUDE
C:\TC\LIB
C:\TC\BIN
..otherwise you can set another path where you want to store your output..Finally you can give OK and finished processes.. It will now work properly
You need to use array_merge_recursive
instead of array_merge
. Of course there can only be one key equal to 'c'
in the array, but the associated value will be an array containing both 3
and 4
.
I was using firefox and some reason, it was not taking the click command though from past 2months it was working. My feeling was to make use of sendKeys and this page solved the problem. Now I am using sendKeys(Keys.Enter)
for those who need to print the call stack while using pdb, just do
(Pdb) where