There’s a gem like quiet_assets that will silence these errors in your logs if, like me, you didn’t want to have to add these files to your Rails app:
You can do these in unix shell:
java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main
You can do these in windows powershell:
java -cp "MyJar.jar;lib\*" com.somepackage.subpackage.Main
no need for the padding or the corners.
here's a sample:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
android:angle="270"/>
</shape>
based on :
This should work fine:
{{ 'http://' ~ app.request.host }}
To add a filter - like 'trans' - in the same tag use
{{ ('http://' ~ app.request.host) | trans }}
As Adam Elsodaney points out, you can also use string interpolation, this does require double quoted strings:
{{ "http://#{app.request.host}" }}
Try writing the properties as a comma separated list, then split the value after the properties file is loaded. For example
a=one,two,three
b=nine,ten,fourteen
You can also use org.apache.commons.configuration and change the value delimiter using the AbstractConfiguration.setListDelimiter(char) method if you're using comma in your values.
//Run with this HTML structure
<!DOCTYPE html>
<head>
<title>OOJS</title>
</head>
<body>
<div id="status">
</div>
<script type="text/javascript" src="scriptfile.js"></script>
</body>
</html>
def round_to_next5(n):
return n + (5 - n) % 5
Interaction of Javascript and PHP
We all grew up knowing that Javascript ran on the Client Side (ie the browser) and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.
But -- good news; it can be made to work and here's how.
The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.
First, to clarify the DHTML usage I'll cite this DHTML example:
<script type="text/javascript">
function updateContent() {
var frameObj = document.getElementById("frameContent");
var y = (frameObj.contentWindow || frameObj.contentDocument);
if (y.document) y = y.document;
y.body.style.backgroundColor="red"; // demonstration of failure to alter the display
// create a default, simplistic alteration usinga fixed string.
var textMsg = 'Say good night Gracy';
y.write(textMsg);
y.body.style.backgroundColor="#00ee00"; // visual confirmation that the updateContent() was effective
}
</script>
Assuming we have an html file with the ID="frameContent" somewhere, then we can alter the display with a simple < body onload="updateContent()" >
Golly gee; we don't need PHP to do that now do we! But that creates a structure for applying PHP provided content.
We change the webpage in question into a PHTML type to allow the server side PHP access to the content:
**foo.html becomes foo.phtml**
and we add to the top of that page. We also cause the php data to be loaded into globals for later access - - like this:
<?php
global $msg1, $msg2, $textMsgPHP;
function getContent($filename) {
if ($theData = file_get_contents($filename, FALSE)) {
return "$theData";
} else {
echo "FAILED!";
}
}
function returnContent($filename) {
if ( $theData = getContent($filename) ) {
// this works ONLY if $theData is one linear line (ie remove all \n)
$textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
return "$textPHP";
} else {
echo '<span class="ERR">Error opening source file :(\n</span>'; # $filename!\n";
}
}
// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 = returnContent('dummy_frame_data.txt');
$msg2 = returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');
?>
Now our javascripts can get to the PHP globals like this:
// by accessig the globals var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';
In the javascript, replace
var textMsg = 'Say good night Gracy';
with: // using php returnContent()
var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';
Summary:
To be resolved: calling updateContent() with a filename and using it via onClick() instead of onLoad()
An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it
Simply add static
in the declaration of these two methods and the compile time error will disappear!
By default in C# methods are instance methods, and they receive the implicit "self" argument. By making them static, no such argument is needed (nor available), and the method must then of course refrain from accessing any instance (non-static) objects or methods of the class.
More info on static methods
Provided the class and the method's access modifiers (public vs. private) are ok, a static method can then be called from anywhere without having to previously instantiate a instance of the class. In other words static methods are used with the following syntax:
className.classMethod(arguments)
rather than
someInstanceVariable.classMethod(arguments)
A classical example of static methods are found in the System.Math class, whereby we can call a bunch of these methods like
Math.Sqrt(2)
Math.Cos(Math.PI)
without ever instantiating a "Math" class (in fact I don't even know if such an instance is possible)
As an update,appears that on windows clock() measures wall clock time (with CLOCKS_PER_SEC precision)
http://msdn.microsoft.com/en-us/library/4e2ess30(VS.71).aspx
while on Linux it measures cpu time across cores used by current process
http://www.manpagez.com/man/3/clock
and (it appears, and as noted by the original poster) actually with less precision than CLOCKS_PER_SEC, though maybe this depends on the specific version of Linux.
Although the accepted answer here is technically correct, there seems to be some confusion amongst users based on the comments. When working with a ViewBag in a .cshtml file, you must use @Html.Raw
otherwise your data, after being unescaped by the ConfigurationManager, will become re-escaped once again. Use Html.Raw()
to prevent this from occurring.
If you want to use native JS, the other answers provide good solutions.
But if you're willing to write self-referencing objects like:
{
a: ...,
b: "${this.a + this.a}",
}
I wrote an npm library called self-referenced-object that supports that syntax and returns a native object.
Just look at setAccessible()
method used to access private
fields and methods:
Now there is a lot more conditions required for this method to work. The only reason it doesn't break almost all of older software is that modules autogenerated from plain JARs are very permissive (open and export everything for everyone).
At first link fontwaesome CSS file in your HTML file then create an after or before pseudo class like "font-family: "FontAwesome"; content: "\f101";" then save. I hope this work good.
following are ways to access your different directories:-
./ = Your current directory
../ = One directory lower
../../ = Two directories lower
../../../ = Three directories lower
To complete oscarbranson's answer: it's possible to automatically pick console or notebook versions of progress bar depending on where it's being run from:
from tqdm.autonotebook import tqdm
More info can be found here
Another solution is to put data definition into a separate file.
The idea is to write data common for both model and migration into a separate file, then require it in both the migration and the model. Then in the model we can add validations, while the migration is already good to go.
In order to not clutter this post with tons of code i wrote a GitHub gist.
See it here: https://gist.github.com/igorvolnyi/f7989fc64006941a7d7a1a9d5e61be47
First in your terminal:
rails g migration change_date_format_in_my_table
Then in your migration file:
For Rails >= 3.2:
class ChangeDateFormatInMyTable < ActiveRecord::Migration
def up
change_column :my_table, :my_column, :datetime
end
def down
change_column :my_table, :my_column, :date
end
end
In the layout (app/design/frontend/your_theme/layout/default.xml):
<default>
<cms_page> <!-- need to be redefined for your needs -->
<reference name="content">
<block type="cms/block" name="cms_newest_product" as="cms_newest_product">
<action method="setBlockId"><block_id>newest_product</block_id></action>
</block>
</reference>
</cms_page>
</default>
In your phtml template:
<?php echo $this->getChildHtml('newest_product'); ?>
Don't forget about cache cleaning.
I think it help.
No hack or js needed. Just apply the following rule to your root element:
min-height: 100%;
height: auto;
It will automatically choose the bigger one from the two as its height, which means if the content is longer than the browser, it will be the height of the content, otherwise, the height of the browser. This is standard css.
I found to be the the askpass
command useful
password=$(/lib/cryptsetup/askpass "Give a password")
Every input character is replaced by *. See: Give a password ****
Here is full code. The result is exactly what you want.
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
if __name__ == '__main__':
animal = Animal()
temp = vars(animal)
for item in temp:
print item , ' : ' , temp[item]
#print item , ' : ', temp[item] ,
INSERT INTO wp_bp_activity
(
user_id,
component,
`type`,
`action`,
content,
primary_link,
item_id,
secondary_item_id,
date_recorded,
hide_sitewide,
mptt_left,
mptt_right
)
VALUES(
1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
)
You want nohup. See http://nixcraft.com/linux-software/313-ssh-nohup-connection.html
It's possible if you believe. Hehe. try this code.
public function add_new_enum($new_value)
{
$table="product";
$column="category";
$row = $this->db->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ? AND COLUMN_NAME = ?", array($table, $column))->row_array();
$old_category = array();
$new_category="";
foreach (explode(',', str_replace("'", '', substr($row['COLUMN_TYPE'], 5, (strlen($row['COLUMN_TYPE']) - 6)))) as $val)
{
//getting the old category first
$old_category[$val] = $val;
$new_category.="'".$old_category[$val]."'".",";
}
//after the end of foreach, add the $new_value to $new_category
$new_category.="'".$new_value."'";
//Then alter the table column with the new enum
$this->db->query("ALTER TABLE product CHANGE category category ENUM($new_category)");
}
What about the following snippet?
require 'json'
value = '{"val":"test","val1":"test1","val2":"test2"}'
puts JSON.parse(value) # => {"val"=>"test","val1"=>"test1","val2"=>"test2"}
They are signals that application developers use. The kernel shouldn't ever send these to a process. You can send them using kill(2)
or using the utility kill(1)
.
If you intend to use signals for synchronization you might want to check real-time signals (there's more of them, they are queued, their delivery order is guaranteed etc).
For fresh setup of LAMP running php 7 edit the file /etc/httpd/conf/httpd.conf Note: make sure to make backup for it before changing anything.
Paste this at the very bottom of the file:
<IfModule php7_module>
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
Then, search for LoadModule and paste the following line:
LoadModule php7_module modules/libphp7.so
This line will simply ask httpd to load the php 7 module
Then restart httpd
This means your array is missing the key you're looking for. I handle this with a function which either returns the value if it exists or it returns a default value instead.
def keyCheck(key, arr, default):
if key in arr.keys():
return arr[key]
else:
return default
myarray = {'key1':1, 'key2':2}
print keyCheck('key1', myarray, '#default')
print keyCheck('key2', myarray, '#default')
print keyCheck('key3', myarray, '#default')
Output:
1
2
#default
The accepted answer still did not work for me
I used
git rm -r --cached .
git add .
git commit -m "fixing .gitignore"
Found the answer from here
Try this code,
public void ConnectToAccess()
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data source= C:\Documents and Settings\username\" +
@"My Documents\AccessFile.mdb";
try
{
conn.Open();
// Insert code to process data.
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}
finally
{
conn.Close();
}
}
http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx
The SET
clause should come after the table specification.
UPDATE business AS b
INNER JOIN business_geocode g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
b.mapy = g.longitude
WHERE (b.mapx = '' or b.mapx = 0) and
g.latitude > 0
Here is a VB.Net example if you are trying to retrieve the value of a variable from within a page loaded in a WebBrowser control.
Step 1) Add a COM reference in your project to Microsoft HTML Object Library
Step 2) Next, add this VB.Net code to your Form1 to import the mshtml library:
Imports mshtml
Step 3) Add this VB.Net code above your "Public Class Form1" line:
<System.Runtime.InteropServices.ComVisibleAttribute(True)>
Step 4) Add a WebBrowser control to your project
Step 5) Add this VB.Net code to your Form1_Load function:
WebBrowser1.ObjectForScripting = Me
Step 6) Add this VB.Net sub which will inject a function "CallbackGetVar" into the web page's Javascript:
Public Sub InjectCallbackGetVar(ByRef wb As WebBrowser)
Dim head As HtmlElement
Dim script As HtmlElement
Dim domElement As IHTMLScriptElement
head = wb.Document.GetElementsByTagName("head")(0)
script = wb.Document.CreateElement("script")
domElement = script.DomElement
domElement.type = "text/javascript"
domElement.text = "function CallbackGetVar(myVar) { window.external.Callback_GetVar(eval(myVar)); }"
head.AppendChild(script)
End Sub
Step 7) Add the following VB.Net sub which the Javascript will then look for when invoked:
Public Sub Callback_GetVar(ByVal vVar As String)
Debug.Print(vVar)
End Sub
Step 8) Finally, to invoke the Javascript callback, add this VB.Net code when a button is pressed, or wherever you like:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
WebBrowser1.Document.InvokeScript("CallbackGetVar", New Object() {"NameOfVarToRetrieve"})
End Sub
Step 9) If it surprises you that this works, you may want to read up on the Javascript "eval" function, used in Step 6, which is what makes this possible. It will take a string and determine whether a variable exists with that name and, if so, returns the value of that variable.
The steps are as follows :
WAMP\bin\php\(your version of php)\
php.ini
extension=php_curl.dll
WAMP\bin\Apache\(your version of apache)\bin\
php.ini
extension=php_curl.dll
You should run:
pip install protobuf
That will install Google protobuf and after that you can run that Python script.
As per this link.
(Which isn't true, because it stands for Representational, but it's a good trick to remember the importance of Resources in REST).
About PUT /groups/api/v1/groups/{group id}/status/activate
: you are not updating an "activate". An "activate" is not a thing, it's a verb. Verbs are never good resources. A rule of thumb: if the action, a verb, is in the URL, it probably is not RESTful.
What are you doing instead? Either you are "adding", "removing" or "updating" an activation on a Group, or if you prefer: manipulating a "status"-resource on a Group. Personally, I'd use "activations" because they are less ambiguous than the concept "status": creating a status is ambiguous, creating an activation is not.
POST /groups/{group id}/activation
Creates (or requests the creation of) an activation.PATCH /groups/{group id}/activation
Updates some details of an existing activation. Since a group has only one activation, we know what activation-resource we are referring to.PUT /groups/{group id}/activation
Inserts-or-replaces the old activation. Since a group has only one activation, we know what activation-resource we are referring to.DELETE /groups/{group id}/activation
Will cancel, or remove the activation.This pattern is useful when the "activation" of a Group has side-effects, such as payments being made, mails being sent and so on. Only POST and PATCH may have such side-effects. When e.g. a deletion of an activation needs to, say, notify users over mail, DELETE is not the right choice; in that case you probably want to create a deactivation resource: POST /groups/{group_id}/deactivation
.
It is a good idea to follow these guidelines, because this standard contract makes it very clear for your clients, and all the proxies and layers between the client and you, know when it is safe to retry, and when not. Let's say the client is somewhere with flaky wifi, and its user clicks on "deactivate", which triggers a DELETE
: If that fails, the client can simply retry, until it gets a 404, 200 or anything else it can handle. But if it triggers a POST to deactivation
it knows not to retry: the POST implies this.
Any client now has a contract, which, when followed, will protect against sending out 42 emails "your group has been deactivated", simply because its HTTP-library kept retrying the call to the backend.
PATCH /groups/{group id}
In case you wish to update an attribute. E.g. the "status" could be an attribute on Groups that can be set. An attribute such as "status" is often a good candidate to limit to a whitelist of values. Examples use some undefined JSON-scheme:
PATCH /groups/{group id} { "attributes": { "status": "active" } }
response: 200 OK
PATCH /groups/{group id} { "attributes": { "status": "deleted" } }
response: 406 Not Acceptable
PUT /groups/{group id}
In case you wish to replace an entire Group. This does not necessarily mean that the server actually creates a new group and throws the old one out, e.g. the ids might remain the same. But for the clients, this is what PUT can mean: the client should assume he gets an entirely new item, based on the server's response.
The client should, in case of a PUT
request, always send the entire resource, having all the data that is needed to create a new item: usually the same data as a POST-create would require.
PUT /groups/{group id} { "attributes": { "status": "active" } }
response: 406 Not Acceptable
PUT /groups/{group id} { "attributes": { "name": .... etc. "status": "active" } }
response: 201 Created or 200 OK, depending on whether we made a new one.
A very important requirement is that PUT
is idempotent: if you require side-effects when updating a Group (or changing an activation), you should use PATCH
. So, when the update results in e.g. sending out a mail, don't use PUT
.
you can simply do this..
<img src={"http://img.example.com/test/" + this.props.url +"/1.jpg"}/>
<input type="text" (keypress)="myMethod(myInput.value)" #myInput />
archive .ts
myMethod(value:string){
...
...
}
First of all you should stop using mysql_*. MySQL supports multiple inserting like
INSERT INTO example
VALUES
(100, 'Name 1', 'Value 1', 'Other 1'),
(101, 'Name 2', 'Value 2', 'Other 2'),
(102, 'Name 3', 'Value 3', 'Other 3'),
(103, 'Name 4', 'Value 4', 'Other 4');
You just have to build one string in your foreach loop which looks like that
$values = "(100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1')";
and then insert it after the loop
$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) VALUES ".$values;
Another way would be Prepared Statements, which are even more suited for your situation.
The question would need more details.
Do you want just to look at a file (eg. a log file) or to edit it?
Do you have more memory than the size of the file you want to load or less?
For example, TheGun, a very small text editor written in assembly language, claims to "not have an effective file size limit and the maximum size that can be loaded into it is determined by available memory and loading speed of the file. [...] It has been speed optimised for both file load and save."
To abstract the memory limit, I suppose one can use mapped memory. But then, if you need to edit the file, some clever method should be used, like storing in memory the local changes, and applying them chunk by chunk when saving. Might be ineffective in some cases (big search/replace for example).
I think this is more clear than describing it in words
s = 'python'
print(len(s))
6
print(s[5])
'n'
print(s[len(s) - 1])
'n'
print(s[-1])
'n'
The URL parameters are available in request.args
, which is an ImmutableMultiDict that has a get
method, with optional parameters for default value (default
) and type (type
) - which is a callable that converts the input value to the desired format. (See the documentation of the method for more details.)
from flask import request
@app.route('/my-route')
def my_route():
page = request.args.get('page', default = 1, type = int)
filter = request.args.get('filter', default = '*', type = str)
Examples with the code above:
/my-route?page=34 -> page: 34 filter: '*'
/my-route -> page: 1 filter: '*'
/my-route?page=10&filter=test -> page: 10 filter: 'test'
/my-route?page=10&filter=10 -> page: 10 filter: '10'
/my-route?page=*&filter=* -> page: 1 filter: '*'
The above answer doesn't work. You have to set DeliveryMethod = SmtpDeliveryMethod.Network
or it will come back with a "client was not authenticated" error. Also it's always a good idea to put a timeout.
Revised code:
using System.Net.Mail;
using System.Net;
var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "To Name");
const string fromPassword = "password";
const string subject = "test";
const string body = "Hey now!!";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
From 1st february Apple will reject app built only for iOS6 or lower. Here is also the official communication from Apple. Better start building for iOS7.
To clarify my statement: If you build for iOS6 or lower, apple will reject your app. If you build for iOS7 AND lower everything is fine, this means:
The content of the Apple email is pretty clear at me
"Make sure your apps work seamlessly with the innovative technologies in iOS 7. Starting February 1, new apps and app updates submitted to the App Store must be built with Xcode 5 and iOS 7 SDK."
Python does not support method overloading like Java or C++. We may overload the methods, but we can only use the latest defined method.
# First sum method.
# Takes two argument and print their sum
def sum(a, b):
s = a + b
print(s)
# Second sum method
# Takes three argument and print their sum
def sum(a, b, c):
s = a + b + c
print(s)
# Uncommenting the below line shows an error
# sum(4, 5)
# This line will call the second sum method
sum(4, 5, 5)
We need to provide optional arguments or *args in order to provide a different number of arguments on calling.
Courtesy Python | Method Overloading
Expanding on @carestad example, which I find easier, is to run the script with cron and have the environment in the script.
In crontab -e file:
SHELL=/bin/bash
*/1 * * * * $HOME/cron_job.sh
In cron_job.sh file:
#!/bin/bash
source $HOME/.bash_profile
some_other_cmd
Any command after the source of .bash_profile will have your environment as if you logged in.
i hope this will work too, try using"is_null"
<?php
$web = the_field('website');
if (!is_null($web)) {
?>
....html code here
<?php
} else {
echo "Niente";
}
?>
http://php.net/manual/en/function.is-null.php
hope that suits you..
It is more light weight to use a SpannableString
instead of html markup. It helps me to see visual examples so here is a supplemental answer.
This is a single TextView
.
// set the text
SpannableString s1 = new SpannableString("bold\n");
SpannableString s2 = new SpannableString("italic\n");
SpannableString s3 = new SpannableString("foreground color\n");
SpannableString s4 = new SpannableString("background color\n");
SpannableString s5 = new SpannableString("underline\n");
SpannableString s6 = new SpannableString("strikethrough\n");
SpannableString s7 = new SpannableString("bigger\n");
SpannableString s8 = new SpannableString("smaller\n");
SpannableString s9 = new SpannableString("font\n");
SpannableString s10 = new SpannableString("URL span\n");
SpannableString s11 = new SpannableString("clickable span\n");
SpannableString s12 = new SpannableString("overlapping spans\n");
// set the style
int flag = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;
s1.setSpan(new StyleSpan(Typeface.BOLD), 0, s1.length(), flag);
s2.setSpan(new StyleSpan(Typeface.ITALIC), 0, s2.length(), flag);
s3.setSpan(new ForegroundColorSpan(Color.RED), 0, s3.length(), flag);
s4.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, s4.length(), flag);
s5.setSpan(new UnderlineSpan(), 0, s5.length(), flag);
s6.setSpan(new StrikethroughSpan(), 0, s6.length(), flag);
s7.setSpan(new RelativeSizeSpan(2), 0, s7.length(), flag);
s8.setSpan(new RelativeSizeSpan(0.5f), 0, s8.length(), flag);
s9.setSpan(new TypefaceSpan("monospace"), 0, s9.length(), flag);
s10.setSpan(new URLSpan("https://developer.android.com"), 0, s10.length(), flag);
s11.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(getApplicationContext(), "Span clicked", Toast.LENGTH_SHORT).show();
}
}, 0, s11.length(), flag);
s12.setSpan(new ForegroundColorSpan(Color.RED), 0, 11, flag);
s12.setSpan(new BackgroundColorSpan(Color.YELLOW), 4, s12.length(), flag);
s12.setSpan(new UnderlineSpan(), 4, 11, flag);
// build the string
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(s1);
builder.append(s2);
builder.append(s3);
builder.append(s4);
builder.append(s5);
builder.append(s6);
builder.append(s7);
builder.append(s8);
builder.append(s9);
builder.append(s10);
builder.append(s11);
builder.append(s12);
// set the text view with the styled text
textView.setText(builder);
// enables clicking on spans for clickable span and url span
textView.setMovementMethod(LinkMovementMethod.getInstance());
This example was originally inspired from here.
It is in fact NTFS permissions, and a strange bug in SQL Server. I'm not sure the above bug report is accurate, or may refer to an additional bug.
To resolve this on Windows 7, I ran SQL Server Management Studio normally (not as Administrator). I then attempted to Attach the MDF file. In the process, I used the UI rather than pasting in the path. I noticed that the path was cut off from me. This is because the MS SQL Server (SQLServerMSSQLUser$machinename$SQLEXPRESS) user that the software adds for you does not have permissions to access the folder (in this case a folder deep in my own user folders).
Pasting the path and proceeding results in the above error. So - I gave the MS SQL Server user permissions to read starting from the first directory it was denied from (my user folder). I then immediately cancelled the propagation operation because it can take an eternity, and again applied read permissions to the next subfolder necessary, and let that propagate fully.
Finally, I gave the MS SQL Server user Modify permissions to the .mdf and .ldf files for the db.
I can now Attach to the database files.
By default .vs folder is hidden (at least in my case).
If you are not able to find the .vs folder, follow the below steps.
Attributes
section, click Hidden
check box(default unchecked),step 3
, this time you need to uncheck
the 'Hidden' option that you checked previously.Now should be able to see .vs folder.
Give the name to both of the buttons and Get the check the value from form.
<div>
<input name="submitButton" type="submit" value="Register" />
</div>
<div>
<input name="cancelButton" type="submit" value="Cancel" />
</div>
On controller side :
public ActionResult Save(FormCollection form)
{
if (this.httpContext.Request.Form["cancelButton"] !=null)
{
// return to the action;
}
else if(this.httpContext.Request.Form["submitButton"] !=null)
{
// save the oprtation and retrun to the action;
}
}
The easisest way to get a posted json string, for example, is to read the contents of 'php://input' and then decode it. For example i had a simple Zend route:
'save-json' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
'options' => array(
'route' => '/save-json/',
'defaults' => array(
'controller' => 'CDB\Controller\Index',
'action' => 'save-json',
),
),
),
and i wanted to post data to it using Angular's $http.post. The post was fine but the retrive method in Zend
$this->params()->fromPost('paramname');
didn't get anything in this case. So my solution was, after trying all kinds of methods like $_POST and the other methods stated above, to read from 'php://':
$content = file_get_contents('php://input');
print_r(json_decode($content));
I got my json array in the end. Hope this helps.
Here is an example using css3:
CSS:
html, body {
height: 100%;
margin: 0;
}
#wrap {
padding: 10px;
min-height: -webkit-calc(100% - 100px); /* Chrome */
min-height: -moz-calc(100% - 100px); /* Firefox */
min-height: calc(100% - 100px); /* native */
}
.footer {
position: relative;
clear:both;
}
HTML:
<div id="wrap">
body content....
</div>
<footer class="footer">
footer content....
</footer>
Update
As @Martin pointed, the ´position: relative´ is not mandatory on the .footer
element, the same for clear:both
. These properties are only there as an example. So, the minimum css necessary to stick the footer on the bottom should be:
html, body {
height: 100%;
margin: 0;
}
#wrap {
min-height: -webkit-calc(100% - 100px); /* Chrome */
min-height: -moz-calc(100% - 100px); /* Firefox */
min-height: calc(100% - 100px); /* native */
}
Also, there is an excellent article at css-tricks showing different ways to do this: https://css-tricks.com/couple-takes-sticky-footer/
Basically, you write a pipe which you can then use in the *ngFor
directive.
In your component:
filterargs = {title: 'hello'};
items = [{title: 'hello world'}, {title: 'hello kitty'}, {title: 'foo bar'}];
In your template, you can pass string, number or object to your pipe to use to filter on:
<li *ngFor="let item of items | myfilter:filterargs">
In your pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'myfilter',
pure: false
})
export class MyFilterPipe implements PipeTransform {
transform(items: any[], filter: Object): any {
if (!items || !filter) {
return items;
}
// filter items array, items which match and return true will be
// kept, false will be filtered out
return items.filter(item => item.title.indexOf(filter.title) !== -1);
}
}
Remember to register your pipe in app.module.ts
; you no longer need to register the pipes in your @Component
import { MyFilterPipe } from './shared/pipes/my-filter.pipe';
@NgModule({
imports: [
..
],
declarations: [
MyFilterPipe,
],
providers: [
..
],
bootstrap: [AppComponent]
})
export class AppModule { }
Here's a Plunker which demos the use of a custom filter pipe and the built-in slice pipe to limit results.
Please note (as several commentators have pointed out) that there is a reason why there are no built-in filter pipes in Angular.
You can get just the edition name by using the following steps.
By passing a block to find_or_create
, you can pass additional parameters that will be added to the object if it is created new. This is useful if you are validating the presence of a field that you aren't searching by.
Assuming:
class GroupMember < ActiveRecord::Base
validates_presence_of :name
end
then
GroupMember.where(:member_id => 4, :group_id => 7).first_or_create { |gm| gm.name = "John Doe" }
will create a new GroupMember with the name "John Doe" if it doesn't find one with member_id 4
and group_id 7
In C everything is pass-by-value. The use of pointers gives us the illusion that we are passing by reference because the value of the variable changes. However, if you were to print out the address of the pointer variable, you will see that it doesn't get affected. A copy of the value of the address is passed-in to the function. Below is a snippet illustrating that.
void add_number(int *a) {
*a = *a + 2;
}
int main(int argc, char *argv[]) {
int a = 2;
printf("before pass by reference, a == %i\n", a);
add_number(&a);
printf("after pass by reference, a == %i\n", a);
printf("before pass by reference, a == %p\n", &a);
add_number(&a);
printf("after pass by reference, a == %p\n", &a);
}
before pass by reference, a == 2
after pass by reference, a == 4
before pass by reference, a == 0x7fff5cf417ec
after pass by reference, a == 0x7fff5cf417ec
The only thing I would update in Apple code is the keyboardWillBeHidden: method, to provide smooth transition.
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
[UIView animateWithDuration:0.4 animations:^{
self.scrollView.contentInset = contentInsets;
}];
self.scrollView.scrollIndicatorInsets = contentInsets;
}
Top answer with most upvotes isn't wrong but still the opposite of what I would post. I say it will totally work to start an exe file and you can do this in the context of any user. Logically you just can't have any user interface or ask for user input...
Here is my advice:
Example to start e.g. plink.exe. You could even listen to the output:
var psi = new ProcessStartInfo()
{
FileName = "./Client/plink.exe", //path to your *.exe
Arguments = "-telnet -P 23 127.0.0.1 -l myUsername -raw", //arguments
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true //no window, you can't show it anyway
};
var p = Process.Start(psi);
I took LocalSystem account which is default and more than Local Service. It worked fine without having to enter login information of a specific user. I didn't even tick the checkbox "Allow service to interact with desktop" which you could if you need higher permissions.
Lastly I just want to say how funny it is that the top answer says quite the opposite of my answer and still both of us are right it's just how you interpret the question :-D. If you now say but you can't with the windows service project type - You CAN but I had this before and installation was sketchy and it was maybe kind of an unintentional hack until I found NSSM.
The syntax
variable=value command
is often used to set an environment variables for a specific process. However, you must understand which process gets what variable and who interprets it. As an example, using two shells:
a=5
# variable expansion by the current shell:
a=3 bash -c "echo $a"
# variable expansion by the second shell:
a=3 bash -c 'echo $a'
The result will be 5 for the first echo and 3 for the second.
I was working on a different project when I saw this question, this is the solution I used and it seems to work.
#[image id] , p {
vertical-align: middle;
display: inline-block;
}
if it doesn't, just try :
float:right;
float:left;
or
display: inline
instead of inline-block
This worked for me, hope this helped!
Of course you could use blocks as properties. But make sure they are declared as @property(copy). For example:
typedef void(^TestBlock)(void);
@interface SecondViewController : UIViewController
@property (nonatomic, copy) TestBlock block;
@end
In MRC, blocks capturing context variables are allocated in stack; they will be released when the stack frame is destroyed. If they are copied, a new block will be allocated in heap, which can be executed later on after the stack frame is poped.
You don't really gain much by doing this, in fact it slows method_a
down because it'll define and recompile the other function every time it's called. Given that, it would probably be better to just prefix the function name with underscore to indicate it's a private method -- i.e. _method_b
.
I suppose you might want to do this if the nested function's definition varied each time for some reason, but that may indicate a flaw in your design. That said, there is a valid reason to do this to allow the nested function to use arguments that were passed to the outer function but not explicitly passed on to them, which sometimes occurs when writing function decorators, for example. It's what is being shown in the accepted answer although a decorator is not being defined or used.
Update:
Here's proof that nesting them is slower (using Python 3.6.1), although admittedly not by much in this trivial case:
setup = """
class Test(object):
def separate(self, arg):
some_data = self._method_b(arg)
def _method_b(self, arg):
return arg+1
def nested(self, arg):
def method_b2(self, arg):
return arg+1
some_data = method_b2(self, arg)
obj = Test()
"""
from timeit import Timer
print(min(Timer(stmt='obj.separate(42)', setup=setup).repeat())) # -> 0.24479823284461724
print(min(Timer(stmt='obj.nested(42)', setup=setup).repeat())) # -> 0.26553459700452575
Note I added some self
arguments to your sample functions to make them more like real methods (although method_b2
still isn't technically a method of the Test
class). Also the nested function is actually called in that version, unlike yours.
I didn't understand your problem clearly but I think this is what you're looking for(Based on my understanding)
person = {"name"=>"BillGates", "company_name"=>"Microsoft", "position"=>"Chairman"}
person.delete_if {|key, value| key == "name"} #doing something if the key == "something"
Output: {"company_name"=>"Microsoft", "position"=>"Chairman"}
It depends what you wanted to do with that column e.g. here's an example of appending a new column to a recordset which can be updated on the client side:
Sub MSDataShape_AddNewCol()
Dim rs As ADODB.Recordset
Set rs = CreateObject("ADODB.Recordset")
With rs
.ActiveConnection = _
"Provider=MSDataShape;" & _
"Data Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Tempo\New_Jet_DB.mdb"
.Source = _
"SHAPE {" & _
" SELECT ExistingField" & _
" FROM ExistingTable" & _
" ORDER BY ExistingField" & _
"} APPEND NEW adNumeric(5, 4) AS NewField"
.LockType = adLockBatchOptimistic
.Open
Dim i As Long
For i = 0 To .RecordCount - 1
.Fields("NewField").Value = Round(.Fields("ExistingField").Value, 4)
.MoveNext
Next
rs.Save "C:\rs.xml", adPersistXML
End With
End Sub
Your fns is a cellstr array. You need to index in to it with {} instead of () to get the single string out as char.
fns{i}
teststruct.(fns{i})
Indexing in to it with () returns a 1-long cellstr array, which isn't the same format as the char array that the ".(name)" dynamic field reference wants. The formatting, especially in the display output, can be confusing. To see the difference, try this.
name_as_char = 'a'
name_as_cellstr = {'a'}
javascript:document.getElementsByClassName("video-stream html5-main-video")[0].playbackRate = 0.1;
you can put any number here just don't go to far so you don't overun your computer.
I can see that the Debugger is retrieving 4 og:image
tags from your URL.
The first image is the largest and therefore takes longest to load. Try shrink that first image down or change the order to show a smaller image first.
I just create a "help" version of the function. Shows up right below the function in autocomplete - the user can select it instead in an adjacent cell for instructions.
Public Function Foo(param1 as range, param2 as string) As String
Foo = "Hello world"
End Function
Public Function Foo_Help() as String
Foo_Help = "The Foo function was designed to return the Foo value for a specified range a cells given a specified constant." & CHR(10) & "Parameters:" & CHR(10)
& " param1 as Range : Specifies the range of cells the Foo function should operate on." & CHR(10)
&" param2 as String : Specifies the constant the function should use to calculate Foo"
&" contact the Foo master at [email protected] for more information."
END FUNCTION
The carriage returns improve readability with wordwrap on. 2 birds with one stone, now the function has some documentation.
Using data-parent
, first solution is to stick to the example selector architecture
<div id="myGroup">
<button class="btn dropdown" data-toggle="collapse" data-target="#keys" data-parent="#myGroup"><i class="icon-chevron-right"></i> Keys <span class="badge badge-info pull-right">X</span></button>
<button class="btn dropdown" data-toggle="collapse" data-target="#attrs" data-parent="#myGroup"><i class="icon-chevron-right"></i> Attributes</button>
<button class="btn dropdown" data-toggle="collapse" data-target="#edit" data-parent="#myGroup"><i class="icon-chevron-right"></i> Edit Details</button>
<div class="accordion-group">
<div class="collapse indent" id="keys">
keys
</div>
<div class="collapse indent" id="attrs">
attrs
</div>
<div class="collapse" id="edit">
edit
</div>
</div>
</div>
Second solution is to bind on the events and hide the other collapsible elements yourself.
var $myGroup = $('#myGroup');
$myGroup.on('show.bs.collapse','.collapse', function() {
$myGroup.find('.collapse.in').collapse('hide');
});
PS: the strange effect in the demos is caused by the min-height
set for the example, just ignore that.
Edit: changed the JS event from show
to show.bs.collapse
as specified in Bootstrap documentation.
I found a way to display the Document Location module
in Office 2010.
File -> Options -> Quick Access Toolbar
From the
Choose commands
list
select All Commands
find "Document Location"
press the "Add>>"
button.
press OK
.
Viola, the file path is at the top of your 2010 office document.
use the dbms_metadata package, as described here
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
In Windows, if you have mapped network drives and you don't know the UNC path for them, you can start a command prompt (Start ? Run ? cmd.exe) and use the net use
command to list your mapped drives and their UNC paths:
C:\>net use
New connections will be remembered.
Status Local Remote Network
-------------------------------------------------------------------------------
OK Q: \\server1\foo Microsoft Windows Network
OK X: \\server2\bar Microsoft Windows Network
The command completed successfully.
Note that this shows the list of mapped and connected network file shares for the user context the command is run under. If you run cmd.exe
under your own user account, the results shown are the network file shares for yourself. If you run cmd.exe
under another user account, such as the local Administrator, you will instead see the network file shares for that user.
If you have some panels or groupboxes reset fields should be recursive.
public class Utilities
{
public static void ResetAllControls(Control form)
{
foreach (Control control in form.Controls)
{
RecursiveResetForm(control);
}
}
private void RecursiveResetForm(Control control)
{
if (control.HasChildren)
{
foreach (Control subControl in control.Controls)
{
RecursiveResetForm(subControl);
}
}
switch (control.GetType().Name)
{
case "TextBox":
TextBox textBox = (TextBox)control;
textBox.Text = null;
break;
case "ComboBox":
ComboBox comboBox = (ComboBox)control;
if (comboBox.Items.Count > 0)
comboBox.SelectedIndex = 0;
break;
case "CheckBox":
CheckBox checkBox = (CheckBox)control;
checkBox.Checked = false;
break;
case "ListBox":
ListBox listBox = (ListBox)control;
listBox.ClearSelected();
break;
case "NumericUpDown":
NumericUpDown numericUpDown = (NumericUpDown)control;
numericUpDown.Value = 0;
break;
}
}
}
There is a switch
statement but I can never seem to get it to work the way I think it should. Since you have not provided an example I will make one using a factor variable:
dft <-data.frame(x = sample(letters[1:8], 20, replace=TRUE))
levels(dft$x)
[1] "a" "b" "c" "d" "e" "f" "g" "h"
If you specify the categories you want in an order appropriate to the reassignment you can use the factor or numeric variables as an index:
c("abc", "abc", "abc", "def", "def", "def", "g", "h")[dft$x]
[1] "def" "h" "g" "def" "def" "abc" "h" "h" "def" "abc" "abc" "abc" "h" "h" "abc"
[16] "def" "abc" "abc" "def" "def"
dft$y <- c("abc", "abc", "abc", "def", "def", "def", "g", "h")[dft$x] str(dft)
'data.frame': 20 obs. of 2 variables:
$ x: Factor w/ 8 levels "a","b","c","d",..: 4 8 7 4 6 1 8 8 5 2 ...
$ y: chr "def" "h" "g" "def" ...
I later learned that there really are two different switch functions. It's not generic function but you should think about it as either switch.numeric
or switch.character
. If your first argument is an R 'factor', you get switch.numeric
behavior, which is likely to cause problems, since most people see factors displayed as character and make the incorrect assumption that all functions will process them as such.
also you should click right button on mouse at your projectname and choose "open module settings" or press F4 button. Then on "dependencies" tab add your lib.jar to declare needed lib
You can skip the container or background image with pure css arrow:
select {
/* make arrow and background */
background:
linear-gradient(45deg, transparent 50%, blue 50%),
linear-gradient(135deg, blue 50%, transparent 50%),
linear-gradient(to right, skyblue, skyblue);
background-position:
calc(100% - 21px) calc(1em + 2px),
calc(100% - 16px) calc(1em + 2px),
100% 0;
background-size:
5px 5px,
5px 5px,
2.5em 2.5em;
background-repeat: no-repeat;
/* styling and reset */
border: thin solid blue;
font: 300 1em/100% "Helvetica Neue", Arial, sans-serif;
line-height: 1.5em;
padding: 0.5em 3.5em 0.5em 1em;
/* reset */
border-radius: 0;
margin: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-appearance:none;
-moz-appearance:none;
}
Sample here
/// <summary>
/// https://stackoverflow.com/a/45620698/2390270
/// Compare a source and target datatables and return the row that are the same, different, added, and removed
/// </summary>
/// <param name="dtOld">DataTable to compare</param>
/// <param name="dtNew">DataTable to compare to dtOld</param>
/// <param name="dtSame">DataTable that would give you the common rows in both</param>
/// <param name="dtDifferences">DataTable that would give you the difference</param>
/// <param name="dtAdded">DataTable that would give you the rows added going from dtOld to dtNew</param>
/// <param name="dtRemoved">DataTable that would give you the rows removed going from dtOld to dtNew</param>
public static void GetTableDiff(DataTable dtOld, DataTable dtNew, ref DataTable dtSame, ref DataTable dtDifferences, ref DataTable dtAdded, ref DataTable dtRemoved)
{
try
{
dtAdded = dtOld.Clone();
dtAdded.Clear();
dtRemoved = dtOld.Clone();
dtRemoved.Clear();
dtSame = dtOld.Clone();
dtSame.Clear();
if (dtNew.Rows.Count > 0) dtDifferences.Merge(dtNew.AsEnumerable().Except(dtOld.AsEnumerable(), DataRowComparer.Default).CopyToDataTable<DataRow>());
if (dtOld.Rows.Count > 0) dtDifferences.Merge(dtOld.AsEnumerable().Except(dtNew.AsEnumerable(), DataRowComparer.Default).CopyToDataTable<DataRow>());
if (dtOld.Rows.Count > 0 && dtNew.Rows.Count > 0) dtSame = dtOld.AsEnumerable().Intersect(dtNew.AsEnumerable(), DataRowComparer.Default).CopyToDataTable<DataRow>();
foreach (DataRow row in dtDifferences.Rows)
{
if (dtOld.AsEnumerable().Any(r => Enumerable.SequenceEqual(r.ItemArray, row.ItemArray))
&& !dtNew.AsEnumerable().Any(r => Enumerable.SequenceEqual(r.ItemArray, row.ItemArray)))
{
dtRemoved.Rows.Add(row.ItemArray);
}
else if (dtNew.AsEnumerable().Any(r => Enumerable.SequenceEqual(r.ItemArray, row.ItemArray))
&& !dtOld.AsEnumerable().Any(r => Enumerable.SequenceEqual(r.ItemArray, row.ItemArray)))
{
dtAdded.Rows.Add(row.ItemArray);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
On macOS you can add it to your ~/.bash_profile
as
alias atom='open -a "Atom"'
and from terminal just call
atom filename.whatever
It is basically a header file that also includes every standard library and STL include file. The only purpose I can see for it would be for testing and education.
Se e.g. GCC 4.8.0 /bits/stdc++.h source.
Using it would include a lot of unnecessary stuff and increases compilation time.
Edit: As Neil says, it's an implementation for precompiled headers. If you set it up for precompilation correctly it could, in fact, speed up compilation time depending on your project. (https://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html)
I would, however, suggest that you take time to learn about each of the sl/stl headers and include them separately instead, and not use "super headers" except for precompilation purposes.
LinearLayout YOUR_LinearLayout =(LinearLayout)findViewById(R.id.YOUR_LinearLayout)
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
/*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
/*height*/ 100,
/*weight*/ 1.0f
);
YOUR_LinearLayout.setLayoutParams(param);
You should include <string.h>
(or its C++ equivalent, <cstring>
).
Granted, OP stated very similarly that this didn't work, but it did for me. Based on the notes in my source, it seems it was implemented around the time, or after, OP's post. Perhaps it's more standard now.
document.getElementsByName('MyElementsName')[0].click();
In my case, my button didn't have an ID. If your element has an id, preferably use the following (untested).
document.getElementById('MyElementsId').click();
I originally tried this method and it didn't work. After Googling I came back and realized my element was by name, and didn't have an ID. Double check you're calling the right attribute.
Source: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAnyOrigin",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.Configure<MvcOptions>(options => {
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAnyOrigin"));
});
}
conda init
As pointed out in a different answer, manually adding Conda on $PATH
is no longer recommended as of v4.4.0 (see Release Notes). Furthermore, since Conda v4.6 new functionality to manage shell initialization via the conda init
command was introduced. Hence, the updated recommendation is to run
Linux/UNIX (OS X < 10.15)
./anaconda3/bin/conda init
Mac OS X >= 10.15
./anaconda3/bin/conda init zsh
Windows
./anaconda3/Scripts/conda.exe init
You must launch a new shell or source your init file (e.g., source .bashrc
) for the changes to take effect.
You may need to explicitly identify your shell to Conda. For example, if you run zsh
(Mac OS X 10.15+ default) instead of bash
then you would run
./anaconda3/bin/conda init zsh
Please see ./anaconda3/bin/conda init --help
for a comprehensive list of supported shells.
I'd recommend running the above command with a --dry-run|-d
flag and a verbosity (-vv
) flag, in order to see exactly what it would do. If you don't already have a Conda-managed section in your shell run commands file (e.g., .bashrc
), then this should appear like a straight-forward insertion of some new lines. If it isn't such a straightforward insertion, I'd recommend clearing any previous Conda sections from $PATH
and the relevant shell initialization files (e.g., bashrc
) first.
Conda v4.6.9 introduced a --reverse
flag that automates removing the changes that are inserted by conda init
.
I figured to set HTTP response header and stream to display download-popup in browser via standard servlet. note: I'm using Excella, excel output API.
package local.test.servlet;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.test.jaxrs.ExcellaTestResource;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.BookData;
import org.bbreak.excella.core.exception.ExportException;
import org.bbreak.excella.reports.exporter.ExcelExporter;
import org.bbreak.excella.reports.exporter.ReportBookExporter;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.ReportProcessor;
@WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"})
public class ExcelServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls");
// /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls
System.out.println(templateFileUrl.getPath());
String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8");
String outputFileDir = "MasatoExcelHorizontalOutput";
ReportProcessor reportProcessor = new ReportProcessor();
ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE);
ReportSheet outputSheet = new ReportSheet("MySheet");
outputBook.addReportSheet(outputSheet);
reportProcessor.addReportBookExporter(new OutputStreamExporter(response));
System.out.println("wtf???");
reportProcessor.process(outputBook);
System.out.println("done!!");
}
catch(Exception e) {
System.out.println(e);
}
} //end doGet()
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}//end class
class OutputStreamExporter extends ReportBookExporter {
private HttpServletResponse response;
public OutputStreamExporter(HttpServletResponse response) {
this.response = response;
}
@Override
public String getExtention() {
return null;
}
@Override
public String getFormatType() {
return ExcelExporter.FORMAT_TYPE;
}
@Override
public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException {
System.out.println(book.getFirstVisibleTab());
System.out.println(book.getSheetName(0));
//TODO write to stream
try {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls");
book.write(response.getOutputStream());
response.getOutputStream().close();
System.out.println("booya!!");
}
catch(Exception e) {
System.out.println(e);
}
}
}//end class
For newbie Powershell users it is important to know that '.' is a syntactic element of Powershell, so the switch has to be enclosed in double quotes:
mvn clean install "-Dmaven.javadoc.skip=true"
You want the (standard) POSIXt
type from base R that can be had in 'compact form' as a POSIXct
(which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt
(which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)
Quick example:
R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10 # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79
$min
[1] 39
$hour
[1] 18
$mday
[1] 25
$mon
[1] 11
$year
[1] 109
$wday
[1] 5
$yday
[1] 358
$isdst
[1] 0
attr(,"tzone")
[1] "America/Chicago" "CST" "CDT"
R>
As for reading them in, see help(strptime)
As for difference, easy too:
R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R>
Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.
Another aproach is:
let result = { ...item, location : { ...response } }
But Object spread isn't yet standardized.
May also be helpful: https://stackoverflow.com/a/32926019/5341953
=========================
Here's an article with your full list of options: https://tobiasahlin.com/blog/flexbox-break-to-new-row/
EDIT: This is really easy to do with Grid now: https://codepen.io/anon/pen/mGONxv?editors=1100
=========================
I don't think you can break after a specific item. The best you can probably do is change the flex-basis at your breakpoints. So:
ul {
flex-flow: row wrap;
display: flex;
}
li {
flex-grow: 1;
flex-shrink: 0;
flex-basis: 50%;
}
@media (min-width: 40em;){
li {
flex-basis: 30%;
}
Here's a sample: http://cdpn.io/ndCzD
============================================
EDIT: You CAN break after a specific element! Heydon Pickering unleashed some css wizardry in an A List Apart article: http://alistapart.com/article/quantity-queries-for-css
EDIT 2: Please have a look at this answer: Line break in multi-line flexbox
@luksak also provides a great answer
This blog post describes two methods of centering a div both horizontally and vertically. One uses only CSS and will work with divs that have a fixed size; the other uses jQuery and will work divs for which you do not know the size in advance.
I've duplicated the CSS and jQuery examples from the blog post's demo here:
CSS
Assuming you have a div with a class of .classname, the css below should work.
The left:50%; top:50%;
sets the top left corner of the div to the center of the screen; the margin:-75px 0 0 -135px;
moves it to the left and up by half of the width and height of the fixed-size div respectively.
.className{
width:270px;
height:150px;
position:absolute;
left:50%;
top:50%;
margin:-75px 0 0 -135px;
}
jQuery
$(document).ready(function(){
$(window).resize(function(){
$('.className').css({
position:'absolute',
left: ($(window).width() - $('.className').outerWidth())/2,
top: ($(window).height() - $('.className').outerHeight())/2
});
});
// To initially run the function:
$(window).resize();
});
Here's a demo of the techniques in practice.
I ran into this same issue, but I think I know what's causing the confusion. If you use MySql Query Analyzer, you can do this just fine:
SELECT myvalue
INTO @myvar
FROM mytable
WHERE anothervalue = 1;
However, if you put that same query in MySql Workbench, it will throw a syntax error. I don't know why they would be different, but they are. To work around the problem in MySql Workbench, you can rewrite the query like this:
SELECT @myvar:=myvalue
FROM mytable
WHERE anothervalue = 1;
Be aware that the line-height
approach fails if you have a long sentence in the span
which breaks the line because there's not enough space. In this case, you would have two lines with a gap with the height of the N pixels specified in the property.
I stuck into it when I wanted to show an image with vertically centered text on its right side which works in a responsive web application. As a base I use the approach suggested by Eric Nickus and Felipe Tadeo.
If you want to achieve:
and this:
.container {_x000D_
background: url( "https://i.imgur.com/tAlPtC4.jpg" ) no-repeat;_x000D_
display: inline-block;_x000D_
background-size: 40px 40px; /* image's size */_x000D_
height: 40px; /* image's height */_x000D_
padding-left: 50px; /* image's width plus 10 px (margin between text and image) */_x000D_
}_x000D_
_x000D_
.container span {_x000D_
height: 40px; /* image's height */_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<span class="container">_x000D_
<span>This is a centered sentence next to an image</span>_x000D_
</span>
_x000D_
Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file
<style type="text/css">
<%@include file="css/style.css" %>
</style>
<script type="text/javascript">
<%@include file="js/script.js" %>
</script>
To really get this clear, here's my for-beginners answer:
You inputed the arguments in the wrong order.
A keyword argument has this style:
nullable=True, unique=False
A fixed parameter should be defined: True, False, etc. A non-keyword argument is different:
name="Ricardo", fruit="chontaduro"
This syntax error asks you to first put name="Ricardo"
and all of its kind (non-keyword) before those like nullable=True.
In Python, to represent the absence of a value, you can use the None value (types.NoneType.None) for objects and "" (or len() == 0) for strings. Therefore:
if yourObject is None: # if yourObject == None:
...
if yourString == "": # if yourString.len() == 0:
...
Regarding the difference between "==" and "is", testing for object identity using "==" should be sufficient. However, since the operation "is" is defined as the object identity operation, it is probably more correct to use it, rather than "==". Not sure if there is even a speed difference.
Anyway, you can have a look at:
In addition set the proxy for the command line session Open a command line where you might want to run your script
netsh winhttp set proxy YourProxySERVER:yourProxyPORT
run your script in that terminal.
The code below creates a set from an array and then, using the ...
operator.
var arr=[1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,];
var set=new Set(arr);
let setarr=[...set];
console.log(setarr);
I joined all qualitative palettes from RColorBrewer
package. Qualitative palettes are supposed to provide X most distinctive colours each. Of course, mixing them joins into one palette also similar colours, but that's the best I can get (74 colors).
library(RColorBrewer)
n <- 60
qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',]
col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))
pie(rep(1,n), col=sample(col_vector, n))
Other solution is: take all R colors from graphical devices and sample from them. I removed shades of grey as they are too similar. This gives 433 colors
color = grDevices::colors()[grep('gr(a|e)y', grDevices::colors(), invert = T)]
pie(rep(1,n), col=sample(color, n))
with 200 colors n = 200
:
pie(rep(1,n), col=sample(color, n))
Setting \itemindent
for a new itemize environment solves the problem:
\newenvironment{beameritemize}
{ \begin{itemize}
\setlength{\itemsep}{1.5ex}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt}
\addtolength{\itemindent}{-2em} }
{ \end{itemize} }
C:\Program Files (x86)\LG Electronics\LG PC Suite\adb>adb install com.lge.filemanager-15052-v3.1.15052.apk
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
2683 KB/s (3159508 bytes in 1.150s)
pkg: /data/local/tmp/com.lge.filemanager-15052-v3.1.15052.apk
Success
C:\Program Files (x86)\LG Electronics\LG PC Suite\adb>
We can use the adb.exe which is there in PC suit, it worked for me. Thanks Chethan
debugger
is a reserved keyword by EcmaScript and given optional semantics since ES5
As a result, it can be used not only in Chrome, but also Firefox and Node.js via node debug myscript.js
.
The standard says:
Syntax
DebuggerStatement : debugger ;
Semantics
Evaluating the DebuggerStatement production may allow an implementation to cause a breakpoint when run under a debugger. If a debugger is not present or active this statement has no observable effect.
The production DebuggerStatement : debugger ; is evaluated as follows:
- If an implementation defined debugging facility is available and enabled, then
- Perform an implementation defined debugging action.
- Let result be an implementation defined Completion value.
- Else
- Let result be (normal, empty, empty).
- Return result.
No changes in ES6.
// Make option have a "selected" attribute using jQuery
var yourValue = "Gateway 2";
$("#gate").find('option').each(function( i, opt ) {
if( opt.value === yourValue )
$(opt).attr('selected', 'selected');
});
function groupeByPHP($array,$indexUnique,$assoGroup,$keepInOne){
$retour = array();
$id = $array[0][$indexUnique];
foreach ($keepInOne as $keep){
$retour[$id][$keep] = $array[0][$keep];
}
foreach ($assoGroup as $cle=>$arrayKey){
$arrayGrouped = array();
foreach ($array as $data){
if($data[$indexUnique] != $id){
$id = $data[$indexUnique];
foreach ($keepInOne as $keep){
$retour[$id][$keep] = $data[$keep];
}
}
foreach ($arrayKey as $val){
$arrayGrouped[$val] = $data[$val];
}
$retour[$id][$cle][] = $arrayGrouped;
$retour[$id][$cle] = array_unique($retour[$id][$cle],SORT_REGULAR);
}
}
return $retour;
}
Try this function
groupeByPHP($yourArray,'id',array('desc'=>array('part_no','packaging_type')),array('id','shipping_no'))
A callable piece of code (routine) can be a Sub (called for a side effect/what it does) or a Function (called for its return value) or a mixture of both. As the docs for MsgBox
Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.
MsgBox(prompt[, buttons][, title][, helpfile, context])
indicate, this routine is of the third kind.
The syntactical rules of VBScript are simple:
Use parameter list () when calling a (routine as a) Function
If you want to display a message to the user and need to know the user's reponse:
Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
' MyVar contains either 1 or 2, depending on which button is clicked.
Don't use parameter list () when calling a (routine as a) Sub
If you want to display a message to the user and are not interested in the response:
MsgBox "Hello World!", 65, "MsgBox Example"
This beautiful simplicity is messed up by:
The design flaw of using () for parameter lists and to force call-by-value semantics
>> Sub S(n) : n = n + 1 : End Sub
>> n = 1
>> S n
>> WScript.Echo n
>> S (n)
>> WScript.Echo n
>>
2
2
S (n) does not mean "call S with n", but "call S with a copy of n's value". Programmers seeing that
>> s = "value"
>> MsgBox(s)
'works' are in for a suprise when they try:
>> MsgBox(s, 65, "MsgBox Example")
>>
Error Number: 1044
Error Description: Cannot use parentheses when calling a Sub
The compiler's leniency with regard to empty () in a Sub call. The 'pure' Sub Randomize (called for the side effect of setting the random seed) can be called by
Randomize()
although the () can neither mean "give me your return value) nor "pass something by value". A bit more strictness here would force prgrammers to be aware of the difference in
Randomize n
and
Randomize (n)
The Call statement that allows parameter list () in Sub calls:
s = "value" Call MsgBox(s, 65, "MsgBox Example")
which further encourage programmers to use () without thinking.
(Based on What do you mean "cannot use parentheses?")
If it is related to the SSIS Package check may be possible that your source db contains few null rows. After removing them this issue will not appear any more.
.e:hover{
background-color:#FF0000;
}
If you only have one camera, or you don't care which camera is the correct one, then use "-1" as the index. Ie for your example capture = cv.CaptureFromCAM(-1)
.
IE works with iframe like all the other browsers (at least for main functions). You just have to keep a set of rules:
when all iframe resources are loaded, change document.domain to be the same as the one defined in parent. (You need to do this later because setting domain will cause the iframe resource's request to fail)
now you can make a reference for parent window: var winn = window.parent
If you mean by literally putting one on the top of the other, one on the top (Same X, Y positions, but different Z position), try using the z-index
CSS attribute. This should work (untested)
<div>
<div style='z-index: 1'>1</div>
<div style='z-index: 2'>2</div>
<div style='z-index: 3'>3</div>
<div style='z-index: 4'>4</div>
</div>
This should show 4 on the top of 3, 3 on the top of 2, and so on. The higher the z-index is, the higher the element is positioned on the z-axis. I hope this helped you :)
And, of course
("ABCD"[2] == 2["ABCD"]) && (2["ABCD"] == 'C') && ("ABCD"[2] == 'C')
The main reason for this was that back in the 70's when C was designed, computers didn't have much memory (64KB was a lot), so the C compiler didn't do much syntax checking. Hence "X[Y]
" was rather blindly translated into "*(X+Y)
"
This also explains the "+=
" and "++
" syntaxes. Everything in the form "A = B + C
" had the same compiled form. But, if B was the same object as A, then an assembly level optimization was available. But the compiler wasn't bright enough to recognize it, so the developer had to (A += C
). Similarly, if C
was 1
, a different assembly level optimization was available, and again the developer had to make it explicit, because the compiler didn't recognize it. (More recently compilers do, so those syntaxes are largely unnecessary these days)
If this is output from a Dockerfile then you don't want / need to commit it.
However you will want to tag the base image and any other contributing images / applications.
E.g.
FROM node:12.18.1
To add to Rob's answer, since iOS 10.0, Apple has introduced an entirely new "Unified Logging" system that supersedes existing logging systems (including ASL and Syslog, NSLog), and also surpasses existing logging approaches in performance, thanks to its new techniques including log data compression and deferred data collection.
From Apple:
The unified logging system provides a single, efficient, performant API for capturing messaging across all levels of the system. This unified system centralizes the storage of log data in memory and in a data store on disk.
Apple highly recommends using os_log
going forward to log all kinds of messages, including info, debug, error messages because of its much improved performance compared to previous logging systems, and its centralized data collection allowing convenient log and activity inspection for developers. In fact, the new system is likely so low-footprint that it won't cause the "observer effect" where your bug disappears if you insert a logging command, interfering the timing of the bug to happen.
You can learn more about this in details here.
To sum it up: use print()
for your personal debugging for convenience (but the message won't be logged when deployed on user devices). Then, use Unified Logging (os_log
) as much as possible for everything else.
With pure JavaScript:
console.log(window.location.href)
Using Angular:
this.router.url
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
template: 'The href is: {{href}}'
/*
Other component settings
*/
})
export class Component {
public href: string = "";
constructor(private router: Router) {}
ngOnInit() {
this.href = this.router.url;
console.log(this.router.url);
}
}
The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview
The line
Object EchoServer0;
says that you are allocating an Object
named EchoServer0
. This has nothing to do with the class EchoServer0
. Furthermore, the object is not initialized, so EchoServer0
is null
. Classes and identifiers have separate namespaces. This will actually compile:
String String = "abc"; // My use of String String was deliberate.
Please keep to the Java naming standards: classes begin with a capital letter, identifiers begin with a small letter, constants and enum
s are all-capitals.
public final String ME = "Eric Jablow";
public final double GAMMA = 0.5772;
public enum Color { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET}
public COLOR background = Color.RED;
You shoud follow the Angular docs and use $sce - $sce is a service that provides Strict Contextual Escaping services to AngularJS. Here is a docs: http://docs-angularjs-org-dev.appspot.com/api/ng.directive:ngBindHtmlUnsafe
Let's take an example with asynchroniously loading Eventbrite login button
In your controller:
someAppControllers.controller('SomeCtrl', ['$scope', '$sce', 'eventbriteLogin',
function($scope, $sce, eventbriteLogin) {
eventbriteLogin.fetchButton(function(data){
$scope.buttonLogin = $sce.trustAsHtml(data);
});
}]);
In your view just add:
<span ng-bind-html="buttonLogin"></span>
In your services:
someAppServices.factory('eventbriteLogin', function($resource){
return {
fetchButton: function(callback){
Eventbrite.prototype.widget.login({'app_key': 'YOUR_API_KEY'}, function(widget_html){
callback(widget_html);
})
}
}
});
I like the ndiff answer, but if you want to spit it all into a list of only the changes, you could do something like:
import difflib
case_a = 'afrykbnerskojezyczny'
case_b = 'afrykanerskojezycznym'
output_list = [li for li in difflib.ndiff(case_a, case_b) if li[0] != ' ']
from dateutil import relativedelta
relativedelta.relativedelta(date1, date2)
months_difference = (r.years * 12) + r.months
You can create the single value array key-value as
$new_row = array($row["datasource_id"]=>$row["title"]);
inside while loop, and then use array_merge
function in loop to combine the each new $new_row
array.
One way to do it is to use flexbox in order to align the text on the middle. The way I found to do it, is the following:
HTML:
<div class="circle-without-text">
<div class="text-inside-circle">
The text
</div>
</div>
CSS:
.circle-without-text {
border-radius: 50%;
width: 70vh;
height: 70vh;
background-color: red;
position: relative;
}
.text-inside-circle {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
Here the plnkr: https://plnkr.co/edit/EvWYLNfTb1B7igoc3TZx?p=preview
Okay, how about a CSS answer! We use display: table
. Then each of the divs are rows, and finally we apply height of 100% to middle 'row' and voilà.
body { display: table; }
div { display: table-row; }
#content {
width:450px;
margin:0 auto;
text-align: center;
background-color: blue;
color: white;
height: 100%;
}
In my case, I noticed mergedmanifest was missing the receiver. So I had to include:
<receiver
android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</receiver>
You need to add a extra parameter with http_errors => false
$request = $client->get($url, ['http_errors' => false]);
From (my entry) in the FAQ, which I certainly do not guarantee to be complete (I added two entries just two days ago):
import scala._ // Wild card -- all of Scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]] // Higher kinded type parameter
def f(m: M[_]) // Existential type
_ + _ // Anonymous function placeholder parameter
m _ // Eta expansion of method into method value
m(_) // Partial function application
_ => 5 // Discarded parameter
case _ => // Wild card pattern -- matches anything
val (a, _) = (1, 2) // same thing
for (_ <- 1 to 10) // same thing
f(xs: _*) // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
var i: Int = _ // Initialization to the default value
def abc_<>! // An underscore must separate alphanumerics from symbols on identifiers
t._2 // Part of a method name, such as tuple getters
1_000_000 // Numeric literal separator (Scala 2.13+)
This is also part of this question.
You can write:
"line 1" +
"line 2" +
"line 3"
which is the same as:
"line 1line 2line 3"
Unlike using back ticks, it will preserve escape characters. Note that the "+" must be on the 'leading' line - for instance, the following will generate an error:
"line 1"
+"line 2"
The simplest way to initialize an array
Create array
$array = @()
Create your header
$line = "" | select name,age,phone
Fill the line
$line.name = "Leandro"
$line.age = "39"
$line.phone = "555-555555"
Add line to $array
$array += $line
Result
$array
name age phone
---- --- -----
Leandro 39 555-555555
What's the column "BIO" datatype? What database server (sql/oracle/mysql)? You should be able to span over multiple lines all you want as long as you adhere to the character limit in the column's datatype (ie: varchar(200) ). Try using single quotes, that might make a difference. This works for me:
update table set mycolumn = 'hello world,
my name is carlos.
goodbye.'
where id = 1;
Also, you might want to put in checks for single quotes if you are concatinating the sql string together in C#. If the variable contains single quotes that could escape the code out of the sql statement, therefore, not doing all the lines you were expecting to see.
BTW, you can delimit your SQL statements with a semi colon like you do in C#, just as FYI.
Try this its worked for me
SELECT * from bookedroom
WHERE UNIX_TIMESTAMP('2020-8-07 5:31')
between UNIX_TIMESTAMP('2020-8-07 5:30') and
UNIX_TIMESTAMP('2020-8-09 5:30')
I got the same problem with my customized theme that used Holo.Light as its parent. In grayed text Android Studio indicated that some attributes were missing. When I added these missing attributes as follows, the rendering problems went away -
<item name="android:textEditSuggestionItemLayout"></item>
<item name="android:textEditSuggestionContainerLayout"></item>
<item name="android:textEditSuggestionHighlightStyle"></item>
Even though they introduced errors in my style's theme, they caused no problems in rendering the activity designs or building my app.
This is useful when you have more than one class to append. You can join all classes in array with a space.
const visibility = this.props.showBulkActions ? "show" : ""
<div className={["btn-group pull-right", visibility].join(' ')}>
Here's a script that will use the Google API to acquire the users postal code and populate an input field.
function postalCodeLookup(input) {
var head= document.getElementsByTagName('head')[0],
script= document.createElement('script');
script.src= '//maps.googleapis.com/maps/api/js?sensor=false';
head.appendChild(script);
script.onload = function() {
if (navigator.geolocation) {
var a = input,
fallback = setTimeout(function () {
fail('10 seconds expired');
}, 10000);
navigator.geolocation.getCurrentPosition(function (pos) {
clearTimeout(fallback);
var point = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
new google.maps.Geocoder().geocode({'latLng': point}, function (res, status) {
if (status == google.maps.GeocoderStatus.OK && typeof res[0] !== 'undefined') {
var zip = res[0].formatted_address.match(/,\s\w{2}\s(\d{5})/);
if (zip) {
a.value = zip[1];
} else fail('Unable to look-up postal code');
} else {
fail('Unable to look-up geolocation');
}
});
}, function (err) {
fail(err.message);
});
} else {
alert('Unable to find your location.');
}
function fail(err) {
console.log('err', err);
a.value('Try Again.');
}
};
}
You can adjust accordingly to acquire different information. For more info, check out the Google Maps API documentation.
try
block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
You can manually place a check in your code. Like this -
if result != []:
for face in result:
bounding_box = face['box']
x, y, w, h = bounding_box[0], bounding_box[1], bounding_box[2], bounding_box[3]
rect_face = cv2.rectangle(frame, (x, y), (x+w, y+h), (46, 204, 113), 2)
face = rgb[y:y+h, x:x+w]
#CHECK FACE SIZE (EXIST OR NOT)
if face.shape[0]*face.shape[1] > 0:
predicted_name, class_probability = face_recognition(face)
print("Result: ", predicted_name, class_probability)
`
This could be useful
class func createAttributedStringFrom (string1 : String ,strin2 : String, attributes1 : Dictionary<String, NSObject>, attributes2 : Dictionary<String, NSObject>) -> NSAttributedString{
let fullStringNormal = (string1 + strin2) as NSString
let attributedFullString = NSMutableAttributedString(string: fullStringNormal as String)
attributedFullString.addAttributes(attributes1, range: fullStringNormal.rangeOfString(string1))
attributedFullString.addAttributes(attributes2, range: fullStringNormal.rangeOfString(strin2))
return attributedFullString
}
Time::HiRes:
use Time::HiRes;
Time::HiRes::sleep(0.1); #.1 seconds
Time::HiRes::usleep(1); # 1 microsecond.
$("#e2").select2({
placeholder: "Select a State",
allowClear: true
});
$("#e2_2").select2({
placeholder: "Select a State"
});
The placeholder can be declared via a data-placeholder attribute attached to the select, or via the placeholder configuration element as seen in the example code.
When placeholder is used for a non-multi-value select box, it requires that you include an empty tag as your first option.
Optionally, a clear button (visible once a selection is made) is available to reset the select box back to the placeholder value.
JSTransform is deprecated , please use babel instead.
<script type="text/babel" src="./lander.js"></script>
If we're willing to sacrifice the succinctness of Hayden's solution, one could also do something like this:
In [22]: orders_df['C'] = orders_df.Action.apply(
lambda x: (1 if x == 'Sell' else -1))
In [23]: orders_df # New column C represents the sign of the transaction
Out[23]:
Prices Amount Action C
0 3 57 Sell 1
1 89 42 Sell 1
2 45 70 Buy -1
3 6 43 Sell 1
4 60 47 Sell 1
5 19 16 Buy -1
6 56 89 Sell 1
7 3 28 Buy -1
8 56 69 Sell 1
9 90 49 Buy -1
Now we have eliminated the need for the if
statement. Using DataFrame.apply()
, we also do away with the for
loop. As Hayden noted, vectorized operations are always faster.
In [24]: orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.C
In [25]: orders_df # The resulting dataframe
Out[25]:
Prices Amount Action C Value
0 3 57 Sell 1 171
1 89 42 Sell 1 3738
2 45 70 Buy -1 -3150
3 6 43 Sell 1 258
4 60 47 Sell 1 2820
5 19 16 Buy -1 -304
6 56 89 Sell 1 4984
7 3 28 Buy -1 -84
8 56 69 Sell 1 3864
9 90 49 Buy -1 -4410
This solution takes two lines of code instead of one, but is a bit easier to read. I suspect that the computational costs are similar as well.
https://stackoverflow.com/a/30640097/2569475
For This Issue check My answer at above given url
Using a request scoped bean outside of an actual web request
If you need stricter replacement matching, PostgreSQL's regexp_replace
function can match using POSIX regular expression patterns. It has the syntax regexp_replace(source, pattern, replacement [, flags ]).
I will use flags i
and g
for case-insensitive and global matching, respectively. I will also use \m
and \M
to match the beginning and the end of a word, respectively.
There are usually quite a few gotchas when performing regex replacment. Let's see how easy it is to replace a cat with a dog.
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog');
--> Cat bobdog cat cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'i');
--> dog bobcat cat cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'g');
--> Cat bobdog dog dogs dogfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'gi');
--> dog bobdog dog dogs dogfish
SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat', 'dog', 'gi');
--> dog bobcat dog dogs dogfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat\M', 'dog', 'gi');
--> dog bobdog dog cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat\M', 'dog', 'gi');
--> dog bobcat dog cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat(s?)\M', 'dog\1', 'gi');
--> dog bobcat dog dogs catfish
Even after all of that, there is at least one unresolved condition. For example, sentences that begin with "Cat" will be replaced with lower-case "dog" which break sentence capitalization.
Check out the current PostgreSQL pattern matching docs for all the details.
Given my examples, maybe the safest option would be:
UPDATE table SET field = regexp_replace(field, '\mcat\M', 'dog', 'gi');
In theory everything is possible but reality you find the numbers much lower than you might expect. I have been trying to address huge spaces on servers often and found that even though a server can have huge amounts of memory it surprised me that most software actually never can address it in real scenario's simply because the cpu's are not fast enough to really address them. Why would you say right ?! . Timings thats the endless downfall of every enormous machine which i have worked on. So i would advise to not go overboard by addressing huge amounts just because you can, but use what you think could be used. Actual values are often much lower than what you expected. Ofcourse non of us really uses hp 9000 systems at home and most of you actually ever will go near the capacity of your home system ever. For instance most users do not have more than 16 Gb of memory in their system. Ofcourse some of the casual gamers use work stations for a game once a month but i bet that is a very small percentage. So coming down to earth means i would address on a 8 Gb 64 bit system not much more than 512 mb for heapspace or if you go overboard try 1 Gb. I am pretty sure its even with these numbers pure overkill. I have constant monitored the memory usage during gaming to see if the addressing would make any difference but did not notice any difference at all when i addressed much lower values or larger ones. Even on the server/workstations there was no visible change in performance no matter how large i set the values. That does not say some jave users might be able to make use of more space addressed, but this far i have not seen any of the applications needing so much ever. Ofcourse i assume that their would be a small difference in performance if java instances would run out of enough heapspace to work with. This far i have not found any of it at all, however lack of real installed memory showed instant drops of performance if you set too much heapspace. When you have a 4 Gb system you run quickly out of heapspace and then you will see some errors and slowdowns because people address too much space which actually is not free in the system so the os starts to address drive space to make up for the shortage hence it starts to swap.
Mark all the desired projects in solution explorer.
Press Alt-F7 or right click in solution explorer and select "Properties"
Configurations:All Configurations
Click on the Preprocessor Definitions line to invoke its editor
Choose Edit...
Copy "_CRT_SECURE_NO_WARNINGS" into the Preprocessor Definitions white box on the top.
Circle Time! :) Easy way of making a circle with a hollow center : use border-radius, give the element a border and no background so you can see through it :
div {_x000D_
display: inline-block;_x000D_
margin-left: 5px;_x000D_
height: 100px;_x000D_
border-radius: 100%;_x000D_
width:100px;_x000D_
border:solid black 2px;_x000D_
}_x000D_
_x000D_
body{_x000D_
background:url('http://lorempixel.com/output/people-q-c-640-480-1.jpg');_x000D_
background-size:cover;_x000D_
}
_x000D_
<div></div>
_x000D_
I will try to answer the question of "why". Imagine a situation where you have a huge database with a lot of columns in a table, and your project/system uses tools to generate entities from database. (Hibernate has those, etc...) Now, suppose that by your business logic you need a particular field NOT to be persisted. You have to "configure" your entity in a particular way. While Transient keyword works on an object - as it behaves within a java language, the @Transient only designed to answer the tasks that pertains only to persistence tasks.
You can try and do this:
myLabel.setText("<html>" + myString.replaceAll("<","<").replaceAll(">", ">").replaceAll("\n", "<br/>") + "</html>")
The advantages of doing this are:
<br/>
, without fail.<
and >
with <
and >
respectively, preventing some render havoc.What it does is:
"<html>" +
adds an opening html
tag at the beginning.replaceAll("<", "<").replaceAll(">", ">")
escapes <
and >
for convenience.replaceAll("\n", "<br/>")
replaces all newlines by br
(HTML line break) tags for what you wanted+ "</html>"
closes our html
tag at the end.P.S.: I'm very sorry to wake up such an old post, but whatever, you have a reliable snippet for your Java!
Using CentOS Linux I found that the easiest syntax would be:
wget "link" -O file.ext
where "link"
is the web address you want to save and "file.ext"
is the filename and extension of your choice.
import pandas as pd
data = pd.read_csv('data.csv')
# read row line by line
for d in data.values:
# read column by index
print(d[2])
Call SortedSet::first
Move elements, and call first()
.
new TreeSet<String>(
pContext.getParent().getPropertyValue( … ) // Transfer elements from your `Set` to this new `TreeSet`, an implementation of the `SortedSet` interface.
)
.first()
Set
Has No OrderAs others have said, a Set
by definition has no order. Therefore asking for the “first” element has no meaning.
Some implementations of Set
have an order such as the order in which items were added. That unofficial order may be available via the Iterator
. But that order is accidental and not guaranteed. If you are lucky, the implementation backing your Set
may indeed be a SortedSet
.
CAVEAT: If order is critical, do not rely on such behavior. If reliability is not critical, such undocumented behavior might be handy. If given a Set
you have no other viable alternative, so trying this may be better than nothing.
Object firstElement = mySet.iterator().next();
To directly address the Question… No, not really any shorter way to get first element from iterator while handling the possible case of an empty Set. However, I would prefer an if
test for isEmpty
rather than the Question’s for
loop.
if ( ! mySet.isEmpty() ) {
Object firstElement = mySet.iterator().next();
)
SortedSet
If you care about maintaining a sort order in a Set
, use a SortedSet
implementation. Such implementations include:
TreeSet
.ConcurrentSkipListSet
.SortedSetMultimap
class returns a SortedSet
from its asMap
method.LinkedHashSet
For Insertion-OrderIf all you need is to remember elements in the order they were added to the Set
use a LinkedHashSet
.
To quote the doc, this class…
maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order).
It is a string formatting syntax (which it borrows from C).
Please see "PyFormat":
Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the
%s
placeholder.
Edit: Here is a really simple example:
#Python2
name = raw_input("who are you? ")
print "hello %s" % (name,)
#Python3+
name = input("who are you? ")
print("hello %s" % (name,))
The %s
token allows me to insert (and potentially format) a string. Notice that the %s
token is replaced by whatever I pass to the string after the %
symbol. Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.
Use Enum.Parse()
.
var content = (ContentEnum)Enum.Parse(typeof(ContentEnum), fileContentMessage);
Probably already too late to answer but since you have already parse the dates while loading the data, you can just do this to get the day
df['date'] = pd.DatetimeIndex(df['date']).year
You can use substring and strpos to accomplish this goal.
You could also use a regular expression to pattern match only what you want. Your mileage may vary on which of these approaches makes more sense.
Just to make this absolutely clear for all:
A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.
This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.
To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.
To qualify the preferred naming conventions:
If you don't use ngRoute module, i.e. you don't have $viewContentLoaded event.
You can use another directive method:
angular.module('someModule')
.directive('someDirective', someDirective);
someDirective.$inject = ['$rootScope', '$timeout']; //Inject services
function someDirective($rootScope, $timeout){
return {
restrict: "A",
priority: Number.MIN_SAFE_INTEGER, //Lowest priority
link : function(scope, element, attr){
$timeout(
function(){
$rootScope.$emit("Some:event");
}
);
}
};
}
Accordingly to trusktr's answer it has lowest priority. Plus $timeout will cause Angular to run through an entire event loop before callback execution.
$rootScope used, because it allow to place directive in any scope of the application and notify only necessary listeners.
$rootScope.$emit will fire an event for all $rootScope.$on listeners only. The interesting part is that $rootScope.$broadcast will notify all $rootScope.$on as well as $scope.$on listeners Source
This is a very good article: http://java.sun.com/developer/technicalArticles/Programming/PerfTuning/
In summary, for great performance, you should:
For example, to reduce the access to disk, you can use a large buffer. The article describes various approaches.
Here is an example which I use in my source code. I am getting key and value from Dictionary from element 0 to number of elements in my Dictionary. Then I fill my string[] array which I send as a parameter after in my function which accept only params string[]
Dictionary<string, decimal> listKomPop = addElements();
int xpopCount = listKomPop.Count;
if (xpopCount > 0)
{
string[] xpostoci = new string[xpopCount];
for (int i = 0; i < xpopCount; i++)
{
/* here you have key and value element */
string key = listKomPop.Keys.ElementAt(i);
decimal value = listKomPop[key];
xpostoci[i] = value.ToString();
}
...
This solution works with SortedDictionary also.
The following approach worked well for me. Modified from here.
function callback(theVar) {_x000D_
return function() {_x000D_
theVar();_x000D_
}_x000D_
}_x000D_
_x000D_
function some_other_function() {_x000D_
document.body.innerHTML += "made it.";_x000D_
}_x000D_
_x000D_
var someVar = some_other_function;_x000D_
document.getElementById('button').addEventListener('click', callback(someVar));
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<button type="button" id="button">Click Me!</button>_x000D_
</body>_x000D_
</html>
_x000D_
An update:
As of Laravel 5.3 doing this in a single step is possible; the firstOrCreate
method now accepts an optional second array as an argument.
The first array argument is the array on which the fields/values are matched, and the second array is the additional fields to use in the creation of the model if no match is found via matching the fields/values in the first array:
Better to first compress catalog on remote server:
tar czfP backup.tar.gz /path/to/catalog
Secondly, download from remote:
scp [email protected]:/path/to/backup.tar.gz .
At the end, extract the files:
tar -xzvf backup.tar.gz
I wrote Class Visualizer, which does it. It's free tool which has all the mentioned functionality - I personally use it for the same purposes, as described in this post. For each browsed class it shows 2 instantly generated class diagrams: class relations and class UML view. Class relations diagram allows to traverse through the whole structure. It has full support for annotations and generics plus special support for JPA entities. Works very well with big projects (thousands of classes).
Here's a bash function which checks all your servers, assuming you're using DNS round-robin. Note that this requires GNU date and won't work on Mac OS
function check_certs () {
if [ -z "$1" ]
then
echo "domain name missing"
exit 1
fi
name="$1"
shift
now_epoch=$( date +%s )
dig +noall +answer $name | while read _ _ _ _ ip;
do
echo -n "$ip:"
expiry_date=$( echo | openssl s_client -showcerts -servername $name -connect $ip:443 2>/dev/null | openssl x509 -inform pem -noout -enddate | cut -d "=" -f 2 )
echo -n " $expiry_date";
expiry_epoch=$( date -d "$expiry_date" +%s )
expiry_days="$(( ($expiry_epoch - $now_epoch) / (3600 * 24) ))"
echo " $expiry_days days"
done
}
Output example:
$ check_certs stackoverflow.com
151.101.1.69: Aug 14 12:00:00 2019 GMT 603 days
151.101.65.69: Aug 14 12:00:00 2019 GMT 603 days
151.101.129.69: Aug 14 12:00:00 2019 GMT 603 days
151.101.193.69: Aug 14 12:00:00 2019 GMT 603 days
More simply, this is what works for me:
MY_DIR=`dirname $0`
source $MY_DIR/_inc_db.sh
So I got a new server, this time it's Windows 2008R2 and my app works fine.
I can't say for sure what the problem was with the old server but I have one idea.
So because I previously compiled the app without any platform in mind it gave me the dll
version which only works if the target host has .Net Core Windows Hosting
package installed. In my case it was installed and that was fine.
After the app didn't work I decieded to compile it as a console app with win7-x64
as runtime. This time the moment I ran the exe
of my app on the server, it crashed with an error about a missing dll:
The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing
That dll is from Universal C Runtime that's included in the Visual C++ Redistributable for Visual Studio 2015.
I tried to install that package (both x64 & x86) but it failed each time (don't know why) on Windows Server 2012 R2.
But when I tried to install them in the new server, Windows Server 2008 R2, they successfully installed. That might have been the reason behind it, but still can't say for sure.
Templates are all about the compiler generating code at compile-time. Virtual functions are all about the run-time system figuring out which function to call at run-time.
Once the run-time system figured out it would need to call a templatized virtual function, compilation is all done and the compiler cannot generate the appropriate instance anymore. Therefore you cannot have virtual member function templates.
However, there are a few powerful and interesting techniques stemming from combining polymorphism and templates, notably so-called type erasure.
Newer method that works on all current browsers:
this.scrollIntoView(false);
Make sure that your log4j is configured correctly, there's probably an exception that is being thrown, but you're only seeing half of the picture.
Please see https://stackoverflow.com/a/16817018/1249304
using $('#introVideo').modal('show');
conflicts with bootstrap proper triggering. When you click on the link that opens the Modal it will close right after completing the fade animation.
Just remove the $('#introVideo').modal('show');
(using bootstrap v3.3.2)
Here is my code:
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">_x000D_
<!-- triggering Link -->_x000D_
<a id="videoLink" href="#0" class="video-hp" data-toggle="modal" data-target="#introVideo"><img src="img/someImage.jpg">toggle video</a>_x000D_
_x000D_
_x000D_
<!-- Intro video -->_x000D_
<div class="modal fade" id="introVideo" tabindex="-1" role="dialog" aria-labelledby="introductionVideo" aria-hidden="true">_x000D_
<div class="modal-dialog modal-lg">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<div class="embed-responsive embed-responsive-16by9">_x000D_
<iframe class="embed-responsive-item allowfullscreen"></iframe>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"> </script>_x000D_
_x000D_
<script>_x000D_
//JS_x000D_
_x000D_
$('#videoLink').click(function () {_x000D_
var src = 'https://www.youtube.com/embed/VI04yNch1hU;autoplay=1';_x000D_
// $('#introVideo').modal('show'); <-- remove this line_x000D_
$('#introVideo iframe').attr('src', src);_x000D_
});_x000D_
_x000D_
_x000D_
$('#introVideo button.close').on('hidden.bs.modal', function () {_x000D_
$('#introVideo iframe').removeAttr('src');_x000D_
})_x000D_
</script>
_x000D_
Most likely, you ran out of memory, so the Kernel killed your process.
Have you heard about OOM Killer?
Here's a log from a script that I developed for processing a huge set of data from CSV files:
Mar 12 18:20:38 server.com kernel: [63802.396693] Out of memory: Kill process 12216 (python3) score 915 or sacrifice child
Mar 12 18:20:38 server.com kernel: [63802.402542] Killed process 12216 (python3) total-vm:9695784kB, anon-rss:7623168kB, file-rss:4kB, shmem-rss:0kB
Mar 12 18:20:38 server.com kernel: [63803.002121] oom_reaper: reaped process 12216 (python3), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB
It was taken from /var/log/syslog
.
Basically:
PID 12216 elected as a victim (due to its use of +9Gb of total-vm), so oom_killer reaped it.
Here's a article about OOM behavior.
Let me explain the difference between “and” - “&&” - "&".
"&&" and "and" both are logical AND operations and they do the same thing, but the operator precedence is different.
The precedence (priority) of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator.
Mixing them together in single operation, could give you unexpected results in some cases I recommend always using &&, but that's your choice.
On the other hand "&" is a bitwise AND operation. It's used for the evaluation and manipulation of specific bits within the integer value.
Example if you do (14 & 7) the result would be 6.
7 = 0111
14 = 1110
------------
= 0110 == 6
ColumnNames
is a property of type List<String>
so when you are setting up you need to pass a List<String>
in the Returns
call as an argument (or a func which return a List<String>
)
But with this line you are trying to return just a string
input.SetupGet(x => x.ColumnNames).Returns(temp[0]);
which is causing the exception.
Change it to return whole list:
input.SetupGet(x => x.ColumnNames).Returns(temp);
I guess anther way, possibly faster, to achieve this is
1) Use dict comprehension to get desired dict (i.e., taking 2nd col of each array)
2) Then use pd.DataFrame
to create an instance directly from the dict without loop over each col and concat.
Assuming your mat
looks like this (you can ignore this since your mat
is loaded from file):
In [135]: mat = {'a': np.random.randint(5, size=(4,2)),
.....: 'b': np.random.randint(5, size=(4,2))}
In [136]: mat
Out[136]:
{'a': array([[2, 0],
[3, 4],
[0, 1],
[4, 2]]), 'b': array([[1, 0],
[1, 1],
[1, 0],
[2, 1]])}
Then you can do:
In [137]: df = pd.DataFrame ({name:mat[name][:,1] for name in mat})
In [138]: df
Out[138]:
a b
0 0 0
1 4 1
2 1 0
3 2 1
[4 rows x 2 columns]
input = InputBox("Text:")
If input <> "" Then
' Normal
Else
' Cancelled, or empty
End If
From MSDN:
If the user clicks Cancel, the function returns a zero-length string ("").
Follow this instructions from standard eclipse docs.
Just made autocrlf
param in .gitconfig file false
and recloned the code. It worked!
[core]
autocrlf = false
I'm looking at a similar problem, and I've found some of the best references come from chemistry (from peaks finding in mass-spec data). For a good thorough review of peaking finding algorithms read this. This is one of the best clearest reviews of peak finding techniques that I've run across. (Wavelets are the best for finding peaks of this sort in noisy data.).
It looks like your peaks are clearly defined and aren't hidden in the noise. That being the case I'd recommend using smooth savtizky-golay derivatives to find the peaks (If you just differentiate the data above you'll have a mess of false positives.). This is a very effective technique and is pretty easy to implemented (you do need a matrix class w/ basic operations). If you simply find the zero crossing of the first S-G derivative I think you'll be happy.
How about a fully functional implementation of a non-recursive Linked List?
I created this for my Algorithms I class as a stepping stone to gain a better understanding before moving onto writing a doubly-linked queue class for an assignment.
Here's the code:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedList<T> implements Iterable<T> {
private Node first;
private Node last;
private int N;
public LinkedList() {
first = null;
last = null;
N = 0;
}
public void add(T item) {
if (item == null) { throw new NullPointerException("The first argument for addLast() is null."); }
if (!isEmpty()) {
Node prev = last;
last = new Node(item, null);
prev.next = last;
}
else {
last = new Node(item, null);
first = last;
}
N++;
}
public boolean remove(T item) {
if (isEmpty()) { throw new IllegalStateException("Cannot remove() from and empty list."); }
boolean result = false;
Node prev = first;
Node curr = first;
while (curr.next != null || curr == last) {
if (curr.data.equals(item)) {
// remove the last remaining element
if (N == 1) { first = null; last = null; }
// remove first element
else if (curr.equals(first)) { first = first.next; }
// remove last element
else if (curr.equals(last)) { last = prev; last.next = null; }
// remove element
else { prev.next = curr.next; }
N--;
result = true;
break;
}
prev = curr;
curr = prev.next;
}
return result;
}
public int size() {
return N;
}
public boolean isEmpty() {
return N == 0;
}
private class Node {
private T data;
private Node next;
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
}
public Iterator<T> iterator() { return new LinkedListIterator(); }
private class LinkedListIterator implements Iterator<T> {
private Node current = first;
public T next() {
if (!hasNext()) { throw new NoSuchElementException(); }
T item = current.data;
current = current.next;
return item;
}
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }
}
@Override public String toString() {
StringBuilder s = new StringBuilder();
for (T item : this)
s.append(item + " ");
return s.toString();
}
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
while(!StdIn.isEmpty()) {
String input = StdIn.readString();
if (input.equals("print")) { StdOut.println(list.toString()); continue; }
if (input.charAt(0) == ('+')) { list.add(input.substring(1)); continue; }
if (input.charAt(0) == ('-')) { list.remove(input.substring(1)); continue; }
break;
}
}
}
Note: It's a pretty basic implementation of a singly-linked-list. The 'T' type is a generic type placeholder. Basically, this linked list should work with any type that inherits from Object. If you use it for primitive types be sure to use the nullable class equivalents (ex 'Integer' for the 'int' type). The 'last' variable isn't really necessary except that it shortens insertions to O(1) time. Removals are slow since they run in O(N) time but it allows you to remove the first occurrence of a value in the list.
If you want you could also look into implementing:
Honestly, it only takes a few lines of code to make this a doubly-linked list. The main difference between this and a doubly-linked-list is that the Node instances of a doubly-linked list require an additional reference that points to the previous element in the list.
The benefit of this over a recursive implementation is that it's faster and you don't have to worry about flooding the stack when you traverse large lists.
There are 3 commands to test this in the debugger/console:
If you have never seen the internals of how one of these works I suggest you step through the following in the debugger:
While there are better and more efficient approaches for lists like array-lists, understanding how the application traverses via references/pointers is integral to understanding how many higher-level data structures work.
To display dataframes contained in a list:
display(*dfs)
I found this thread looking for a way to control Shift + any key. I pasted together other solutions to make this combined function to accomplish what I needed. I hope it helps someone else.
function () {
return this.each(function () {
$(this).keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
// Shift + anything is not desired
if (e.shiftKey) {
return false;
}
// allow backspace, tab, delete, enter, arrows, numbers
//and keypad numbers ONLY
// home, end, period, and numpad decimal
return (
key == 8 ||
key == 9 ||
key == 13 ||
key == 46 ||
key == 110 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
});
This is a classic case of divitis - you don't need a div to be clickable, just give the <a>
tag a class. Then edit the CSS of the class to display:block, and define a height and width like a lot of other answers have mentioned.
The <a>
tag works perfectly well on its own, so you don't need an extra level of mark-up on the page.
You should be able to find your command with a ps
variant like:
ps -ef
ps -fubob # if your job's user ID is bob.
Then, once located, it should be a simple matter to use kill
to kill the process (permissions permitting).
If you're talking about getting rid of jobs in the at
queue (that aren't running yet), you can use atq
to list them and atrm
to get rid of them.
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
Where str
is your XML string. See the MSDN article for more info.
I had this error and the other fixes didn't help me, but changing the CPU type the emulator used did get it working.
Create a new emulator and try using mips or arm for the cpu selection
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
If you want to do this often, you can create a keybindings file in your Library to map it to a key combination.
In ~/Library create a directory named KeyBindings. Create a file named DefaultKeyBinding.dict inside the directory. You can add key bindings in this format:
{
"x" = (insertText:, "\U23CF");
"y" = (insertText:, "hi"); /* warning: this will change 'y' to 'hi'! */
}
The LHS is the key combination you'll hit to enter the character. You can use the following characters to indicate command keys:
@ - Command
~ - Option
^ - Control
You'll need to look up the unicode for your character (in this case, ? is \U2234). So to type this character whenever you typed Control-M, you'd use
"^m" = (insertText:, "\U2234");
You can find more information here: http://www.hcs.harvard.edu/~jrus/site/cocoa-text.html
Default metro builder runs on port 8081. But in my PC, this port is already occupied by some other process (McAfee Antivirus) So I changed the default running port of metro builder to port number 8088 using the following command
react-native run-android start --port=8088
This resolved my issue and the app works fine now.
PS: You can check whether a port is occupied or not in windows using "Resource Monitor" app. (Under "Listening Ports" in "Network" tab). Check out this link for detailed explanation: https://www.paddingleft.com/2018/05/03/Find-process-listening-port-on-Windows/
For ease of implementation, it's hard to beat naively searching through an array. Aside from some error checking, this is a complete implementation (untested).
typedef struct dict_entry_s {
const char *key;
int value;
} dict_entry_s;
typedef struct dict_s {
int len;
int cap;
dict_entry_s *entry;
} dict_s, *dict_t;
int dict_find_index(dict_t dict, const char *key) {
for (int i = 0; i < dict->len; i++) {
if (!strcmp(dict->entry[i], key)) {
return i;
}
}
return -1;
}
int dict_find(dict_t dict, const char *key, int def) {
int idx = dict_find_index(dict, key);
return idx == -1 ? def : dict->entry[idx].value;
}
void dict_add(dict_t dict, const char *key, int value) {
int idx = dict_find_index(dict, key);
if (idx != -1) {
dict->entry[idx].value = value;
return;
}
if (dict->len == dict->cap) {
dict->cap *= 2;
dict->entry = realloc(dict->entry, dict->cap * sizeof(dict_entry_s));
}
dict->entry[dict->len].key = strdup(key);
dict->entry[dict->len].value = value;
dict->len++;
}
dict_t dict_new(void) {
dict_s proto = {0, 10, malloc(10 * sizeof(dict_entry_s))};
dict_t d = malloc(sizeof(dict_s));
*d = proto;
return d;
}
void dict_free(dict_t dict) {
for (int i = 0; i < dict->len; i++) {
free(dict->entry[i].key);
}
free(dict->entry);
free(dict);
}
Use optparse
which comes with the standard library. For example:
#!/usr/bin/env python
import optparse
def main():
p = optparse.OptionParser()
p.add_option('--person', '-p', default="world")
options, arguments = p.parse_args()
print 'Hello %s' % options.person
if __name__ == '__main__':
main()
Source: Using Python to create UNIX command line tools
However as of Python 2.7 optparse is deprecated, see: Why use argparse rather than optparse?
Essentially, and as-noted by @kevin-b:
// find('#id')
angular.element(document.querySelector('#id'))
//find('.classname'), assumes you already have the starting elem to search from
angular.element(elem.querySelector('.classname'))
Note: If you're looking to do this from your controllers you may want to have a look at the "Using Controllers Correctly" section in the developers guide and refactor your presentation logic into appropriate directives (such as <a2b ...>).
This is my code without any div within the header tag. My goal/intention is to implement the same behavior with minimal HTML tags and CSS style. It works.
whois.css
.header-img {
height: 9%;
width: 15%;
}
header {
background: dodgerblue;
}
header h1 {
display: inline;
}
whois.html
<!DOCTYPE html>
<head>
<title> Javapedia.net WHOIS Lookup </title>
<link rel="stylesheet" type="text/css" href="whois.css"/>
</head>
<body>
<header>
<img class="header-img" src ="javapediafb.jpg" alt="javapedia.net" href="https://www.javapedia.net"/>
<h1>WHOIS Lookup</h1>
</header>
</body>
As Homebrew is my favorite for macOS although it is possible to have apt-get
on macOS using Fink.
You can actually create a simple Array with Alert Dialog like this.
val sexArray = arrayOf("Male", "Female")
val selectedPosition = 0
AlertDialog.Builder(requireContext())
.setSingleChoiceItems(sexArray, 0) { dialog, position ->
val selectedSex = sexArray[position]
}.show()
You can just use wildcards in the predicate (after IF, WHERE or ON):
@mainstring LIKE '%' + @substring + '%'
or in this specific case
' ' + @mainstring + ' ' LIKE '% ME[., ]%'
(Put the spaces in the quoted string if you're looking for the whole word, or leave them out if ME can be part of a bigger word).
You must have copy/paste text from Word Document. Word document use Smart Quotes. You can replace it with Special Character (’) or simply type in your HTML editor (').
I'm sure this will solve your problem.
As written in How to pop fragment off backstack and by LarsH here, we can pop several fragments from top down to specifical tag (together with the tagged fragment) using this method:
fragmentManager?.popBackStack ("frag", FragmentManager.POP_BACK_STACK_INCLUSIVE);
Substitute "frag" with your fragment's tag. Remember that first we should add the fragment to backstack with:
fragmentTransaction.addToBackStack("frag")
If we add fragments with addToBackStack(null)
, we won't pop fragments that way.
Like many people, I was looking for something that was:
...But alas - nothing!
Well if a job's worth doing... I was able to get something up and running in about 30 mins. Disclaimer: there's quite a few known (and probably a few as yet unknown) problems with it, but it makes me wonder what on Earth the other 2920 lines of JS are there for in many offerings!
(window => {
let initCoords;
const coords_update = e => {
if (initCoords) {
const elem = initCoords.bar.closest('.scrollr');
const eSuffix = initCoords.axis.toUpperCase();
const sSuffix = initCoords.axis == 'x' ? 'Left' : 'Top';
const dSuffix = initCoords.axis == 'x' ? 'Width' : 'Height';
const max = elem['scroll' + dSuffix] - elem['client' + dSuffix];
const room = elem['client' + dSuffix] - initCoords.bar['client' + dSuffix];
const delta = e['page' + eSuffix] - initCoords.abs;
const abs = initCoords.p0 + delta;
elem['scroll' + sSuffix] = max * abs / room;
}
};
const scrollr_resize = elem => {
const xBar = elem.querySelector('.track.x .bar');
const yBar = elem.querySelector('.track.y .bar');
const xRel = elem.clientWidth / elem.scrollWidth;
const yRel = elem.clientHeight / elem.scrollHeight;
xBar.style.width = (100 * xRel).toFixed(2) + '%';
yBar.style.height = (100 * yRel).toFixed(2) + '%';
};
const scrollr_init = elem => {
const xTrack = document.createElement('span');
const yTrack = document.createElement('span');
const xBar = document.createElement('span');
const yBar = document.createElement('span');
xTrack.className = 'track x';
yTrack.className = 'track y';
xBar.className = 'bar';
yBar.className = 'bar';
xTrack.appendChild(xBar);
yTrack.appendChild(yBar);
elem.appendChild(xTrack);
elem.appendChild(yTrack);
elem.addEventListener('wheel', scrollr_OnWheel);
elem.addEventListener('scroll', scrollr_OnScroll);
xTrack.addEventListener('wheel', xTrack_OnWheel);
xTrack.addEventListener('click', xTrack_OnClick);
xTrack.addEventListener('mouseover', () => xTrack.classList.add('active'));
xTrack.addEventListener('mouseout', () => {
if (!initCoords) xTrack.classList.remove('active');
});
yTrack.addEventListener('click', yTrack_OnClick);
yTrack.addEventListener('mouseover', () => yTrack.classList.add('active'));
yTrack.addEventListener('mouseout', () => {
if (!initCoords) yTrack.classList.remove('active');
});
xBar.addEventListener('click', bar_OnClick);
xBar.addEventListener('mousedown', xBar_OnMouseDown);
yBar.addEventListener('click', bar_OnClick);
yBar.addEventListener('mousedown', yBar_OnMouseDown);
scrollr_resize(elem);
};
window.addEventListener('load', e => {
const scrollrz = Array.from(document.querySelectorAll('.scrollr'));
scrollrz.forEach(scrollr_init);
});
window.addEventListener('resize', e => {
const scrollrz = Array.from(document.querySelectorAll('.scrollr'));
scrollrz.forEach(scrollr_resize);
});
window.addEventListener('mousemove', coords_update);
window.addEventListener('mouseup', e => {
initCoords = null;
Array.from(document.querySelectorAll('.track.active'))
.forEach(elem => elem.classList.remove('active'));
});
function xBar_OnMouseDown(e) {
const p0 = this.offsetLeft;
initCoords = {
axis: 'x',
abs: e.pageX,
bar: this,
p0
};
}
function yBar_OnMouseDown(e) {
const p0 = this.offsetTop;
initCoords = {
axis: 'y',
abs: e.pageY,
bar: this,
p0
};
}
function bar_OnClick(e) {
e.stopPropagation();
}
function xTrack_OnClick(e) {
const elem = this.closest('.scrollr');
const xBar = this.querySelector('.bar');
let unit = elem.clientWidth - 30;
if (e.offsetX <= xBar.offsetLeft) unit *= -1;
elem.scrollLeft += unit;
}
function yTrack_OnClick(e) {
const elem = this.closest('.scrollr');
const yBar = this.querySelector('.bar');
let unit = elem.clientHeight - 30;
if (e.offsetY <= yBar.offsetTop) unit *= -1;
elem.scrollTop += unit;
}
function xTrack_OnWheel(e) {
e.stopPropagation();
const elem = this.closest('.scrollr');
const left0 = elem.scrollLeft;
const delta = e.deltaY !== 0 ? e.deltaY : e.deltaX;
elem.scrollLeft += delta;
const moved = left0 !== elem.scrollLeft;
if (moved) e.preventDefault();
}
function scrollr_OnWheel(e) {
const left0 = this.scrollLeft;
const top0 = this.scrollTop;
this.scrollLeft += e.deltaX;
this.scrollTop += e.deltaY;
const moved = left0 !== this.scrollLeft || top0 !== this.scrollTop;
if (moved) e.preventDefault();
}
function scrollr_OnScroll(e) {
const xTrack = this.querySelector('.track.x');
const yTrack = this.querySelector('.track.y');
const xBar = xTrack.querySelector('.bar');
const yBar = yTrack.querySelector('.bar');
const xMax = this.scrollWidth - this.clientWidth;
const yMax = this.scrollHeight - this.clientHeight;
const xFrac = this.scrollLeft / xMax;
const yFrac = this.scrollTop / yMax;
const xAbs = xFrac * (this.clientWidth - xBar.clientWidth);
const yAbs = yFrac * (this.clientHeight - yBar.clientHeight);
xTrack.style.left = this.scrollLeft + 'px';
xTrack.style.bottom = -this.scrollTop + 'px';
xBar.style.left = xAbs + 'px';
yTrack.style.top = this.scrollTop + 'px';
yTrack.style.right = -this.scrollLeft + 'px';
yBar.style.top = yAbs + 'px';
};
})(window);
_x000D_
.scrollr {
overflow: hidden;
position: relative;
}
.track {
position: absolute;
cursor: pointer;
transition: background-color .3s;
user-select: none;
}
.track.x {
left: 0;
bottom: 0;
width: 100%;
height: 10px;
}
.track.y {
top: 0;
right: 0;
height: 100%;
width: 10px;
}
.bar {
position: absolute;
background-color: yellow;
transition: background-color .3s, opacity .3s, width .3s, height .3s, margin .3s;
display: block;
width: 100%;
height: 100%;
opacity: .7;
}
.track.x .bar {
min-width: 25px;
height: 3px;
margin: 5px 0 2px 0;
}
.track.y .bar {
min-height: 25px;
width: 3px;
margin: 0 2px 0 5px;
}
.track.active {
background-color: #ccc;
}
.track.active .bar {
background-color: #999;
margin: 0;
opacity: 1;
}
.track.x.active .bar {
height: 10px;
}
.track.y.active .bar {
width: 10px;
}
/* Custom client stuff */
.content {
background: red;
}
.content p {
width: 450px;
margin: 0;
}
.scrollr {
max-width: 350px;
max-height: 150px;
}
_x000D_
<div class="scrollr content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
<p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
<p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
<p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
<p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
<p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
<p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
<p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
<p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
<p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
<p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
<p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
<p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
</div>
_x000D_
This helped me at the end:
Quick guide:
Download Google USB Driver
Connect your device with Android Debugging enabled to your PC
Open Device Manager of Windows from System Properties.
Your device should appear under Other devices
listed as something like
Android ADB Interface
or 'Android Phone' or similar. Right-click that and
click on Update Driver Software...
Select Browse my computer for driver software
Select Let me pick from a list of device drivers on my computer
Double-click Show all devices
Press the Have disk
button
Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf
Select Android ADB Interface
from the list of device types.
Press the Yes
button
Press the Install
button
Press the Close
button
Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.
Python 3 includes an improved super() which allows use like this:
super().__init__(args)
String[] split = data.split("\\|",-1);
This is not the actual requirement in all the time. The Drawback of above is show below:
Scenerio 1:
When all data are present:
String data = "5|6|7||8|9|10|";
String[] split = data.split("\\|");
String[] splt = data.split("\\|",-1);
System.out.println(split.length); //output: 7
System.out.println(splt.length); //output: 8
When data is missing:
Scenerio 2: Data Missing
String data = "5|6|7||8|||";
String[] split = data.split("\\|");
String[] splt = data.split("\\|",-1);
System.out.println(split.length); //output: 5
System.out.println(splt.length); //output: 8
Real requirement is length should be 7 although there is data missing. Because there are cases such as when I need to insert in database or something else. We can achieve this by using below approach.
String data = "5|6|7||8|||";
String[] split = data.split("\\|");
String[] splt = data.replaceAll("\\|$","").split("\\|",-1);
System.out.println(split.length); //output: 5
System.out.println(splt.length); //output:7
What I've done here is, I'm removing "|" pipe at the end and then splitting the String. If you have "," as a seperator then you need to add ",$" inside replaceAll.