On production I prefer to redirect the requests to .php files under the directories where PHP processing should be disabled to a home page or to 404 page. This won't reveal any source code (why search engines should index uploaded malicious code?) and will look more friendly for visitors and even for evil hackers trying to exploit the stuff. Also it can be implemented in mostly in any context - vhost or .htaccess. Something like this:
<DirectoryMatch "^${docroot}/(image|cache|upload)/">
<FilesMatch "\.php$">
# use one of the redirections
#RedirectMatch temp "(.*)" "http://${servername}/404/"
RedirectMatch temp "(.*)" "http://${servername}"
</FilesMatch>
</DirectoryMatch>
Adjust the directives as you need.
May this one help a little more
Let suppose if you want to make the bar button in a separate file(for modular approach) and want to give selector back to your viewcontroller, you can do like this :-
your Utility File
class GeneralUtility {
class func customeNavigationBar(viewController: UIViewController,title:String){
let add = UIBarButtonItem(title: "Play", style: .plain, target: viewController, action: #selector(SuperViewController.buttonClicked(sender:)));
viewController.navigationController?.navigationBar.topItem?.rightBarButtonItems = [add];
}
}
Then make a SuperviewController class and define the same function on it.
class SuperViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@objc func buttonClicked(sender: UIBarButtonItem) {
}
}
and In our base viewController(which inherit your SuperviewController class) override the same function
import UIKit
class HomeViewController: SuperViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
GeneralUtility.customeNavigationBar(viewController: self,title:"Event");
}
@objc override func buttonClicked(sender: UIBarButtonItem) {
print("button clicked")
}
}
Now just inherit the SuperViewController in whichever class you want this barbutton.
Thanks for the read
Off course, myDico.Values is List<List<MyType>>
.
Use Linq if you want to flattern your lists
var items = myDico.SelectMany (d => d.Value).ToList();
You can use fuckit module.
Wrap your code in a function with @fuckit
decorator:
@fuckit
def func():
code a
code b #if b fails, it should ignore, and go to c.
code c #if c fails, go to d
code d
https://kotlinlang.org/docs/reference/collections.html
According to above link List<E> is immutable in Kotlin. However this would work:
var list2 = ArrayList<String>()
list2.removeAt(1)
Be careful. For this you need @GET (not @PUT).
You can use it to transform some aggregate functions into analytic:
SELECT MAX(date)
FROM mytable
will return 1
row with a single maximum,
SELECT MAX(date) OVER (ORDER BY id)
FROM mytable
will return all rows with a running maximum.
bool IsExist = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("/UploadedFiles/"));
if (!IsExist)
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("/UploadedFiles/"));
StreamWriter textWriter = File.CreateText(Path.Combine(HttpContext.Current.Server.MapPath("/UploadedFiles/") + "FileName.csv"));
var csvWriter = new CsvWriter(textWriter, System.Globalization.CultureInfo.CurrentCulture);
csvWriter.WriteRecords(classVM);
You are using relative paths for your assets, change to an absolute path and everything will work (add a slash before "css".
<link rel="stylesheet" href="/css/app.css" />
Like most database problems, they should be solved by using the database.
Storing the data you want to group by and using indexes you can achieve an efficient and clear method to solve this problem.
$table->tinyInteger('activity_year')->unsigned()->index();
$table->smallInteger('activity_day_of_year')->unsigned()->index();
<?php
namespace App\Models;
use DB;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class PageView extends Model
{
public function scopePerDay($query){
$query->groupBy('activity_year');
$query->groupBy('activity_day_of_year');
return $query;
}
public function setUpdatedAt($value)
{
$date = Carbon::now();
$this->activity_year = (int)$date->format('y');
$this->activity_day_of_year = $date->dayOfYear;
return parent::setUpdatedAt($value);
}
$viewsPerDay = PageView::perDay()->get();
Use regular expression to match your requirement.
String num,num1,num2;
String str = "123-456-789";
String regex ="(\\d+)";
Matcher matcher = Pattern.compile( regex ).matcher( str);
while (matcher.find( ))
{
num = matcher.group();
System.out.print(num);
}
It depends on how your $('site-header') is constructed.
You can try to use $timeout with 0 delay. Something like:
return function(scope, element, attrs) {
$timeout(function(){
$('.main').height( $('.site-header').height() - $('.site-footer').height() );
});
}
Explanations how it works: one, two.
Don't forget to inject $timeout
in your directive:
.directive('sticky', function($timeout)
I got the same error when I executed the Spring JPA deleteAll()
method from Junit test cases. I simply used the deleteInBatch()
& deleteAllInBatch()
and its perfectly works. We do not need to mark @Transactional
at the test cases level.
You can try using Regular Expressions by testing the input string to have only digits (0-9) by using the .IsMatch(string input, string pattern)
method in C#.
using System;
using System.Text.RegularExpression;
public namespace MyNS
{
public class MyClass
{
public void static Main(string[] args)
{
string input = Console.ReadLine();
bool containsNumber = ContainsOnlyDigits(input);
}
private bool ContainOnlyDigits (string input)
{
bool containsNumbers = true;
if (!Regex.IsMatch(input, @"/d"))
{
containsNumbers = false;
}
return containsNumbers;
}
}
}
Regards
enter code here public Timer timer;
public TimerTask task;
public ImageView slidingimage;
private int[] IMAGE_IDS = {
R.drawable.home_banner1, R.drawable.home_banner2, R.drawable.home_banner3
};
enter code here @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 2000; // delay for 1 sec.
int period = 2000; // repeat every 4 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
enter code here private void AnimateandSlideShow() {
slidingimage = (ImageView)findViewById(R.id.banner);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.custom_anim);
slidingimage.startAnimation(rotateimage);
}
I had the same problem. Get the warning. Went to Data connections and deleted connection. Save, close reopen. Still get the warning. I use a xp/vista menu plugin for classic menus. I found under data, get external data, properties, uncheck the save query definition. Save close and reopen. That seemed to get rid of the warning. Just removing the connection does not work. You have to get rid of the query.
Certainly TOP will surfice if you simply want the TOP 2, but if you need them individually so that you can do something with those values then use the ROW_NUMBER which will give you more control over the rows you want to select
ps. I did this as i'm not sure if the OP is after a simple TOP 2 in a select. (I may be wrong!)
-- Get first row, same as TOP 1
SELECT [Id] FROM
(
SELECT [Id], ROW_NUMBER() OVER (ORDER BY [Id]) AS Rownumber
FROM table
) results
WHERE results.Rownumber = 1
-- Get second row only
SELECT [Id] FROM
(
SELECT [Id], ROW_NUMBER() OVER (ORDER BY [Id]) AS Rownumber
FROM table
) results
WHERE results.Rownumber = 2
I had a similar issue and ended up with this:
For me this has the advantage that data and annotation are not overlapping.
from matplotlib import pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54
plt.plot(A,B)
# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
x = A[ind]
y = B[ind]
xPos = x1 + .02 * (x1 - x0)
yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
ax.annotate('',#label,
xy=(x, y), xycoords='data',
xytext=(xPos, yPos), textcoords='data',
arrowprops=dict(
connectionstyle="arc3,rad=0.",
shrinkA=0, shrinkB=10,
arrowstyle= '-|>', ls= '-', linewidth=2
),
va='bottom', ha='left', zorder=19
)
ax.text(xPos + .01 * (x1 - x0), yPos,
'({:.2f}, {:.2f})'.format(x,y),
transform=ax.transData, va='center')
plt.grid()
plt.show()
Using the text argument in .annotate
ended up with unfavorable text positions.
Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.
In my case I upgraded to VS2017 and wanted to build all projects with MSBuild 4 with my build script (which had been using MSBuild 3.5 when we were using VS2015). That MSBuild upgrade appeared fine for the Windows desktop applications but the ones for Windows CE with compact framework would give me this confusing error. Reverting to MSBuild 3.5 for Windows CE projects fixed the issue for me.
I did have the BOM in .csproj files by the way and removed them for all projects in a solution that would not build but that did not help.
The List
s allow you to use and work with subList
of something transparently. Primitive arrays would require you to keep track of some kind of offset - limit. ByteBuffer
s have similar options as I heard.
Edit: If you are in charge of the useful method, you could just define it with bounds (as done in many array related methods in java itself:
doUseful(byte[] arr, int start, int len) {
// implementation here
}
doUseful(byte[] arr) {
doUseful(arr, 0, arr.length);
}
It's not clear, however, if you work on the array elements themselves, e.g. you compute something and write back the result?
How about
sub foo()
dim r As Range, rows As Long, i As Long
Set r = ActiveSheet.Range("A1:Z50")
rows = r.rows.Count
For i = rows To 1 Step (-1)
If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
Next
End Sub
Try this
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Range("A" & i & ":" & "Z" & i)
Else
Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
IF you want to delete the entire row then use this code
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Rows(i)
Else
Set DelRange = Union(DelRange, Rows(i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
If you read the help file for ?boxplot
, you'll see there is a names=
parameter.
boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))
I was having problems getting a commandField Delete button to honor the 'return false' response to when a user clicked cancel on the 'Are you sure' pop-up that one gets with using the javascript confirm() function. I didn't want to change it to a template field.
The problem, as I see it, was that these commandField Buttons already have some Javascript associated with them to perform the postback. No amount of simply appending the confirm() function was effective.
Here's how I solved it:
Using JQuery, I first found each delete button on the page (there are several), then manipulated the button's associated Javascript based on whether the visitor agreed or canceled the confirming pop-up.
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('input[type="button"]').each(function() {
if ($(this).val() == "Delete") {
var curEvent = $(this).attr('onclick');
var newContent = "if(affirmDelete() == true){" + curEvent + "};"
$(this).attr('onclick',newContent);
}
});
}
function affirmDelete() {
return confirm('Are you sure?');
}
</script>
This is a good example of the maven-ear-plugin part.
You can also check the maven archetypes that are available as an example. If you just runt mvn archetype:generate you'll get a list of available archetypes. One of them is
maven-archetype-j2ee-simple
Little Edit
Try adding
return new JavascriptResult() { Script = "alert('Successfully registered');" };
in place of
return RedirectToAction("Index");
Try using the type
attribute selector to find buttons (maybe this'll fix it too):
input[type=button]
{
background-color: #E3E1B8;
}
input[type=button]:hover
{
background-color: #46000D
}
Here a good implementation example of using schemas with SQL Server. We had several ms-access applications. We wanted to convert those to a ASP.NET App portal. Every ms-access application is written as an App for that portal. Every ms-access application has its own database tables. Some of those are related, we put those in the common dbo schema of SQL Server. The rest gets its own schemas. That way if we want to know what tables belong to an App on the ASP.NET app portal that can easily be navigated, visualised and maintained.
As to what cdstamper suggested instead of the table view, adding below lines in the cell's layoutSubview method works for me.
- (void)layoutSubviews
{
[super layoutSubviews];
if ([self respondsToSelector:@selector(setSeparatorInset:)])
[self setSeparatorInset:UIEdgeInsetsZero];
if ([self respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)])
{
[self setPreservesSuperviewLayoutMargins:NO];;
}
if ([self respondsToSelector:@selector(setLayoutMargins:)])
{
[self setLayoutMargins:UIEdgeInsetsZero];
}
}
The message:
Waiting for available socket...
is shown, because you've reached a limit on the ssl_socket_pool either per Host, Proxy or Group.
Here are the maximum number of HTTP connections which you can make with a Chrome browser:
Maximum per Host: 6 connections.
This is likely hardcoded in the source code of the web browser, so you can't change it.
Total 256 HTTP connections pooled per browser.
Source: Enterprise networking for Chrome devices
The above limits can be checked or flushed at chrome://net-internals/#sockets
(or in real-time at chrome://net-internals/#events&q=type:SOCKET%20is:active
).
Your issue with audio can be related to Chrome bug 162627 where HTML5 audio fails to load and it hits max simultaneous connections per server:proxy. This is still active issue at the time of writing (2016).
Much older issue related to HTML5 video request stay pending, then it's probably related to Issue #234779 which has been fixed 2014. And related to SPDY which can be found in Issue 324653: SPDY issue: waiting for available sockets, but this was already fixed in 2014, so probably it's not related.
Other related issue now marked as duplicate can be found in Issue 401845: Failure to preload audio metadata. Loaded only 6 of 10+ which was related to the problem with the media player code leaving a bunch of paused requests hanging around.
This also may be related to some Chrome adware or antivirus extensions using your sockets in the backgrounds (like Sophos or Kaspersky), so check for Network activity in DevTools.
Based on solution You've already found How to apply CSS to iframe?:
var cssLink = document.createElement("link")
cssLink.href = "file://path/to/style.css";
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
frames['iframe'].document.body.appendChild(cssLink);
or more jqueryish (from Append a stylesheet to an iframe with jQuery):
var $head = $("iframe").contents().find("head");
$head.append($("<link/>",
{ rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));
as for security issues: Disabling same-origin policy in Safari
You need to use an SSH key to login to your instance.
The GCE documentation explains the process here.
I had a similar issue.
Yesterday, I submitted an app build (1.03) using Xcode, it was around 6 PM and this morning it was still "Processing", in fact it is still "Processing".
This morning around 10:30 AM I submitted a second build (1.04) using Xcode but that one also took too much time to change its status, so I submitted a third build (1.05) using Application Loader around noon, application loader gave me a warning about the app being too large to validate its API usage (the build is around 12.5 MB), it was just a warning so I submitted it and I'm still waiting to for it to change status (2:16 PM).
Of course, each time I bumped up the Build number. All the builds had Enable Bitcode set to NO.
UPDATE (1:52 PM):
The second build (1.0.4) just became available for TestFlight.
UPDATE (4:43 PM):
The third build (1.0.5), the one submitted with Application Loader just became available for TestFlight.
My conclusion is that their servers are slower than before... maybe the volume of apps that are being processed has increased and the load of their systems is higher because there are new things to check for (bitcode, watch os stuff, etc).
As @KaptajnKold had answered
var x = [ 'p0', 'p1', 'p2' ];
call_me.apply(this, x);
And you don't need to define every parameters for call_me function either.
You can just use arguments
function call_me () {
// arguments is a array consisting of params.
// arguments[0] == 'p0',
// arguments[1] == 'p1',
// arguments[2] == 'p2'
}
As Alex Gray points out in a comment above, "all of the corresponding IDs are actually on the extensions page within the browser".
However, you must click the Developer Mode checkbox at top of Extensions page to see them.
.Click() - Perform only click operation as like mouse click.
.Submit() - Perform Enter operation as like keyboard Enter event.
For Example. Consider a login page where it contains username and password and submit button.
On filling password if we want to login without clicking login button. we need to user .submit button on password where .click() operation does not work.[to login into application]
Brif.
driver.get("https:// anyURL");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.id("txtUserId")).sendKeys("[email protected]");
WebElement text = driver.findElement(By.id("txtPassword")); text.sendKeys("password");
Thread.sleep(1000);
text.click(); //This will not work - it will on perform click operation not submit operation
text.submit(); //This will perform submit operation has enter key
The ConverterParameter
property can not be bound because it is not a dependency property.
Since Binding
is not derived from DependencyObject
none of its properties can be dependency properties. As a consequence, a Binding can never be the target object of another Binding.
There is however an alternative solution. You could use a MultiBinding
with a multi-value converter instead of a normal Binding:
<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
<Setter.Value>
<MultiBinding Converter="{StaticResource AccessLevelToVisibilityConverter}">
<Binding Path="Tag" RelativeSource="{RelativeSource Mode=FindAncestor,
AncestorType=UserControl}"/>
<Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
The multi-value converter gets an array of source values as input:
public class AccessLevelToVisibilityConverter : IMultiValueConverter
{
public object Convert(
object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.All(v => (v is bool && (bool)v))
? Visibility.Visible
: Visibility.Hidden;
}
public object[] ConvertBack(
object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
The error "only length-1 arrays can be converted to Python scalars" is raised when the function expects a single value but you pass an array instead.
If you look at the call signature of np.int
, you'll see that it accepts a single value, not an array. In general, if you want to apply a function that accepts a single element to every element in an array, you can use np.vectorize
:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.int(x)
f2 = np.vectorize(f)
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f2(x))
plt.show()
You can skip the definition of f(x) and just pass np.int to the vectorize function: f2 = np.vectorize(np.int)
.
Note that np.vectorize
is just a convenience function and basically a for loop. That will be inefficient over large arrays. Whenever you have the possibility, use truly vectorized functions or methods (like astype(int)
as @FFT suggests).
Although it's a long time after this question is being asked since I was searching so much for the same problem and couldn't find the extant solutions helpful, I write what fixed my trouble for anyone with the same issue:
The point is, Jupyter should be installed in your virtual environment, meaning, after activating the tensorflow
environment, run the following in the command prompt (in tensorflow
virtual environment):
conda install jupyter
jupyter notebook
and then the jupyter will pop up.
With Django version 1.3, the class based approach is:
from django.conf.urls.defaults import patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns('',
url(r'^some-url/$', RedirectView.as_view(url='/redirect-url/'), name='some_redirect'),
)
This example lives in in urls.py
The hack is recursive. It is like IE itself uses the component that is used by many other processes which want "web component". Hence in registry we add IEXPLORE.exe
. In effect it is a recursive hack.
You could move the common parts to another configuration file and include
from both server contexts. This should work:
server {
listen 80;
server_name server1.example;
...
include /etc/nginx/include.d/your-common-stuff.conf;
}
server {
listen 80;
server_name another-one.example;
...
include /etc/nginx/include.d/your-common-stuff.conf;
}
Edit: Here's an example that's actually copied from my running server. I configure my basic server settings in /etc/nginx/sites-enabled
(normal stuff for nginx on Ubuntu/Debian). For example, my main server bunkus.org
's configuration file is /etc/nginx/sites-enabled
and it looks like this:
server {
listen 80 default_server;
listen [2a01:4f8:120:3105::101:1]:80 default_server;
include /etc/nginx/include.d/all-common;
include /etc/nginx/include.d/bunkus.org-common;
include /etc/nginx/include.d/bunkus.org-80;
}
server {
listen 443 default_server;
listen [2a01:4f8:120:3105::101:1]:443 default_server;
include /etc/nginx/include.d/all-common;
include /etc/nginx/include.d/ssl-common;
include /etc/nginx/include.d/bunkus.org-common;
include /etc/nginx/include.d/bunkus.org-443;
}
As an example here's the /etc/nginx/include.d/all-common
file that's included from both server
contexts:
index index.html index.htm index.php .dirindex.php;
try_files $uri $uri/ =404;
location ~ /\.ht {
deny all;
}
location = /favicon.ico {
log_not_found off;
access_log off;
}
location ~ /(README|ChangeLog)$ {
types { }
default_type text/plain;
}
In HTML
<div style="overflow: hidden;">
in CSS
overflow: hidden;
you can also end scrolling for x or y separately
overflow-y: hidden; /* Hide vertical scrollbar */
overflow-x: hidden; /* Hide horizontal scrollbar */
Starting with the 2.6 release, another way to do this is to compare the field to an empty array:
ME.find({pictures: {$gt: []}})
Testing it out in the shell:
> db.ME.insert([
{pictures: [1,2,3]},
{pictures: []},
{pictures: ['']},
{pictures: [0]},
{pictures: 1},
{foobar: 1}
])
> db.ME.find({pictures: {$gt: []}})
{ "_id": ObjectId("54d4d9ff96340090b6c1c4a7"), "pictures": [ 1, 2, 3 ] }
{ "_id": ObjectId("54d4d9ff96340090b6c1c4a9"), "pictures": [ "" ] }
{ "_id": ObjectId("54d4d9ff96340090b6c1c4aa"), "pictures": [ 0 ] }
So it properly includes the docs where pictures
has at least one array element, and excludes the docs where pictures
is either an empty array, not an array, or missing.
sortedWith
+ compareBy
(taking a vararg of lambdas) do the trick:
val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))
You can also use the somewhat more succinct callable reference syntax:
val sortedList = list.sortedWith(compareBy(Person::age, Person::name))
For me just ${workspace}
worked without even initializing the variable 'workspace.'
Use the default version:
Collections.sort(myarrayList);
Of course this requires that your Elements implement Comparable
, but the same holds true for the version you mentioned.
BTW: you should use generics in your code, that way you get compile-time errors if your class doesn't implement Comparable. And compile-time errors are much better than the runtime errors you'll get otherwise.
List<MyClass> list = new ArrayList<MyClass>();
// now fill up the list
// compile error here unless MyClass implements Comparable
Collections.sort(list);
It sounds as if the only problem here is that the default editor that is launched is vi
or vim
, with which you're not familiar. (As quick tip, to exit that editor without saving changes, hit Esc a few times and then type :, q, ! and Enter.)
There are several ways to set up your default editor, and you haven't indicated which operating system you're using, so it's difficult to recommend one in particular. I'd suggest using:
git config --global core.editor "name-of-your-editor"
... which sets a global git preference for a particular editor. Alternatively you can set the $EDITOR
environment variable.
Like this:
{{ form_widget(form.description, { 'attr': {'class': 'form-control', 'rows': '5', 'style': 'resize:none;'} }) }}
Lodash omit
let source = //{a: 1, b: 2, c: 3, ..., z:26}
let copySansProperty = _.omit(source, 'b');
// {a: 1, c: 3, ..., z:26}
With the latest aws-cli python command line tools, to recursively delete all the files under a folder in a bucket is just:
aws s3 rm --recursive s3://your_bucket_name/foo/
Or delete everything under the bucket:
aws s3 rm --recursive s3://your_bucket_name
If what you want is to actually delete the bucket, there is one-step shortcut:
aws s3 rb --force s3://your_bucket_name
which will remove the contents in that bucket recursively then delete the bucket.
Note: the s3://
protocol prefix is required for these commands to work
First, avoid all type comparisons. They're very, very rarely necessary. Sometimes, they help to check parameter types in a function -- even that's rare. Wrong type data will raise an exception, and that's all you'll ever need.
All of the basic conversion functions will map as equal to the type function.
type(9) is int
type(2.5) is float
type('x') is str
type(u'x') is unicode
type(2+3j) is complex
There are a few other cases.
isinstance( 'x', basestring )
isinstance( u'u', basestring )
isinstance( 9, int )
isinstance( 2.5, float )
isinstance( (2+3j), complex )
None, BTW, never needs any of this kind of type checking. None is the only instance of NoneType. The None object is a Singleton. Just check for None
variable is None
BTW, do not use the above in general. Use ordinary exceptions and Python's own natural polymorphism.
The core team responsible for Postgres is gradually phasing out OIDs.
The use of OID as an optional system column on your tables is now removed from Postgres 12. You can no longer use:
CREATE TABLE … WITH OIDS
commanddefault_with_oids (boolean)
compatibility settingThe data type OID
remains in Postgres 12. You can explicitly create a column of the type OID
.
After migrating to Postgres 12, any optionally-defined system column oid
will no longer be invisible by default. Performing a SELECT *
will now include this column. Note that this extra “surprise” column may break naïvely written SQL code.
You can use the curses.h
library in linux as mentioned in the other answer.
You can install it in Ubuntu by:
sudo apt-get update
sudo apt-get install ncurses-dev
I took the installation part from here.
What is Predicate Delegate?
1) Predicate is a feature that returns true or false.This concept has come in .net 2.0 framework.
2) It is being used with lambda expression (=>). It takes generic type as an argument.
3) It allows a predicate function to be defined and passed as a parameter to another function.
4) It is a special case of a Func
, in that it takes only a single parameter and always returns a bool.
In C# namespace:
namespace System
{
public delegate bool Predicate<in T>(T obj);
}
It is defined in the System namespace.
Where should we use Predicate Delegate?
We should use Predicate Delegate in the following cases:
1) For searching items in a generic collection. e.g.
var employeeDetails = employees.Where(o=>o.employeeId == 1237).FirstOrDefault();
2) Basic example that shortens the code and returns true or false:
Predicate<int> isValueOne = x => x == 1;
now, Call above predicate:
Console.WriteLine(isValueOne.Invoke(1)); // -- returns true.
3) An anonymous method can also be assigned to a Predicate delegate type as below:
Predicate<string> isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
bool result = isUpper("Hello Chap!!");
Any best practices about predicates?
Use Func, Lambda Expressions and Delegates instead of Predicates.
If you want to disable particular date(s) in jquery datepicker then here is the simple demo for you.
<script type="text/javascript">
var arrDisabledDates = {};
arrDisabledDates[new Date("08/28/2017")] = new Date("08/28/2017");
arrDisabledDates[new Date("12/23/2017")] = new Date("12/23/2017");
$(".datepicker").datepicker({
dateFormat: "dd/mm/yy",
beforeShowDay: function (date) {
var day = date.getDay(),
bDisable = arrDisabledDates[date];
if (bDisable)
return [false, "", ""]
}
});
</script>
You actually don't need a UIScrollView to do this. I used this code and it works for me:
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField==_myTextField)
{
[self keyBoardAppeared];
}
return true;
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
if (textField==_myTextField)
{
[self keyBoardDisappeared];
}
}
-(void) keyBoardAppeared
{
CGRect frame = self.view.frame;
[UIView animateWithDuration:0.3
delay:0
options: UIViewAnimationCurveEaseOut
animations:^{
self.view.frame = CGRectMake(frame.origin.x, frame.origin.y-215, frame.size.width, frame.size.height);
}
completion:^(BOOL finished){
}];
}
-(void) keyBoardDisappeared
{
CGRect frame = self.view.frame;
[UIView animateWithDuration:0.3
delay:0
options: UIViewAnimationCurveEaseOut
animations:^{
self.view.frame = CGRectMake(frame.origin.x, frame.origin.y+215, frame.size.width, frame.size.height);
}
completion:^(BOOL finished){
}];
}
It means another user is accessing the database. Simply restart PostgreSQL. This command will do the trick
root@kalilinux:~#sudo service postgresql restart
Then try dropping the database:
postgres=# drop database test_database;
This will do the trick.
To make the answer simple here is a program that reads integers from the file and sorting them
f = open("input.txt", 'r')
nums = f.readlines()
nums = [int(i) for i in nums]
After reading each line of the file converting each string to a digit
nums.sort()
Sorting the numbers
f.close()
f = open("input.txt", 'w')
for num in nums:
f.write("%d\n" %num)
f.close()
Writing them back As easy as that, Hope this helps
It's easy (For Chorme only)
.woff
format) > open link in new tab (this should download the font in .woff
formatIt does includes boundaries.
declare @startDate date = cast('15-NOV-2016' as date)
declare @endDate date = cast('30-NOV-2016' as date)
create table #test (c1 date)
insert into #test values(cast('15-NOV-2016' as date))
insert into #test values(cast('20-NOV-2016' as date))
insert into #test values(cast('30-NOV-2016' as date))
select * from #test where c1 between @startDate and @endDate
drop table #test
RESULT c1
2016-11-15
2016-11-20
2016-11-30
declare @r1 int = 10
declare @r2 int = 15
create table #test1 (c1 int)
insert into #test1 values(10)
insert into #test1 values(15)
insert into #test1 values(11)
select * from #test1 where c1 between @r1 and @r2
drop table #test1
RESULT c1
10
11
15
There's an easy way to do that. Very easy. Since I noticed that
$scope.yourModel = [];
removes all $scope.yourModel array list you can do like this
function deleteAnObjectByKey(objects, key) {
var clonedObjects = Object.assign({}, objects);
for (var x in clonedObjects)
if (clonedObjects.hasOwnProperty(x))
if (clonedObjects[x].id == key)
delete clonedObjects[x];
$scope.yourModel = clonedObjects;
}
The $scope.yourModel will be updated with the clonedObjects.
Hope that helps.
How about
when( method-call ).thenReturn( value1, value2, value3 );
You can put as many arguments as you like in the brackets of thenReturn, provided they're all the correct type. The first value will be returned the first time the method is called, then the second answer, and so on. The last value will be returned repeatedly once all the other values are used up.
As described by Crist Clark.
CLOSE_WAIT means that the local end of the connection has received a FIN from the other end, but the OS is waiting for the program at the local end to actually close its connection.
The problem is your program running on the local machine is not closing the socket. It is not a TCP tuning issue. A connection can (and quite correctly) stay in CLOSE_WAIT forever while the program holds the connection open.
Once the local program closes the socket, the OS can send the FIN to the remote end which transitions you to LAST_ACK while you wait for the ACK of the FIN. Once that is received, the connection is finished and drops from the connection table (if your end is in CLOSE_WAIT you do not end up in the TIME_WAIT state).
The command :hide will hide the currently focused window. I think this is the functionality you are looking for.
In order to navigate between windows type Ctrl+w followed by a navigation key (h,j,k,l, or arrow keys)
For more information run :help window
and :help hide
in vim.
isset() only checks if a variable is set.. Has got nothing to do with size or what the array contains
//animated show/hide
function showHide(id) {
var hidden= ("none" == $( "#".concat(id) ).css("display"));
if(hidden){
$( "#".concat(id) ).show(1000);
}else{
$("#".concat(id) ).hide(1000);
}
}
I just looked into my code. In one application, I just add the controls, but without specifying the index, and when done, I just loop through the row styles and set the size type to AutoSize. So just adding them without specifying the indices seems to add the rows as intended (provided the GrowStyle is set to AddRows).
In another application, I clear the controls and set the RowCount property to the needed value. This does not add the RowStyles. Then I add my controls, this time specifying the indices, and add a new RowStyle (RowStyles.Add(new RowStyle(...)
) and this also works.
So, pick one of these methods, they both work. I remember the headaches the table layout panel caused me.
In the shell, you can't execute more than one statement at a time:
>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement
You need to execute them one by one:
>>> x = 5
>>> y = 6
>>>
When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.
This can be achieved by putting padding between the columns using CSS. You can either add padding to the left of all columns except the first, or add padding to the right of all columns except the last. You should avoid adding padding to the right of the last column or to the left of the first as this will insert redundant white space. You should also avoid being too prescriptive with classes to specify which columns should have the additional padding as this will make maintenance harder if you later add a new column.
The 'lobotomised owl selector' allows you to select all siblings, regardless of if they are a th
, td
or something else.
tr > * + * {
padding-left: 4em;
}
_x000D_
<table>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</tbody>
</table>
_x000D_
Ok, here is a better way to deal with Currency formats, delete-backward keystroke. The code is based on @androidcurious' code above... But, deals with some problems related to backwards-deletion and some parse exceptions: http://miguelt.blogspot.ca/2013/01/textwatcher-for-currency-masksformatting.html [UPDATE] The previous solution had some problems... This is a better solutoin: http://miguelt.blogspot.ca/2013/02/update-textwatcher-for-currency.html And... here are the details:
This approach is better since it uses the conventional Android mechanisms. The idea is to format values after the user exists the View.
Define an InputFilter to restrict the numeric values – this is required in most cases because the screen is not large enough to accommodate long EditText views. This can be a static inner class or just another plain class:
/** Numeric range Filter. */
class NumericRangeFilter implements InputFilter {
/** Maximum value. */
private final double maximum;
/** Minimum value. */
private final double minimum;
/** Creates a new filter between 0.00 and 999,999.99. */
NumericRangeFilter() {
this(0.00, 999999.99);
}
/** Creates a new filter.
* @param p_min Minimum value.
* @param p_max Maximum value.
*/
NumericRangeFilter(double p_min, double p_max) {
maximum = p_max;
minimum = p_min;
}
@Override
public CharSequence filter(
CharSequence p_source, int p_start,
int p_end, Spanned p_dest, int p_dstart, int p_dend
) {
try {
String v_valueStr = p_dest.toString().concat(p_source.toString());
double v_value = Double.parseDouble(v_valueStr);
if (v_value<=maximum && v_value>=minimum) {
// Returning null will make the EditText to accept more values.
return null;
}
} catch (NumberFormatException p_ex) {
// do nothing
}
// Value is out of range - return empty string.
return "";
}
}
Define a class (inner static or just a class) that will implement View.OnFocusChangeListener. Note that I'm using an Utils class - the implementation can be found at "Amounts, Taxes".
/** Used to format the amount views. */
class AmountOnFocusChangeListener implements View.OnFocusChangeListener {
@Override
public void onFocusChange(View p_view, boolean p_hasFocus) {
// This listener will be attached to any view containing amounts.
EditText v_amountView = (EditText)p_view;
if (p_hasFocus) {
// v_value is using a currency mask - transfor over to cents.
String v_value = v_amountView.getText().toString();
int v_cents = Utils.parseAmountToCents(v_value);
// Now, format cents to an amount (without currency mask)
v_value = Utils.formatCentsToAmount(v_cents);
v_amountView.setText(v_value);
// Select all so the user can overwrite the entire amount in one shot.
v_amountView.selectAll();
} else {
// v_value is not using a currency mask - transfor over to cents.
String v_value = v_amountView.getText().toString();
int v_cents = Utils.parseAmountToCents(v_value);
// Now, format cents to an amount (with currency mask)
v_value = Utils.formatCentsToCurrency(v_cents);
v_amountView.setText(v_value);
}
}
}
This class will remove the currency format when editing - relying on standard mechanisms. When the user exits, the currency format is re-applied.
It's better to define some static variables to minimize the number of instances:
static final InputFilter[] FILTERS = new InputFilter[] {new NumericRangeFilter()};
static final View.OnFocusChangeListener ON_FOCUS = new AmountOnFocusChangeListener();
Finally, within the onCreateView(...):
EditText mAmountView = ....
mAmountView.setFilters(FILTERS);
mAmountView.setOnFocusChangeListener(ON_FOCUS);
You can reuse FILTERS and ON_FOCUS on any number of EditText views.
Here is the Utils class:
public class Utils {
private static final NumberFormat FORMAT_CURRENCY = NumberFormat.getCurrencyInstance();
/** Parses an amount into cents.
* @param p_value Amount formatted using the default currency.
* @return Value as cents.
*/
public static int parseAmountToCents(String p_value) {
try {
Number v_value = FORMAT_CURRENCY.parse(p_value);
BigDecimal v_bigDec = new BigDecimal(v_value.doubleValue());
v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
return v_bigDec.movePointRight(2).intValue();
} catch (ParseException p_ex) {
try {
// p_value doesn't have a currency format.
BigDecimal v_bigDec = new BigDecimal(p_value);
v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
return v_bigDec.movePointRight(2).intValue();
} catch (NumberFormatException p_ex1) {
return -1;
}
}
}
/** Formats cents into a valid amount using the default currency.
* @param p_value Value as cents
* @return Amount formatted using a currency.
*/
public static String formatCentsToAmount(int p_value) {
BigDecimal v_bigDec = new BigDecimal(p_value);
v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
v_bigDec = v_bigDec.movePointLeft(2);
String v_currency = FORMAT_CURRENCY.format(v_bigDec.doubleValue());
return v_currency.replace(FORMAT_CURRENCY.getCurrency().getSymbol(), "").replace(",", "");
}
/** Formats cents into a valid amount using the default currency.
* @param p_value Value as cents
* @return Amount formatted using a currency.
*/
public static String formatCentsToCurrency(int p_value) {
BigDecimal v_bigDec = new BigDecimal(p_value);
v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
v_bigDec = v_bigDec.movePointLeft(2);
return FORMAT_CURRENCY.format(v_bigDec.doubleValue());
}
}
You are exceeding the length of int datatype. You can use UNSIGNED attribute to support that value.
SIGNED INT can support till 2147483647 and with UNSIGNED INT allows double than this. After this you still want to save data than use CHAR or VARCHAR with length 10
Converting to an Index, you can use get_loc
In [1]: myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
In [3]: Index(myseries).get_loc(7)
Out[3]: 3
In [4]: Index(myseries).get_loc(10)
KeyError: 10
Duplicate handling
In [5]: Index([1,1,2,2,3,4]).get_loc(2)
Out[5]: slice(2, 4, None)
Will return a boolean array if non-contiguous returns
In [6]: Index([1,1,2,1,3,2,4]).get_loc(2)
Out[6]: array([False, False, True, False, False, True, False], dtype=bool)
Uses a hashtable internally, so fast
In [7]: s = Series(randint(0,10,10000))
In [9]: %timeit s[s == 5]
1000 loops, best of 3: 203 µs per loop
In [12]: i = Index(s)
In [13]: %timeit i.get_loc(5)
1000 loops, best of 3: 226 µs per loop
As Viktor points out, there is a one-time creation overhead to creating an index (its incurred when you actually DO something with the index, e.g. the is_unique
)
In [2]: s = Series(randint(0,10,10000))
In [3]: %timeit Index(s)
100000 loops, best of 3: 9.6 µs per loop
In [4]: %timeit Index(s).is_unique
10000 loops, best of 3: 140 µs per loop
The Bootstrap team seems to have removed it. See here: https://github.com/twbs/bootstrap/issues/8922 . @Skelly's answer involves custom css which I didn't want to do so I used the grid system and nav-pills. It worked fine and looked great. The code looks like so:
<div class="row">
<!-- Navigation Buttons -->
<div class="col-md-3">
<ul class="nav nav-pills nav-stacked" id="myTabs">
<li class="active"><a href="#home" data-toggle="pill">Home</a></li>
<li><a href="#profile" data-toggle="pill">Profile</a></li>
<li><a href="#messages" data-toggle="pill">Messages</a></li>
</ul>
</div>
<!-- Content -->
<div class="col-md-9">
<div class="tab-content">
<div class="tab-pane active" id="home">Home</div>
<div class="tab-pane" id="profile">Profile</div>
<div class="tab-pane" id="messages">Messages</div>
</div>
</div>
</div>
You can see this in action here: http://bootply.com/81948
[Update]
@SeanK gives the option of not having to enable the nav-pills through Javascript and instead using data-toggle="pill"
. Check it out here: http://bootply.com/96067. Thanks Sean.
Let me know if this works. Way to detect an Apple device (Mac computers, iPhones, etc.) with help from StackOverflow.com:
What is the list of possible values for navigator.platform as of today?
var deviceDetect = navigator.platform;
var appleDevicesArr = ['MacIntel', 'MacPPC', 'Mac68K', 'Macintosh', 'iPhone',
'iPod', 'iPad', 'iPhone Simulator', 'iPod Simulator', 'iPad Simulator', 'Pike
v7.6 release 92', 'Pike v7.8 release 517'];
// If on Apple device
if(appleDevicesArr.includes(deviceDetect)) {
// Execute code
}
// If NOT on Apple device
else {
// Execute code
}
To change the font size of the <input />
tag in HTML, use this:
<input style="font-size:20px" type="text" value="" />
It will create a text input box and the text inside the text box will be 20 pixels.
To delete the last element of the lists, you could use:
def deleteLast(self):
if self.Ans:
del self.Ans[-1]
if self.masses:
del self.masses[-1]
With ES6 you can write this:
const countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
const $ul = $('<ul>', { class: "mylist" }).append(
countries.map(country =>
$("<li>").append($("<a>").text(country))
)
);
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
You should look into XPath. Once you start using it, you'll find its a lot more efficient and easier to code than iterating through lists. It also lets you directly get the things you want.
Then the code would be something similar to
string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;
Note that XPath 3.0 became a W3C Recommendation on April 8, 2014.
Try BeanComparator from Apache Commons.
import org.apache.commons.beanutils.BeanComparator;
BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);
I recently saw this one-liner:
def foo(name: str, opts: dict=None) -> str:
opts = {} if not opts else opts
pass
Strings are immutable, meaning their contents cannot change. When you call replace(this,that)
you end up with a totally new String. If you want to keep this new copy, you need to assign it to a variable. You can overwrite the old reference (a la sentence = sentence.replace(this,that)
or a new reference as seen below:
public class Test{
public static void main(String[] args) {
String sentence = "Define, Measure, Analyze, Design and Verify";
String replaced = sentence.replace("and", "");
System.out.println(replaced);
}
}
As an aside, note that I've removed the contains()
check, as it is an unnecessary call here. If it didn't contain it, the replace will just fail to make any replacements. You'd only want that contains method if what you're replacing was different than the actual condition you're checking.
MySQL doesn't reduce the size of ibdata1. Ever. Even if you use optimize table
to free the space used from deleted records, it will reuse it later.
An alternative is to configure the server to use innodb_file_per_table
, but this will require a backup, drop database and restore. The positive side is that the .ibd file for the table is reduced after an optimize table
.
all above fix may not work in android studio .if you are using ANDROID STUDIO...... use this fix
add
xmlns:compat="http://schemas.android.com/tools"
in menu tag instead of
xmlns:compat="http://schemas.android.com/apk/res-auto"
in menu tag.
I would like to give another example where groupby without sort is not working. Adapted from example by James Sulak
from itertools import groupby
things = [("vehicle", "bear"), ("animal", "duck"), ("animal", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
for key, group in groupby(things, lambda x: x[0]):
for thing in group:
print "A %s is a %s." % (thing[1], key)
print " "
output is
A bear is a vehicle.
A duck is a animal.
A cactus is a animal.
A speed boat is a vehicle.
A school bus is a vehicle.
there are two groups with vehicule, whereas one could expect only one group
This may work:
nvm install NEW_VERSION --reinstall-packages-from=OLD_VERSION
For example:
nvm install 6.7 --reinstall-packages-from=6.4
then, if you want, you can delete your previous version with:
nvm uninstall OLD_VERSION
Where, in your case, NEW_VERSION = 5.4 OLD_VERSION = 5.0
Alternatively, try:
nvm install stable --reinstall-packages-from=current
Here is a version that will handle multiple files drag and dropped from windows. Based on the above works by
Christian Lemer
plang
ScottF
Open Notepad, create a file called XlsToCsv.vbs and paste this in:
'* Usage: Drop .xl* files on me to export each sheet as CSV
'* Global Settings and Variables
Dim gSkip
Set args = Wscript.Arguments
For Each sFilename In args
iErr = ExportExcelFileToCSV(sFilename)
' 0 for normal success
' 404 for file not found
' 10 for file skipped (or user abort if script returns 10)
Next
WScript.Quit(0)
Function ExportExcelFileToCSV(sFilename)
'* Settings
Dim oExcel, oFSO, oExcelFile
Set oExcel = CreateObject("Excel.Application")
Set oFSO = CreateObject("Scripting.FileSystemObject")
iCSV_Format = 6
'* Set Up
sExtension = oFSO.GetExtensionName(sFilename)
if sExtension = "" then
ExportExcelFileToCSV = 404
Exit Function
end if
sTest = Mid(sExtension,1,2) '* first 2 letters of the extension, vb's missing a Like operator
if not (sTest = "xl") then
if (PromptForSkip(sFilename,oExcel)) then
ExportExcelFileToCSV = 10
Exit Function
end if
End If
sAbsoluteSource = oFSO.GetAbsolutePathName(sFilename)
sAbsoluteDestination = Replace(sAbsoluteSource,sExtension,"{sheet}.csv")
'* Do Work
Set oExcelFile = oExcel.Workbooks.Open(sAbsoluteSource)
For Each oSheet in oExcelFile.Sheets
sThisDestination = Replace(sAbsoluteDestination,"{sheet}",oSheet.Name)
oExcelFile.Sheets(oSheet.Name).Select
oExcelFile.SaveAs sThisDestination, iCSV_Format
Next
'* Take Down
oExcelFile.Close False
oExcel.Quit
ExportExcelFileToCSV = 0
Exit Function
End Function
Function PromptForSkip(sFilename,oExcel)
if not (VarType(gSkip) = vbEmpty) then
PromptForSkip = gSkip
Exit Function
end if
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
sPrompt = vbCRLF & _
"A filename was received that doesn't appear to be an Excel Document." & vbCRLF & _
"Do you want to skip this and all other unrecognized files? (Will only prompt this once)" & vbCRLF & _
"" & vbCRLF & _
"Yes - Will skip all further files that don't have a .xl* extension" & vbCRLF & _
"No - Will pass the file to excel regardless of extension" & vbCRLF & _
"Cancel - Abort any further conversions and exit this script" & vbCRLF & _
"" & vbCRLF & _
"The unrecognized file was:" & vbCRLF & _
sFilename & vbCRLF & _
"" & vbCRLF & _
"The path returned by the system was:" & vbCRLF & _
oFSO.GetAbsolutePathName(sFilename) & vbCRLF
sTitle = "Unrecognized File Type Encountered"
sResponse = MsgBox (sPrompt,vbYesNoCancel,sTitle)
Select Case sResponse
Case vbYes
gSkip = True
Case vbNo
gSkip = False
Case vbCancel
oExcel.Quit
WScript.Quit(10) '* 10 Is the error code I use to indicate there was a user abort (1 because wasn't successful, + 0 because the user chose to exit)
End Select
PromptForSkip = gSkip
Exit Function
End Function
You can handle the AppDomain.UnhandledException
event
EDIT: actually, this event is probably more adequate: Application.DispatcherUnhandledException
If you want to have control over this you need to implement the [IEquatable interface][1]
[1]: http://This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable.Equals method for T (the type of values in the list).
var Data=[{"id": "name2", "label": "Quantity"}]
Pass the string variable into Json parse :
Objdata= Json.parse(Data);
The prompt command will echo text to the output:
prompt A useful comment.
select(*) from TableA;
Will be displayed as:
SQL> A useful comment.
SQL>
COUNT(*)
----------
0
A thread dump is a dump of the stacks of all live threads. Thus useful for analysing what an app is up to at some point in time, and if done at intervals handy in diagnosing some kinds of 'execution' problems (e.g. thread deadlock).
A heap dump is a dump of the state of the Java heap memory. Thus useful for analysing what use of memory an app is making at some point in time so handy in diagnosing some memory issues, and if done at intervals handy in diagnosing memory leaks.
This is what they are in 'raw' terms, and could be provided in many ways. In general used to describe dumped files from JVMs and app servers, and in this form they are a low level tool. Useful if for some reason you can't get anything else, but you will find life easier using decent profiling tool to get similar but easier to dissect info.
With respect to WebSphere a javacore file is a thread dump, albeit with a lot of other info such as locks and loaded classes and some limited memory usage info, and a PHD file is a heap dump.
If you want to read a javacore file you can do so by hand, but there is an IBM tool (BM Thread and Monitor Dump Analyzer) which makes it simpler. If you want to read a heap dump file you need one of many IBM tools: MDD4J or Heap Analyzer.
If you already have the data "for (Parcelable currentHeadline : allHeadlines)," then why are you doing that in a separate thread?
You should poll the data in a separate thread, and when it's finished gathering it, then call your populateTables method on the UI thread:
private void populateTable() {
runOnUiThread(new Runnable(){
public void run() {
//If there are stories, add them to the table
for (Parcelable currentHeadline : allHeadlines) {
addHeadlineToTable(currentHeadline);
}
try {
dialog.dismiss();
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
}
});
}
You could descendingly order the tabele by id and limit the number of results to one:
SELECT id FROM tablename ORDER BY id DESC LIMIT 1
BUT: ORDER BY
rearranges the entire table for this request. So if you have a lot of data and you need to repeat this operation several times, I would not recommend this solution.
For those who like boost:
boost::filesystem::path mySourcePath("foo.bar");
boost::filesystem::path myTargetPath("bar.foo");
// Variant 1: Overwrite existing
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::overwrite_if_exists);
// Variant 2: Fail if exists
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::fail_if_exists);
Note that boost::filesystem::path is also available as wpath for Unicode. And that you could also use
using namespace boost::filesystem
if you do not like those long type names
I think you don't need to update only some specific field. Just update whole data.
@Update query
It is a given query basically. No need to make some new query.
@Dao
interface MemoDao {
@Insert
suspend fun insert(memo: Memo)
@Delete
suspend fun delete(memo: Memo)
@Update
suspend fun update(memo: Memo)
}
Memo.class
@Entity
data class Memo (
@PrimaryKey(autoGenerate = true) val id: Int,
@ColumnInfo(name = "title") val title: String?,
@ColumnInfo(name = "content") val content: String?,
@ColumnInfo(name = "photo") val photo: List<ByteArray>?
)
Only thing you need to know is 'id'. For instance, if you want to update only 'title', you can reuse 'content' and 'photo' from already inserted data. In real code, use like this
val memo = Memo(id, title, content, byteArrayList)
memoViewModel.update(memo)
in my .net core 3.1 applications I am getting two problem where inner cause was timeout exception. 1, one is i am getting aggregate exception and in it's inner exception was timeout exception 2, other case was Task canceled exception
My solution is
catch (Exception ex)
{
if (ex.InnerException is TimeoutException)
{
ex = ex.InnerException;
}
else if (ex is TaskCanceledException)
{
if ((ex as TaskCanceledException).CancellationToken == null || (ex as TaskCanceledException).CancellationToken.IsCancellationRequested == false)
{
ex = new TimeoutException("Timeout occurred");
}
}
Logger.Fatal(string.Format("Exception at calling {0} :{1}", url, ex.Message), ex);
}
It's not a file association problem since you can launch the application correctly through command line.
The problem is when you double click on an associated file the application starts and runs with the file's path as base execution path. Any relative path will be computed from the file path and everything you try to load will probably be missing.
Nothing happens, even if you surround all of your entry point code with try/catch(Exception) because java s throwing Throwables and not Exceptions: to fix this in your java entry point surround the content of the main method with a try/catch(Throwable) (base class for Exception and Error) and debug.
async
and defer
will download the file during HTML parsing. Both will not interrupt the parser.
The script with async
attribute will be executed once it is downloaded. While the script with defer
attribute will be executed after completing the DOM parsing.
The scripts loaded with async
doesn't guarantee any order. While the scripts loaded with defer
attribute maintains the order in which they appear on the DOM.
Use <script async>
when the script does not rely on anything.
when the script depends use <script defer>
.
Best solution would be add the <script>
at the bottom of the body. There will be no issue with blocking or rendering.
I am fairly new to Docker. I was cleaning up some initial testing mess and was not able to remove a volume either. I had stopped all the running instances, performed a docker rmi -f $(docker image ls -q)
, but still received the Error response from daemon: unable to remove volume: remove uuid: volume is in use
.
I did a docker system prune
and it cleaned up what was needed to remove the last volume:
[0]$ docker system prune
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all dangling images
- all build cache
Are you sure you want to continue? [y/N] y
Deleted Containers:
... about 15 containers UUID's truncated
Total reclaimed space: 2.273MB
[0]$ docker volume ls
DRIVER VOLUME NAME
local uuid
[0]$ docker volume rm uuid
uuid
[0]$
The client and daemon API must both be at least 1.25 to use this command. Use the
docker version
command on the client to check your client and daemon API versions.
Well, the simplest solution regarding to your CSS, imo, is to add spacers into HTML:
<div id='box'>
<div class='item'></div>
<div style='width: 5px;'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
</div>
so, you may control it with inline-style or class names.. sometimes, it's also possible to do spacing with padding.
I'm late but I need to say for those who need an object, using only html, there's a way. In some server side frameworks like PHP you can write the follow code:
<form action="myurl" method="POST" name="myForm">
<p><label for="first_name">First Name:</label>
<input type="text" name="name[first]" id="fname"></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="name[last]" id="lname"></p>
<input value="Submit" type="submit">
</form>
So, we need setup the name of the input as object[property]
for got an object. In the above example, we got a data with the follow JSON:
{
"name": {
"first": "some data",
"last": "some data"
}
}
When passing a struct to another function, it would usually be better to do as Donnell suggested above and pass it by reference instead.
A very good reason for this is that it makes things easier if you want to make changes that will be reflected when you return to the function that created the instance of it.
Here is an example of the simplest way to do this:
#include <stdio.h>
typedef struct student {
int age;
} student;
void addStudent(student *s) {
/* Here we can use the arrow operator (->) to dereference
the pointer and access any of it's members: */
s->age = 10;
}
int main(void) {
student aStudent = {0}; /* create an instance of the student struct */
addStudent(&aStudent); /* pass a pointer to the instance */
printf("%d", aStudent.age);
return 0;
}
In this example, the argument for the addStudent()
function is a pointer to an instance of a student
struct - student *s
. In main()
, we create an instance of the student
struct and then pass a reference to it to our addStudent()
function using the reference operator (&
).
In the addStudent()
function we can make use of the arrow operator (->
) to dereference the pointer, and access any of it's members (functionally equivalent to: (*s).age
).
Any changes that we make in the addStudent()
function will be reflected when we return to main()
, because the pointer gave us a reference to where in the memory the instance of the student
struct is being stored. This is illustrated by the printf()
, which will output "10" in this example.
Had you not passed a reference, you would actually be working with a copy of the struct you passed in to the function, meaning that any changes would not be reflected when you return to main
- unless you implemented a way of passing the new version of the struct back to main or something along those lines!
Although pointers may seem off-putting at first, once you get your head around how they work and why they are so handy they become second nature, and you wonder how you ever coped without them!
clone()
method can be used for this purpose.Found an answer.
var obj = {a: 123, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));
$('<a href="data:' + data + '" download="data.json">download JSON</a>').appendTo('#container');
seems to work fine for me.
** All credit goes to @cowboy-ben-alman, who is the author of the code above **
>>> import pandas as pd
>>> df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]})
>>> df
x y
0 1 4
1 2 5
2 3 6
3 4 7
>>> s = df.ix[:,0]
>>> type(s)
<class 'pandas.core.series.Series'>
>>>
===========================================================================
UPDATE
If you're reading this after June 2017, ix
has been deprecated in pandas 0.20.2, so don't use it. Use loc
or iloc
instead. See comments and other answers to this question.
From what I know when I look at this question here
It said there that "in PHP, there is a distinct difference in Header output. In the examples below I chose to use a different header but for sake of showing the difference between exit() and die() that doesn't matter", and tested (personally)
If you are in Linux, set JAVA_HOME using syntax export JAVA_HOME=<path-to-java>
. Actually it is not only for Maven.
I struggled a bit with the Interface Builder of XCode 7 to set the Presentation Style as @VenuGopalTewari suggested. In this version, there seems to be no Over Current Context
or Over Full Screen
presentation mode for the segue. Thus, to make it work, I set the mode to Default
:
Additionally I set the presentation mode of the modally presented view controller to Over Full Screen
:
As far as I know, apart from setting the command or connection timeouts in the client, there is no way to change timeouts on a query by query basis in the server.
You can indeed change the default 600 seconds using sp_configure
, but these are server scoped.
There is no config file unless you create one yourself. However, the port is a parameter of the listen()
function. For example, to listen on port 8124:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
If you're having problems finding a port that's open, you can go to the command line and type:
netstat -ano
To see a list of all ports in use per adapter.
Just to expand on @splattne's answer a little:
MapPath(string virtualPath)
calls the following:
public string MapPath(string virtualPath)
{
return this.MapPath(VirtualPath.CreateAllowNull(virtualPath));
}
MapPath(VirtualPath virtualPath)
in turn calls MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, bool allowCrossAppMapping)
which contains the following:
//...
if (virtualPath == null)
{
virtualPath = VirtualPath.Create(".");
}
//...
So if you call MapPath(null)
or MapPath("")
, you are effectively calling MapPath(".")
Use stringi
package and stri_length
function
> stri_length(c("ala ma kota","ABC",NA))
[1] 11 3 NA
Why? Because it is the FASTEST among presented solutions :)
require(microbenchmark)
require(stringi)
require(stringr)
x <- c(letters,NA,paste(sample(letters,2000,TRUE),collapse=" "))
microbenchmark(nchar(x),str_length(x),stri_length(x))
Unit: microseconds
expr min lq median uq max neval
nchar(x) 11.868 12.776 13.1590 13.6475 41.815 100
str_length(x) 30.715 33.159 33.6825 34.1360 173.400 100
stri_length(x) 2.653 3.281 4.0495 4.5380 19.966 100
and also works fine with NA's
nchar(NA)
## [1] 2
stri_length(NA)
## [1] NA
public static String readFile(String fn) throws IOException
{
File f = new File(fn);
byte[] buffer = new byte[(int)f.length()];
FileInputStream is = new FileInputStream(fn);
is.read(buffer);
is.close();
return new String(buffer, "UTF-8"); // use desired encoding
}
If you're looking to print specific data that you already have access to, whether it's from a Store, AJAX, or available elsewhere, you can leverage my library react-print.
https://github.com/captray/react-print
It makes creating print templates much easier (assuming you already have a dependency on react). You just need to tag your HTML appropriately.
This ID should be added higher up in your actual DOM tree to exclude everything except the "print mount" below.
<div id="react-no-print">
This is where your react-print component will mount and wrap your template that you create:
<div id="print-mount"></div>
An example looks something like this:
var PrintTemplate = require('react-print');
var ReactDOM = require('react-dom');
var React = require('react');
var MyTemplate = React.createClass({
render() {
return (
<PrintTemplate>
<p>Your custom</p>
<span>print stuff goes</span>
<h1>Here</h1>
</PrintTemplate>
);
}
});
ReactDOM.render(<MyTemplate/>, document.getElementById('print-mount'));
It's worth noting that you can create new or utilize existing child components inside of your template, and everything should render fine for printing.
Assuming you have python 2.7 64bit on your computer and have downloaded numpy from here, follow the steps below (changing numpy-1.9.2+mkl-cp27-none-win_amd64.whl
as appropriate).
At the command prompt, navigate to the directory containing get-pip.py
and runpython get-pip.py
which creates files in C:\Python27\Scripts
, including pip2
, pip2.7
and pip
.
Copy the downloaded numpy-1.9.2+mkl-cp27-none-win_amd64.whl
into the above directory (C:\Python27\Scripts
)
Still at the command prompt, navigate to the above directory and run:
pip2.7.exe install "numpy-1.9.2+mkl-cp27-none-win_amd64.whl"
Three more ways of doing so:
(I) I think using map
may also be an option, though is requires generation of an additional list with None
s in some cases and always needs a list of arguments:
def do():
print 'hello world'
l=map(lambda x: do(), range(10))
(II) itertools
contain functions which can be used used to iterate through other functions as well https://docs.python.org/2/library/itertools.html
(III) Using lists of functions was not mentioned so far I think (and it is actually the closest in syntax to the one originally discussed) :
it=[do]*10
[f() for f in it]
Or as a one liner:
[f() for f in [do]*10]
String.equals("")
is actually a bit slower than just an isEmpty()
call. Strings store a count variable initialized in the constructor, since Strings are immutable.
isEmpty()
compares the count variable to 0, while equals will check the type, string length, and then iterate over the string for comparison if the sizes match.
So to answer your question, isEmpty()
will actually do a lot less! and that's a good thing.
PHP manual has a good read on the question here.
The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.
If this is your first time to submit an app, I recommend going ahead and reading through the full Apple iTunes Connect documentation or reading one of the following tutorials:
However, those materials are cumbersome when you just want a quick reminder of the steps. My answer to that is below:
Sign in to iTunes Connect and go to My Apps. Then click the "+" button and choose New App.
Then fill out the basic information for a new app. The app bundle id needs to be the same as the one you are using in your Xcode project. There is probably a better was to name the SKU, but I've never needed it and I just use the bundle id.
Click Create and then go on to Step 2.
Choose the Generic iOS Device from the active scheme menu.
Then go to Product > Archive.
You may have to wait a little while for Xcode to finish archiving your project. After that you will be shown a dialog with your archived project. You can select Upload to the App Store... and follow the prompts.
I sometimes have to repeat this step a few times because I forgot to include something. Besides the upload wait, it isn't a big deal. Just keep doing it until you don't get any more errors.
Back in iTunes Connect you will need to complete all the required information and resources.
Just go through all the menu options and make sure that you have everything entered that needs to be.
In iTunes Connect, under your app's Prepare for Submission section, click Submit for Review. That's it. Give it about a week to be accepted (or rejected), but it might be faster.
I think I am a bit late to the party but... In my opinion, what you need is the object oriented API of matplotlib. In matplotlib 1.4.2 and using IPython 2.4.1 with Qt4Agg backend, I can do the following:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1) # Creates figure fig and add an axes, ax.
fig2, ax2 = plt.subplots(1) # Another figure
ax.plot(range(20)) #Add a straight line to the axes of the first figure.
ax2.plot(range(100)) #Add a straight line to the axes of the first figure.
fig.show() #Only shows figure 1 and removes it from the "current" stack.
fig2.show() #Only shows figure 2 and removes it from the "current" stack.
plt.show() #Does not show anything, because there is nothing in the "current" stack.
fig.show() # Shows figure 1 again. You can show it as many times as you want.
In this case plt.show() shows anything in the "current" stack. You can specify figure.show() ONLY if you are using a GUI backend (e.g. Qt4Agg). Otherwise, I think you will need to really dig down into the guts of matplotlib to monkeypatch a solution.
Remember that most (all?) plt.* functions are just shortcuts and aliases for figure and axes methods. They are very useful for sequential programing, but you will find blocking walls very soon if you plan to use them in a more complex way.
You can access session state using a custom RouteHandler.
// In global.asax
public class MvcApp : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
var route = routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
route.RouteHandler = new MyHttpControllerRouteHandler();
}
}
// Create two new classes
public class MyHttpControllerHandler
: HttpControllerHandler, IRequiresSessionState
{
public MyHttpControllerHandler(RouteData routeData) : base(routeData)
{ }
}
public class MyHttpControllerRouteHandler : HttpControllerRouteHandler
{
protected override IHttpHandler GetHttpHandler(
RequestContext requestContext)
{
return new MyHttpControllerHandler(requestContext.RouteData);
}
}
// Now Session is visible in your Web API
public class ValuesController : ApiController
{
public string Get(string input)
{
var session = HttpContext.Current.Session;
if (session != null)
{
if (session["Time"] == null)
session["Time"] = DateTime.Now;
return "Session Time: " + session["Time"] + input;
}
return "Session is not availabe" + input;
}
}
Found here: http://techhasnoboundary.blogspot.com/2012/03/mvc-4-web-api-access-session.html
This is how i solved my problem
xampp/mysql/data
directoryFollowing the Jenkins wiki, you'll have to:
chown -R jenkins:jenkins $JENKINS_HOME
JENKINS_HOME is by default located in ~/.jenkins
on a Linux installation, yet to exactly find where it is located, go on the http://your_jenkins_url/configure page and check the value of the first parameter: Home directory
; this is the JENKINS_HOME.
Editor's note: Although this answer contains some useful information, it is factually incorrect about the workings of Directory.Delete
. Please read the comments for this answer, and other answers to this question.
I ran into this problem before.
The root of the problem is that this function does not delete files that are within the directory structure. So what you'll need to do is create a function that deletes all the files within the directory structure then all the directories before removing the directory itself. I know this goes against the second parameter but it's a much safer approach. In addition, you will probably want to remove READ-ONLY access attributes from the files right before you delete them. Otherwise that will raise an exception.
Just slap this code into your project.
public static void DeleteDirectory(string target_dir)
{
string[] files = Directory.GetFiles(target_dir);
string[] dirs = Directory.GetDirectories(target_dir);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
Directory.Delete(target_dir, false);
}
Also, for me I personally add a restriction on areas of the machine that are allowed to be deleted because do you want someone to call this function on C:\WINDOWS (%WinDir%)
or C:\
.
#define DEBUG
#ifdef DEBUG
#define PRINT print
#else
#define PRINT(...) ((void)0) //strip out PRINT instructions from code
#endif
void print(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
vsprintf(str, fmt, args);
va_end(args);
printf("%s\n", str);
}
int main() {
PRINT("[%s %d, %d] Hello World", "March", 26, 2009);
return 0;
}
If the compiler does not understand variadic macros, you can also strip out PRINT with either of the following:
#define PRINT //
or
#define PRINT if(0)print
The first comments out the PRINT instructions, the second prevents PRINT instruction because of a NULL if condition. If optimization is set, the compiler should strip out never executed instructions like: if(0) print("hello world"); or ((void)0);
You can just run:
git stash pop
and it will unstash your changes.
If you want to preserve the state of files (staged vs. working), use
git stash apply --index
Use ListObjectsRequest setting Prefix as your key.
.NET code:
public bool Exists(string key)
{
using (Amazon.S3.AmazonS3Client client = (Amazon.S3.AmazonS3Client)Amazon.AWSClientFactory.CreateAmazonS3Client(m_accessKey, m_accessSecret))
{
ListObjectsRequest request = new ListObjectsRequest();
request.BucketName = m_bucketName;
request.Prefix = key;
using (ListObjectsResponse response = client.ListObjects(request))
{
foreach (S3Object o in response.S3Objects)
{
if( o.Key == key )
return true;
}
return false;
}
}
}.
You only need to prefix an if
statement with @
if you're not already inside a razor code block.
Edit: You have a couple of things wrong with your code right now.
You're declaring nmb
, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:
@if (ViewBag.Articles != null)
{
int nmb = 0;
foreach (var item in ViewBag.Articles)
{
if (nmb % 3 == 0)
{
@:<div class="row">
}
<a href="@Url.Action("Article", "Programming", new { id = item.id })">
<div class="tasks">
<div class="col-md-4">
<div class="task important">
<h4>@item.Title</h4>
<div class="tmeta">
<i class="icon-calendar"></i>
@item.DateAdded - Pregleda:@item.Click
<i class="icon-pushpin"></i> Authorrr
</div>
</div>
</div>
</div>
</a>
if (nmb % 3 == 0)
{
@:</div>
}
}
}
The important part here is the @:
. It's a short-hand of <text></text>
, which is used to force the razor engine to render text.
One other thing, the HTML standard specifies that a
tags can only contain inline elements, and right now, you're putting a div
, which is a block-level element, inside an a
.
Here's the code that works for me everytime (for Outlook emails):
#to read Subjects and Body of email in a folder (or subfolder)
import win32com.client
#import package
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
#create object
#get to the desired folder ([email protected] is my root folder)
root_folder =
outlook.Folders['[email protected]'].Folders['Inbox'].Folders['SubFolderName']
#('Inbox' and 'SubFolderName' are the subfolders)
messages = root_folder.Items
for message in messages:
if message.Unread == True: # gets only 'Unread' emails
subject_content = message.subject
# to store subject lines of mails
body_content = message.body
# to store Body of mails
print(subject_content)
print(body_content)
message.Unread = True # mark the mail as 'Read'
message = messages.GetNext() #iterate over mails
This Plugin Made by me may be helpful.
You can use this plugin you have to supply the key Codes and function to be run like this
simulatorControl([17,83], function(){
console.log('You have pressed Ctrl+Z');
});
In the code i have displayed how to perform for Ctrl+S. You will get Detailed Documentation On the link. Plugin is in JavaScript Code section Of my Pen on Codepen.
The best to remove a class in jquery from all the elements is to target via element tag. e.g.,
$("div").removeClass("highlight");
Moment.js
Install moment.js
from here.
npm : $ npm i --save moment
Bower : $ bower install --save moment
Next,
var date = moment()
.add(2,'d') //replace 2 with number of days you want to add
.toDate(); //convert it to a Javascript Date Object if you like
Link Ref : http://momentjs.com/docs/#/manipulating/add/
Moment.js
is an amazing Javascript library to manage Date objects and extremely light weight at 40kb
.
Good Luck.
Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.
This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.
To change the datasource connection, go the Database menu and click Set Datasource Location.
And try running the report again.
The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.
To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.
_WIN32 identifier is not defined.
use #include <SDKDDKVer.h>
MSVS generated projects wrap this include by generating a local "targetver.h"
which is included by "stdafx.h"
that is comiled into a precompiled-header through "stdafx.cpp"
.
EDIT : do you have a /D "WIN32" on your commandline ?
The AtomicBoolean
class gives you a boolean value that you can update atomically. Use it when you have multiple threads accessing a boolean variable.
The java.util.concurrent.atomic package overview gives you a good high-level description of what the classes in this package do and when to use them. I'd also recommend the book Java Concurrency in Practice by Brian Goetz.
HTML
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
</ul>
CSS
li:not(:last-child) {
margin-bottom: 5px;
}
EDIT: If you don't use the special case for the last li element your list will have a small spacing afterwards which you can see here: http://jsfiddle.net/wQYw7/
Now compare that with my solution: http://jsfiddle.net/wQYw7/1/
Sure this doesn't work in older browsers but you can easily use js extensions which will enable this for older browsers.
The error TypeError: 'numpy.ndarray' object is not callable
means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:
In [16]: import numpy as np
In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()
TypeError: 'numpy.ndarray' object is not callable
If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean
or pd.rolling_std
to a numpy array earlier in your code.
What I mean is something like this:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan, nan, nan])
In [4]: pd.rolling_mean = np.array([1,2,3])
In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
TypeError: 'numpy.ndarray' object is not callable
So, basically you need to search the rest of your codebase for pd.rolling_mean = ...
and/or pd.rolling_std = ...
to see where you may have overwritten them.
reload(pd)
just before your snippet, which should make it run by restoring the value of pd
to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.
You can use sort of Maybe monad (though I'd prefer Jay's answer)
public class Maybe<T>
{
private readonly T _value;
public Maybe(T value)
{
_value = value;
IsNothing = false;
}
public Maybe()
{
IsNothing = true;
}
public bool IsNothing { get; private set; }
public T Value
{
get
{
if (IsNothing)
{
throw new InvalidOperationException("Value doesn't exist");
}
return _value;
}
}
public override bool Equals(object other)
{
if (IsNothing)
{
return (other == null);
}
if (other == null)
{
return false;
}
return _value.Equals(other);
}
public override int GetHashCode()
{
if (IsNothing)
{
return 0;
}
return _value.GetHashCode();
}
public override string ToString()
{
if (IsNothing)
{
return "";
}
return _value.ToString();
}
public static implicit operator Maybe<T>(T value)
{
return new Maybe<T>(value);
}
public static explicit operator T(Maybe<T> value)
{
return value.Value;
}
}
Your method would look like:
public static Maybe<T> GetQueryString<T>(string key) where T : IConvertible
{
if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[key]) == false)
{
string value = HttpContext.Current.Request.QueryString[key];
try
{
return (T)Convert.ChangeType(value, typeof(T));
}
catch
{
//Could not convert. Pass back default value...
return new Maybe<T>();
}
}
return new Maybe<T>();
}
UPDATE: 2019-12-30
It seem that this tool is no longer working!
[Request for update!]
UPDATE 2019-01-06: You can bypass X-Frame-Options
in an <iframe>
using my X-Frame-Bypass Web Component. It extends the IFrame element by using multiple CORS proxies and it was tested in the latest Firefox and Chrome.
You can use it as follows:
(Optional) Include the Custom Elements with Built-in Extends polyfill for Safari:
<script src="https://unpkg.com/@ungap/custom-elements-builtin"></script>
Include the X-Frame-Bypass JS module:
<script type="module" src="x-frame-bypass.js"></script>
Insert the X-Frame-Bypass Custom Element:
<iframe is="x-frame-bypass" src="https://example.org/"></iframe>
vars:
mypath: "/etc/file.txt"
tasks:
- name: checking the file exists
command: touch file.txt
when: mypath is not exists
You don't have access to the right image as far my knowledge, unless you override the onTouch
event. I suggest to use a RelativeLayout
, with one editText
and one imageView
, and set OnClickListener
over the image view as below:
<RelativeLayout
android:id="@+id/rlSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:drawable/edit_text"
android:padding="5dip" >
<EditText
android:id="@+id/txtSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="@+id/imgSearch"
android:background="#00000000"
android:ems="10"/>
<ImageView
android:id="@+id/imgSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="@drawable/btnsearch" />
</RelativeLayout>
Try this, by for Loop
<form method="post">
<?php
for ($i=1; $i <5 ; $i++)
{
echo'<input type="checkbox" value="'.$i.'" name="checkbox[]"/>';
}
?>
<input type="submit" name="submit" class="form-control" value="Submit">
</form>
<?php
if(isset($_POST['submit']))
{
$check=implode(", ", $_POST['checkbox']);
print_r($check);
}
?>
None of the accepted answers pointed me in the right direction, and this is still the question that comes up when searching the topic, so here's my (partially) successful saga.
Background: I run a Python script on a Beaglebone Black that polls the cryptocurrency exchange Poloniex using the python-poloniex library. It suddenly stopped working with the TLSV1_ALERT_PROTOCOL_VERSION error.
Turns out that OpenSSL was fine, and trying to force a v1.2 connection was a huge wild goose chase - the library will use the latest version as necessary. The weak link in the chain was actually Python, which only defined ssl.PROTOCOL_TLSv1_2
, and therefore started supporting TLS v1.2, since version 3.4.
Meanwhile, the version of Debian on the Beaglebone considers Python 3.3 the latest. The workaround I used was to install Python 3.5 from source (3.4 might have eventually worked too, but after hours of trial and error I'm done):
sudo apt-get install build-essential checkinstall
sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
wget https://www.python.org/ftp/python/3.5.4/Python-3.5.4.tgz
sudo tar xzf Python-3.5.4.tgz
cd Python-3.5.4
./configure
sudo make altinstall
Maybe not all those packages are strictly necessary, but installing them all at once saves a bunch of retries. The altinstall
prevents the install from clobbering existing python binaries, installing as python3.5
instead, though that does mean you have to re-install additional libraries. The ./configure
took a good five or ten minutes. The make
took a couple of hours.
Now this still didn't work until I finally ran
sudo -H pip3.5 install requests[security]
Which also installs pyOpenSSL
, cryptography
and idna
. I suspect pyOpenSSL
was the key, so maybe pip3.5 install -U pyopenssl
would have been sufficient but I've spent far too long on this already to make sure.
So in summary, if you get TLSV1_ALERT_PROTOCOL_VERSION error in Python, it's probably because you can't support TLS v1.2. To add support, you need at least the following:
This has got me past TLSV1_ALERT_PROTOCOL_VERSION, and now I get to battle with SSL23_GET_SERVER_HELLO instead.
Turns out this is back to the original issue of Python selecting the wrong SSL version. This can be confirmed by using this trick to mount a requests session with ssl_version=ssl.PROTOCOL_TLSv1_2
. Without it, SSLv23 is used and the SSL23_GET_SERVER_HELLO error appears. With it, the request succeeds.
The final battle was to force TLSv1_2 to be picked when the request is made deep within a third party library. Both this method and this method ought to have done the trick, but neither made any difference. My final solution is horrible, but effective. I edited /usr/local/lib/python3.5/site-packages/urllib3/util/ssl_.py
and changed
def resolve_ssl_version(candidate):
"""
like resolve_cert_reqs
"""
if candidate is None:
return PROTOCOL_SSLv23
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'PROTOCOL_' + candidate)
return res
return candidate
to
def resolve_ssl_version(candidate):
"""
like resolve_cert_reqs
"""
if candidate is None:
return ssl.PROTOCOL_TLSv1_2
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'PROTOCOL_' + candidate)
return res
return candidate
and voila, my script can finally contact the server again.
If you are experiencing the OP's problem where your cookies have been set using JavaScript - for example:
document.cookie = "my_cookie_name=my_cookie_value; expires=Thu, 11 Jun 2070 11:11:11 UTC; path=/";
you could instead use:
document.cookie = "my_cookie_name=my_cookie_value; expires=Thu, 11 Jun 2070 11:11:11 UTC; path=/; SameSite=None; Secure";
It worked for me. More info here.
ah homework...
So wait, you need to deduct the balance of items in stock from the total number of those items that have been ordered? I have to tell you that sounds a bit backwards. Generally I think people do it the other way round. Deduct the total number of items ordered from the balance.
If you really need to do that though... Assuming that ITEM is unique in stock_bal...
SELECT s.ITEM, SUM(m.QTY) - s.QTY AS result
FROM stock_bal s
INNER JOIN master_table m ON m.ITEM = s.ITEM
GROUP BY s.ITEM, s.QTY
You can revert only one file to a specified revision.
First you can check on which commits the file was changed.
git log path/to/file.txt
Then you can checkout the file with the revision number.
git checkout 3cdc61015724f9965575ba954c8cd4232c8b42e4 /path/to/file.txt
After that you can commit and push it again.
OS X is "LP64". This means that:
int
is always 32-bits.
long long
is always 64-bits.
NSInteger
and long
are always pointer-sized. That means they're 32-bits on 32-bit systems, and 64 bits on 64-bit systems.
The reason NSInteger exists is because many legacy APIs incorrectly used int
instead of long
to hold pointer-sized variables, which meant that the APIs had to change from int
to long
in their 64-bit versions. In other words, an API would have different function signatures depending on whether you're compiling for 32-bit or 64-bit architectures. NSInteger
intends to mask this problem with these legacy APIs.
In your new code, use int
if you need a 32-bit variable, long long
if you need a 64-bit integer, and long
or NSInteger
if you need a pointer-sized variable.
In all versions of .NET, you can repeat a string thus:
public static string Repeat(string value, int count)
{
return new StringBuilder(value.Length * count).Insert(0, value, count).ToString();
}
To repeat a character, new String('\t', count)
is your best bet. See the answer by @CMS.
Executing following code from the browser address bar:
javascript: console.log(2);
successfully prints message to the "JavaScript Console" in Google Chrome.
Or, you can ignore the error:
declare
column_exists exception;
pragma exception_init (column_exists , -01430);
begin
execute immediate 'ALTER TABLE db.tablename ADD columnname NVARCHAR2(30)';
exception when column_exists then null;
end;
/
You could also use the RenderView Controller extension
from here
(source)
and use it like this:
public ActionResult Do() {
var html = this.RenderView("index", theModel);
...
}
it works for razor and web-forms viewengines
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
It must be overridden. You could use:
<!-- Add a class name to override -->
<select name="funTimes" class="funTimes" size="5">
#elementId select.funTimes {
/* Override styles here */
}
Make sure you use !important
flag in css style e.g. margin-top: 0px !important
What does !important mean in CSS?
You could use an attribute selector, but since that isn't supported by legacy browsers (read IE6 etc), it's better to add a class name
WorksheetFunction Transpose()
Instead of copying, pasting via PasteSpecial, and using the Transpose
option you can simply type a formula
=TRANSPOSE(Sheet1!A1:A5)
or if you prefer VBA:
Dim v
v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
Sheet2.Range("A1").Resize(1, UBound(v)) = v
Note: alternatively you could use late-bound Application.Transpose
instead.
MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.
Versions Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365
there is a little problem here because the
if (typeof item !== 'string') {
return false
}
will not stop the foreach. So the function will return true even if the array does contain none string values.
This seems to wok for me:
function isStringArray(value: any): value is number[] {
if (Object.prototype.toString.call(value) === '[object Array]') {
if (value.length < 1) {
return false;
} else {
return value.every((d: any) => typeof d === 'string');
}
}
return false;
}
Greetings, Hans
The top answer is good but it doesn't mention expression trees which explain "how" the two interfaces differ. Basically, there are two identical sets of LINQ extensions. Where()
, Sum()
, Count()
, FirstOrDefault()
, etc all have two versions: one that accepts functions and one that accepts expressions.
The IEnumerable
version signature is: Where(Func<Customer, bool> predicate)
The IQueryable
version signature is: Where(Expression<Func<Customer, bool>> predicate)
You've probably been using both of those without realizing it because both are called using identical syntax:
e.g. Where(x => x.City == "<City>")
works on both IEnumerable
and IQueryable
When using Where()
on an IEnumerable
collection, the compiler passes a compiled function to Where()
When using Where()
on an IQueryable
collection, the compiler passes an expression tree to Where()
. An expression tree is like the reflection system but for code. The compiler converts your code into a data structure that describes what your code does in a format that's easily digestible.
Why bother with this expression tree thing? I just want Where()
to filter my data.
The main reason is that both the EF and Linq2SQL ORMs can convert expression trees directly into SQL where your code will execute much faster.
Oh, that sounds like a free performance boost, should I use AsQueryable()
all over the place in that case?
No, IQueryable
is only useful if the underlying data provider can do something with it. Converting something like a regular List
to IQueryable
will not give you any benefit.
If you're wondering about functionality, then jQuery's .html()
performs the same intended functionality as .innerHTML
, but it also performs checks for cross-browser compatibility.
For this reason, you can always use jQuery's .html()
instead of .innerHTML
where possible.
As an additional hint to the great accepted answer:
When using a variation of the proposed solution, I got errors because of php setting 'max_execution_time'. So what I did was the following:
set_time_limit(120);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true);
$result = curl_exec($curl);
set_time_limit(ini_get('max_execution_time'));
curl_close($curl);
First I set the time limit to a higher number of seconds, in the end I set it back to the value defined in the php settings.
int bigNumber = 1234567;
String formattedNumber = String.format("%,d", bigNumber);
One classic root cause for this message is:
git init lis4368/assignments
),Ie, if you don't have added and committed at least once, there won't be a local master
branch to push to.
Try first to create a commit:
git add .
) then git commit -m "first commit"
git commit --allow-empty -m "Initial empty commit"
And then try git push -u origin master
again.
See "Why do I need to explicitly push a new branch?" for more.
You can also do it on the worksheet level captured in the worksheet's change event. If that suites your needs better. Allows for dynamic locking based on values, criteria, ect...
Private Sub Worksheet_Change(ByVal Target As Range)
'set your criteria here
If Target.Column = 1 Then
'must disable events if you change the sheet as it will
'continually trigger the change event
Application.EnableEvents = False
Application.Undo
Application.EnableEvents = True
MsgBox "You cannot do that!"
End If
End Sub
__main__.py
file for?When creating a Python module, it is common to make the module execute some functionality (usually contained in a main
function) when run as the entry point of the program. This is typically done with the following common idiom placed at the bottom of most Python files:
if __name__ == '__main__':
# execute only if run as the entry point into the program
main()
You can get the same semantics for a Python package with __main__.py
, which might have the following structure:
.
+-- demo
+-- __init__.py
+-- __main__.py
To see this, paste the below into a Python 3 shell:
from pathlib import Path
demo = Path.cwd() / 'demo'
demo.mkdir()
(demo / '__init__.py').write_text("""
print('demo/__init__.py executed')
def main():
print('main() executed')
""")
(demo / '__main__.py').write_text("""
print('demo/__main__.py executed')
from demo import main
main()
""")
We can treat demo as a package and actually import it, which executes the top-level code in the __init__.py
(but not the main
function):
>>> import demo
demo/__init__.py executed
When we use the package as the entry point to the program, we perform the code in the __main__.py
, which imports the __init__.py
first:
$ python -m demo
demo/__init__.py executed
demo/__main__.py executed
main() executed
You can derive this from the documentation. The documentation says:
__main__
— Top-level script environment
'__main__'
is the name of the scope in which top-level code executes. A module’s__name__
is set equal to'__main__'
when read from standard input, a script, or from an interactive prompt.A module can discover whether or not it is running in the main scope by checking its own
__name__
, which allows a common idiom for conditionally executing code in a module when it is run as a script or withpython -m
but not when it is imported:if __name__ == '__main__': # execute only if run as a script main()
For a package, the same effect can be achieved by including a
__main__.py
module, the contents of which will be executed when the module is run with-m
.
You can also zip up this directory, including the __main__.py
, into a single file and run it from the command line like this - but note that zipped packages can't execute sub-packages or submodules as the entry point:
from pathlib import Path
demo = Path.cwd() / 'demo2'
demo.mkdir()
(demo / '__init__.py').write_text("""
print('demo2/__init__.py executed')
def main():
print('main() executed')
""")
(demo / '__main__.py').write_text("""
print('demo2/__main__.py executed')
from __init__ import main
main()
""")
Note the subtle change - we are importing main
from __init__
instead of demo2
- this zipped directory is not being treated as a package, but as a directory of scripts. So it must be used without the -m
flag.
Particularly relevant to the question - zipapp
causes the zipped directory to execute the __main__.py
by default - and it is executed first, before __init__.py
:
$ python -m zipapp demo2 -o demo2zip
$ python demo2zip
demo2/__main__.py executed
demo2/__init__.py executed
main() executed
Note again, this zipped directory is not a package - you cannot import it either.
.container {_x000D_
padding: 10px;_x000D_
}_x000D_
.parent {_x000D_
width: 100%;_x000D_
background: #7b7b7b;_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
height: 4px;_x000D_
}_x000D_
.child {_x000D_
color: #fff;_x000D_
background: green;_x000D_
padding: 10px 10px;_x000D_
border-radius: 50%;_x000D_
position: relative;_x000D_
top: -8px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="parent">_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
<span class="child"></span>_x000D_
</div>_x000D_
</div>
_x000D_
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class CharCountFromAllFilesInFolder {
public static void main(String[] args)throws IOException {
try{
//C:\Users\MD\Desktop\Test1
System.out.println("Enter Your FilePath:");
Scanner sc = new Scanner(System.in);
Map<Character,Integer> hm = new TreeMap<Character, Integer>();
String s1 = sc.nextLine();
File file = new File(s1);
File[] filearr = file.listFiles();
for (File file2 : filearr) {
System.out.println(file2.getName());
FileReader fr = new FileReader(file2);
BufferedReader br = new BufferedReader(fr);
String s2 = br.readLine();
for (int i = 0; i < s2.length(); i++) {
if(!hm.containsKey(s2.charAt(i))){
hm.put(s2.charAt(i), 1);
}//if
else{
hm.put(s2.charAt(i), hm.get(s2.charAt(i))+1);
}//else
}//for2
System.out.println("The Char Count: "+hm);
}//for1
}//try
catch(Exception e){
System.out.println("Please Give Correct File Path:");
}//catch
}
}
Looks like the above answer did not answer the question completely.
I think you are looking for something like below:
class TransactionResponse {
String Success, Message;
List<Response> Response;
}
TransactionResponse = new Gson().fromJson(response, TransactionResponse.class);
where my response is something like this:
{"Success":false,"Message":"Invalid access token.","Response":null}
As you can see, the variable name should be same as the Json string representation of the key in the key value pair. This will automatically convert your gson string to JsonObject.
Yes, it is 128, except for temp tables, whose names can only be up to 116 character long. It is perfectly explained here.
And the verification can be easily made with the following script contained in the blog post before:
DECLARE @i NVARCHAR(800)
SELECT @i = REPLICATE('A', 116)
SELECT @i = 'CREATE TABLE #'+@i+'(i int)'
PRINT @i
EXEC(@i)
I recommend you to generate an open format XML Excel file, is much more flexible than CSV.
Read Generating an Excel file in ASP.NET for more info
I got a similar error with '/' operand while processing images. I discovered the folder included a text file created by the 'XnView' image viewer. So, this kind of error occurs when some object is not the kind of object expected.
The HTML Tidy library is able to fix some malformed XML files. Running your feeds through that before passing them on to the parser may help.
I have modified the above answer, so you don't need to cast from Object
public static <T> List<T> safeClient( List<T> other ) {
return other == null ? Collections.EMPTY_LIST : other;
}
and then simply call the List by
for (MyOwnObject ownObject : safeClient(someList)) {
// do whatever
}
Explaination:
MyOwnObject: If List<Integer>
then MyOwnObject will be Integer in this case.
To find a hostname in your local network by IP address you can use:
nmblookup -A <ip>
To find a hostname on the internet you could use the host
program:
host <ip>
Or you can install nbtscan
by running:
sudo apt-get install nbtscan
And use:
nbtscan <ip>
Update 2018-05-13
You can query a name server with nslookup
. It works both ways!
nslookup <IP>
nslookup <hostname>
In addition to the above posts, i'd like to point out that "man ls" will give you a nice manual about the "ls" ( List " command.
Also, using ls -la myFile will list & show all the facts about that file.
In Python 2.7 the multiline comment is:
"""
This is a
multilline comment
"""
In case you are inside a class you should tab it properly.
For example:
class weather2():
"""
def getStatus_code(self, url):
world.url = url
result = requests.get(url)
return result.status_code
"""
And as a context manager:
import signal
class GracefulInterruptHandler(object):
def __init__(self, sig=signal.SIGINT):
self.sig = sig
def __enter__(self):
self.interrupted = False
self.released = False
self.original_handler = signal.getsignal(self.sig)
def handler(signum, frame):
self.release()
self.interrupted = True
signal.signal(self.sig, handler)
return self
def __exit__(self, type, value, tb):
self.release()
def release(self):
if self.released:
return False
signal.signal(self.sig, self.original_handler)
self.released = True
return True
To use:
with GracefulInterruptHandler() as h:
for i in xrange(1000):
print "..."
time.sleep(1)
if h.interrupted:
print "interrupted!"
time.sleep(2)
break
Nested handlers:
with GracefulInterruptHandler() as h1:
while True:
print "(1)..."
time.sleep(1)
with GracefulInterruptHandler() as h2:
while True:
print "\t(2)..."
time.sleep(1)
if h2.interrupted:
print "\t(2) interrupted!"
time.sleep(2)
break
if h1.interrupted:
print "(1) interrupted!"
time.sleep(2)
break
From here: https://gist.github.com/2907502
Considering this still shows up when we search for EF in .NET Core, I'll post my answer here (Since it has haunted me a lot). Note that there are some subtleties with the EF 6 .NET version (No initial command, and you will need to delete "Snapshot" files)
(Tested in .NET Core 2.1)
Here are the steps:
_efmigrationhistory
table.ApplicationDbContextSnapshot.cs
, and delete them.Add-Migration InitialMigration
Please note: You must delete ALL the Snapshot files. I spent countless hours just deleting the database... This will generate an empty migration if you don't do it.
Also, in #3 you can just name your migration however you want.
Here are some additional resources: asp.net CORE Migrations generated empty
jQuery.ajax({
type: 'GET',
url: "../struktur2/load.php",
async: false,
contentType: "application/json",
dataType: 'json',
success: function(json) {
items = json;
},
error: function(e) {
console.log("jQuery error message = "+e.message);
}
});
You can use the clear method
List<string> test = new List<string>();
test.Clear();
here's my refactored version which accepts multiline/single as an option
public string ShowDialog(string text, string caption, bool isMultiline = false, int formWidth = 300, int formHeight = 200)
{
var prompt = new Form
{
Width = formWidth,
Height = isMultiline ? formHeight : formHeight - 70,
FormBorderStyle = isMultiline ? FormBorderStyle.Sizable : FormBorderStyle.FixedSingle,
Text = caption,
StartPosition = FormStartPosition.CenterScreen,
MaximizeBox = isMultiline
};
var textLabel = new Label
{
Left = 10,
Padding = new Padding(0, 3, 0, 0),
Text = text,
Dock = DockStyle.Top
};
var textBox = new TextBox
{
Left = isMultiline ? 50 : 4,
Top = isMultiline ? 50 : textLabel.Height + 4,
Multiline = isMultiline,
Dock = isMultiline ? DockStyle.Fill : DockStyle.None,
Width = prompt.Width - 24,
Anchor = isMultiline ? AnchorStyles.Left | AnchorStyles.Top : AnchorStyles.Left | AnchorStyles.Right
};
var confirmationButton = new Button
{
Text = @"OK",
Cursor = Cursors.Hand,
DialogResult = DialogResult.OK,
Dock = DockStyle.Bottom,
};
confirmationButton.Click += (sender, e) =>
{
prompt.Close();
};
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmationButton);
prompt.Controls.Add(textLabel);
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : string.Empty;
}
For excluding multiple file types, you can use '+' to concatenate other lists. For example:
xcopy /r /d /i /s /y /exclude:excludedfileslist1.txt+excludedfileslist2.txt C:\dev\apan C:\web\apan
Source: http://www.tech-recipes.com/rx/2682/xcopy_command_using_the_exclude_flag/
The best
and the rest
As a general statement, its good to make your if conditionals as readable as possible. For your example, using ! is ok. the problem is when things look like
if ((a.b && c.d.e) || !f)
you might want to do something like
bool isOk = a.b;
bool isStillOk = c.d.e
bool alternateOk = !f
then your if statement is simplified to
if ( (isOk && isStillOk) || alternateOk)
It just makes the code more readable. And if you have to debug, you can debug the isOk set of vars instead of having to dig through the variables in scope. It is also helpful for dealing with NPEs -- breaking code out into simpler chunks is always good.
You can download a native OpenSSL for Windows, or you can always use Cygwin.
In my case, click event was propagating on child element. So, I had to put the following:
e.stopPropagation()
on click event:
$(document).on("click", ".remove-discount-button", function (e) {
e.stopPropagation();
//some code
});
$(document).on("click", ".current-code", function () {
$('.remove-discount-button').trigger("click");
});
Here is the html code:
<div class="current-code">
<input type="submit" name="removediscountcouponcode" value="
title="Remove" class="remove-discount-button">
</div>
To answer your question:
In my Dockerfile, I would like to define variables that I can use later in the Dockerfile.
You can define a variable with:
ARG myvalue=3
Spaces around the equal character are not allowed.
And use it later with:
RUN echo $myvalue > /test
As Arnaud suggested in a comment to the original post, you should put this in your html header:
<meta http-equiv="X-UA-Compatible" content="IE=edge">
I don't want any cred for this. I just want to make it more visible for anyone else that come here.
As suggested by Adam Miller in the comments, I'll add another solution.
The MailMessage(String from, String to) constructor accepts a comma separated list of addresses. So if you happen to have already a comma (',') separated list, the usage is as simple as:
MailMessage Msg = new MailMessage(fromMail, addresses);
In this particular case, we can replace the ';' for ',' and still make use of the constructor.
MailMessage Msg = new MailMessage(fromMail, addresses.replace(";", ","));
Whether you prefer this or the accepted answer it's up to you. Arguably the loop makes the intent clearer, but this is shorter and not obscure. But should you already have a comma separated list, I think this is the way to go.
c# version of @qfactor77's answer. This is the best way without LINQ .
string[] wildcards= {"*.mp4", "*.jpg"};
ReadOnlyCollection<string> filePathCollection = FileSystem.GetFiles(dirPath, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, wildcards);
string[] filePath=new string[filePathCollection.Count];
filePathCollection.CopyTo(filePath,0);
now return filePath
string array. In the beginning you need
using Microsoft.VisualBasic.FileIO;
using System.Collections.ObjectModel;
also you need to add reference to Microsoft.VisualBasic
You have to use shell=True in subprocess and no shlex.split:
def subprocess_cmd(command):
process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
print proc_stdout
subprocess_cmd('echo a; echo b')
returns:
a
b
You should add maven-resources-plugin in your pom.xml file. Deleting ~/.m2/repository does not work always.
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4</version>
</plugin>
</plugins>
Now build your project again. It should be successful!
Checking internet status every time using Broadcast Receiver:
Full source code available on Google Drive.
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<receiver android:name=".receivers.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
BroadcastReciever
package com.keshav.networkchangereceiverexample.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import static com.keshav.networkchangereceiverexample.MainActivity.dialog;
public class NetworkChangeReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
try
{
if (isOnline(context)) {
dialog(true);
Log.e("keshav", "Online Connect Intenet ");
} else {
dialog(false);
Log.e("keshav", "Conectivity Failure !!! ");
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private boolean isOnline(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
}
MainActivity.java
package com.keshav.networkchangereceiverexample;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import com.keshav.networkchangereceiverexample.receivers.NetworkChangeReceiver;
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver mNetworkReceiver;
static TextView tv_check_connection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_check_connection=(TextView) findViewById(R.id.tv_check_connection);
mNetworkReceiver = new NetworkChangeReceiver();
registerNetworkBroadcastForNougat();
}
public static void dialog(boolean value){
if(value){
tv_check_connection.setText("We are back !!!");
tv_check_connection.setBackgroundColor(Color.GREEN);
tv_check_connection.setTextColor(Color.WHITE);
Handler handler = new Handler();
Runnable delayrunnable = new Runnable() {
@Override
public void run() {
tv_check_connection.setVisibility(View.GONE);
}
};
handler.postDelayed(delayrunnable, 3000);
}else {
tv_check_connection.setVisibility(View.VISIBLE);
tv_check_connection.setText("Could not Connect to internet");
tv_check_connection.setBackgroundColor(Color.RED);
tv_check_connection.setTextColor(Color.WHITE);
}
}
private void registerNetworkBroadcastForNougat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
protected void unregisterNetworkChanges() {
try {
unregisterReceiver(mNetworkReceiver);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterNetworkChanges();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.keshav.networkchangereceiverexample.MainActivity">
<TextView
android:id="@+id/tv_check_connection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connection establised !"
android:padding="25dp"
app:layout_constraintBottom_toBottomOf="parent"
android:gravity="center"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
Or you can use the focus event on your dateSelect object and position api together. You can swap top and bottom and left for right or center (or really anything you want from the position api). This way you don't need an interval or any insanely complex solution and you can configure the layout to suit your needs depending on where the input is.
dateSelect.focus(function () {
$("#ui-datepicker-div").position({
my: "left top",
at: "left bottom",
of: $(this)
});
});
MySQL doesn't allow selecting from a table and update in the same table at the same time. But there is always a workaround :)
This doesn't work >>>>
UPDATE table1 SET col1 = (SELECT MAX(col1) from table1) WHERE col1 IS NULL;
But this works >>>>
UPDATE table1 SET col1 = (SELECT MAX(col1) FROM (SELECT * FROM table1) AS table1_new) WHERE col1 IS NULL;
My first response was made before iOS 7 introduced explicit support for displaying attributed strings in common controls. You may now set attributedText
of UITextView
to an NSAttributedString
created from HTML content using:
-(id)initWithData:(NSData *)data options:(NSDictionary *)options documentAttributes:(NSDictionary **)dict error:(NSError **)error
- initWithData:options:documentAttributes:error: (Apple Doc)
Original answer, preserved for history:
Unless you use a UIWebView
, your solution will rely directly on CoreText
. As ElanthiraiyanS points out, some open source projects have emerged to simplify rich text rendering. I would recommend NSAttributedString-Additions-For-HTML (Edit: the project has been supplanted DTCoreText), which features classes to generate and display attributed strings from HTML.
The Oracle error ORA-01036 means that the query uses an undefined variable somewhere. From the query we can determine which variables are in use, namely all that start with @. However, if you're inputting this into an advanced query, it's important to confirm that all variables have a matching input parameter, including the same case as in the variable name, if your Oracle database is Case Sensitive.
Assuming you are using Windows forms, you could allow the user to select a row and in the delete key click event. It is recommended that you allow the user to select 1 row only and not a group of rows (myDataGridView.MultiSelect = false)
Private Sub pbtnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
If myDataGridView.SelectedRows.Count > 0 Then
'you may want to add a confirmation message, and if the user confirms delete
myDataGridView.Rows.Remove(myDataGridView.SelectedRows(0))
Else
MessageBox.Show("Select 1 row before you hit Delete")
End If
End Sub
Note that this will not delete the row form the database until you perform the delete in the database.
I think we can do this with one line simple command
for i in `grep -rl eth0 . 2> /dev/null`; do sed -i ‘s/eth0/eth1/’ $i; done
Refer to this page.
Here's a workaround for installing the 64-bit version of the Microsoft Access Database Engine 2010 redistributable on a system with a 32-bit MS Office version installed:
Now you can start a 32-bit MS Office application without the "re-configuring" issue. Note that the "mso.dll" registry value will already be present if a 64-bit version of MS Office is installed. In this case the value should not be deleted or renamed.
Also if you do not want to use the "/passive" command line parameter you can edit the AceRedist.msi file to remove the MS Office architecture check:
You can now use this file to install the Microsoft Access Database Engine 2010 redistributable on a system where a "conflicting" version of MS Office is installed (e.g. 64-bit version on system with 32-bit MS Office version) Make sure that you rename the "mso.dll" registry value as explained above (if needed).
I had a similar sounding situation with my Nexus 4. For me it was an issue with the drivers Windows was installing automatically. I followed the instructions in [Q]Computer won't recognize phone? - Post #8. I had some slight differences on Windows 7.
For me I,
Good luck!
One thing, regardless of how you initialize the field, use of the final
qualifier, if possible, will ensure the visibility of the field's value in a multi-threaded environment.