I have a C# Winforms project called SetTags with a large number of forms that I use Visual Studio 2013 to work on. After editing one of them and trying to build I got the error:
Could not load file or assembly 'SetTags Version = 2.1.85.0, Culture=neutral,PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
The error also appeared when I tried to save the project or to close the form I had been working on.
I fixed the problem by removing a recently added radio button control and commenting out all references to it, then added the control again and uncommenting the code. This allowed me to save the form, and on closing restarting VS the problem had disappeared.
My Visual Studio environment has many occasional problems - Toolbox not showing or appearing only on VS startup, unrecognized custom controls when trying to view a form in Design mode - and it may be that I need to move on to a later VS version.
I think you should indeed be using the Control overload of the RegisterStartupScript.
I've tried the following code in a server control:
[ToolboxData("<{0}:AlertControl runat=server></{0}:AlertControl>")]
public class AlertControl : Control{
protected override void OnInit(EventArgs e){
base.OnInit(e);
string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
Then in my page I have:
protected override void OnInit(EventArgs e){
base.OnInit(e);
Placeholder1.Controls.Add(new AlertControl());
}
Where Placeholder1 is a placeholder in an update panel. The placeholder has a couple of other controls on in it, including buttons.
This behaved exactly as you would expect, I got an alert saying "Hello" every time I loaded the page or caused the update panel to update.
The other thing you could look at is to hook into some of the page lifecycle events that are fired during an update panel request:
Sys.WebForms.PageRequestManager.getInstance()
.add_endRequest(EndRequestHandler);
The PageRequestManager endRequestHandler event fires every time an update panel completes its update - this would allow you to call a method to set up your control.
My only other questions are:
I guess you are using an IDE (like Netbeans) which allows you to run the code even if certain classes are not compilable. During the application's runtime, if you access this class it would lead to this exception.
I just came across the same problem where I needed to wait for all the threads which were created using the for loop.I just tried out the following piece of code.It may not be the perfect solution but I thought it would be a simple solution to test:
for t in threading.enumerate():
try:
t.join()
except RuntimeError as err:
if 'cannot join current thread' in err:
continue
else:
raise
You should install Android SDK Build Tools 23.0.1 via Android SDK. Don't forget to check Show Packages Details
.
I changed the python interpreter and it worked. On the keyboard, I pressed ctrl+shift+p. On the next window, I typed python: select interpreter, and there was an option to select the interpreter I wanted. From here, I chose the python interpreter located in my virtual environment.
In this case, it was my ~\DevFolder\myenv\scripts\python.exe
-eq
is a mathematical comparison operator. I've never used it for string comparison, relying on ==
and !=
for compares.
if [ 'XYZ' == 'ABC' ]; then # Double equal to will work in Linux but not on HPUX boxes it should be if [ 'XYZ' = 'ABC' ] which will work on both
echo "Match"
else
echo "No Match"
fi
You could make the directories that your modules exist in read-only for the user that the Python interpreter is running as.
I don't think there's a more elegant option. PEP 304 appears to have been an attempt to introduce a simple option for this, but it appears to have been abandoned.
I imagine there's probably some other problem you're trying to solve, for which disabling .py[co] would appear to be a workaround, but it'll probably be better to attack whatever this original problem is instead.
Oracle SQL: Usable with any phone number length and can easily support localization.
CREATE TABLE digit_character_map (digit number(1), character varchar2(1));
SELECT replace(permutations,' ','') AS permutations
FROM (SELECT sys_connect_by_path(map.CHARACTER,' ') AS permutations, LEVEL AS lvl
FROM digit_character_map map
START WITH map.digit = substr('12345',1,1)
CONNECT BY digit = substr('12345',LEVEL,1))
WHERE lvl = length('12345');
You can place your folder in the root of the ServletContext.
Then specify a relative or absolute path to this directory in application.yml:
spring:
resources:
static-locations: file:some_temp_files/
The resources in this folder will be available (for downloading, for example) at:
http://<host>:<port>/<context>/your_file.csv
You can define your versionName
and versionCode
in your module's build.gradle
file like this :
android {
compileSdkVersion 19
buildToolsVersion "19.0.1"
defaultConfig {
minSdkVersion 8
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
.... //Other Configuration
}
It allows you to queue up animations... for example, instead of this
$('#my-element').animate( { opacity: 0.2, width: '100px' }, 2000);
Which fades the element and makes the width 100 px at the same time. Using the queue allows you to stage the animations. So one finishes after the other.
$("#show").click(function () {
var n = $("div").queue("fx");
$("span").text("Queue length is: " + n.length);
});
function runIt() {
$("div").show("slow");
$("div").animate({left:'+=200'},2000);
$("div").slideToggle(1000);
$("div").slideToggle("fast");
$("div").animate({left:'-=200'},1500);
$("div").hide("slow");
$("div").show(1200);
$("div").slideUp("normal", runIt);
}
runIt();
Example from http://docs.jquery.com/Effects/queue
I had the same issue on localhost. I have changed the domain for the app, but in URLs and hosts file there was still the old domain. Updated my browser bookmarks and hosts file to use new domain and now everything works fine.
p
is the conversion specifier to print pointers. Use this.
int a = 42;
printf("%p\n", (void *) &a);
Remember that omitting the cast is undefined behavior and that printing with p
conversion specifier is done in an implementation-defined manner.
I don't like to create a new settings/
directory. I simply add files named settings_dev.py
and settings_production.py
so I don't have to edit the BASE_DIR
.
The approach below increase the default structure instead of changing it.
mysite/ # Project
conf/
locale/
en_US/
fr_FR/
it_IT/
mysite/
__init__.py
settings.py
settings_dev.py
settings_production.py
urls.py
wsgi.py
static/
admin/
css/ # Custom back end styles
css/ # Project front end styles
fonts/
images/
js/
sass/
staticfiles/
templates/ # Project templates
includes/
footer.html
header.html
index.html
myapp/ # Application
core/
migrations/
__init__.py
templates/ # Application templates
myapp/
index.html
static/
myapp/
js/
css/
images/
__init__.py
admin.py
apps.py
forms.py
models.py
models_foo.py
models_bar.py
views.py
templatetags/ # Application with custom context processors and template tags
__init__.py
context_processors.py
templatetags/
__init__.py
templatetag_extras.py
gulpfile.js
manage.py
requirements.txt
I think this:
settings.py
settings_dev.py
settings_production.py
is better than this:
settings/__init__.py
settings/base.py
settings/dev.py
settings/production.py
This concept applies to other files as well.
I usually place node_modules/
and bower_components/
in the project directory within the default static/
folder.
Sometime a vendor/
directory for Git Submodules but usually I place them in the static/
folder.
The ES6 way:
let people = [{firstName:'Alice',lastName:'Cooper'},{firstName:'Bob',age:'Dylan'}];
let names = Array.from(people, p => p.firstName);
for (let name of names) {
console.log(name);
}
also at: https://jsfiddle.net/52dpucey/
Since your date field data is in int
you will need to convert it to a datetime:
declare @date int
set @date = 20080102
SELECT Datename(quarter, Cast(left(@date, 4) + '-'
+ substring(cast(@date as char(8)), 5, 2) + '-'
+ substring(cast(@date as char(8)), 7, 2) as datetime)) as Quarter
or
SELECT Datename(quarter, Cast(left(@date, 4) + '-'
+ substring(cast(@date as char(8)), 5, 2) + '-'
+ right(@date, 2) as datetime)) as quarter
Then if you want the Q1
added:
SELECT left(@date, 4) + '-Q' + Convert(varchar(1), Datename(quarter, Cast(left(@date, 4) + '-'
+ substring(cast(@date as char(8)), 5, 2) + '-'
+ right(@date, 2) as datetime))) as quarter
My advice would be to store your date
data as a datetime
so then you do not need to perform these conversions.
From: http://nginx.org/r/large_client_header_buffers
Syntax:
large_client_header_buffers
number
size
;
Default:large_client_header_buffers 4 8k;
Context: http, serverSets the maximum
number
andsize
of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.
so you need to change the size parameter at the end of that line to something bigger for your needs.
Found this thread when I couldn't load a json-file
with ES6 TypeScript 2.6
. I kept getting this error:
TS2307 (TS) Cannot find module 'json-loader!./suburbs.json'
To get it working I had to declare the module first. I hope this will save a few hours for someone.
declare module "json-loader!*" {
let json: any;
export default json;
}
...
import suburbs from 'json-loader!./suburbs.json';
If I tried to omit loader
from json-loader
I got the following error from webpack
:
BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders. You need to specify 'json-loader' instead of 'json', see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed
You can do it like this.
Models.TestModels obj = new Models.TestModels();
foreach (var item in obj.sp)
{
Console.Write(item.Key);
Console.Write(item.Value.name);
Console.Write(item.Value.age);
}
The problem you most likely have right now is that the collection is private. If you add public to the beginning of this line
Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>
You should be able to access it from the function inside your controller.
Edit: Adding functional example of the full TestModels
implementation.
Your TestModels
class should look something like this.
public class TestModels
{
public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();
public TestModels()
{
sp.Add(0, new {name="Test One", age=5});
sp.Add(1, new {name="Test Two", age=7});
}
}
You probably want to read up on the dynamic keyword as well.
just add below two annotations to your POJO.
@ComponentScan
@Configuration
public class YourClass {
//TODO
}
I would like to refer a previous question, Because I have faced same problem and solved by this solution.
First of all a constraint is always built with a Hash
value in it's name. So problem is this HASH
is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4
here 6AB17FE4
is the hash value(8 bit). So I am referring a single script which will be fruitful to all
DECLARE @Command NVARCHAR(MAX)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
set @table_name = N'ProcedureAlerts'
set @col_name = N'EmailSent'
select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
from
sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where
t.name = @table_name
and c.name = @col_name) + ']'
--print @Command
exec sp_executesql @Command
It will drop your default constraint. However if you want to create it again you can simply try this
ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]
Finally, just simply run a DROP
command to drop the column.
I started having this issue after upgrading from Rails 5.1 to 5.2
It got solved with:
spring stop
spring binstub --all
spring start
rails s
The default PostgreSQL port is 5432
. The host that the database is operating on should have been provided by your hosting provider; I'd guess it would be the same host as the web server if one wasn't specified. Typically this would be configured as localhost, assuming your web server and database server are on the same host.
You should always avoid using List<T>
as a parameter. Not only because this pattern reduces the opportunities of the caller to store the data in a different kind of collection, but also the caller has to convert the data into a List
first.
Converting an IEnumerable
into a List
costs O(n) complexity which is absolutely unneccessary. And it also creates a new object.
TL;DR you should always use a proper interface like IEnumerable
or IQueryable
based on what do you want to do with your collection. ;)
In your case:
public void foo(IEnumerable<DateTime> dateTimes)
{
}
If you happened to run npm install
command on Windows, first make sure you open your command prompt with Administration Privileges. That's what solved the issue for me.
The only way you can accomplish this in a cross-browser way is to use a framework like jQuery UI and create a custom Dialog:
It doesn't work in exactly the same way as the built-in confirm popup but you should be able to make it do what you want.
There is no shorthand in VBA unfortunately, The closest you will get is a purely visual thing using the :
continuation character if you want it on one line for readability;
Dim clientToTest As String: clientToTest = clientsToTest(i)
Dim clientString As Variant: clientString = Split(clientToTest)
Hint (summary of other answers/comments): Works with objects too (Excel 2010):
Dim ws As Worksheet: Set ws = ActiveWorkbook.Worksheets("Sheet1")
Dim ws2 As New Worksheet: ws2.Name = "test"
You would benefit from trying the TestScenarios library.
testscenarios provides clean dependency injection for python unittest style tests. This can be used for interface testing (testing many implementations via a single test suite) or for classic dependency injection (provide tests with dependencies externally to the test code itself, allowing easy testing in different situations).
Can you set the password to the phpmyadmin here
http://localhost/security/index.php
Django 1.10 no longer allows you to specify views as a string (e.g. 'myapp.views.home'
) in your URL patterns.
The solution is to update your urls.py
to include the view callable. This means that you have to import the view in your urls.py
. If your URL patterns don't have names, then now is a good time to add one, because reversing with the dotted python path no longer works.
from django.conf.urls import include, url
from django.contrib.auth.views import login
from myapp.views import home, contact
urlpatterns = [
url(r'^$', home, name='home'),
url(r'^contact/$', contact, name='contact'),
url(r'^login/$', login, name='login'),
]
If there are many views, then importing them individually can be inconvenient. An alternative is to import the views module from your app.
from django.conf.urls import include, url
from django.contrib.auth import views as auth_views
from myapp import views as myapp_views
urlpatterns = [
url(r'^$', myapp_views.home, name='home'),
url(r'^contact/$', myapp_views.contact, name='contact'),
url(r'^login/$', auth_views.login, name='login'),
]
Note that we have used as myapp_views
and as auth_views
, which allows us to import the views.py
from multiple apps without them clashing.
See the Django URL dispatcher docs for more information about urlpatterns
.
To parse the age:
Age age;
if (Enum.TryParse(typeof(Age), "New_Born", out age))
MessageBox.Show("Defined"); // Defined for "New_Born, 1, 4 , 8, 12"
To see if it is defined:
if (Enum.IsDefined(typeof(Age), "New_Born"))
MessageBox.Show("Defined");
Depending on how you plan to use the Age
enum, flags may not be the right thing. As you probably know, [Flags]
indicates you want to allow multiple values (as in a bit mask). IsDefined
will return false for Age.Toddler | Age.Preschool
because it has multiple values.
Easiest way is probably using command status; In the output you'll find database, user, host and port:
mysql> status;
--------------
mysql Ver 8.0.13 for Win64 on x86_64 (MySQL Community Server - GPL)
Connection id: 43
Current database: mysql
Current user: user@localhost
SSL: Cipher in use is DHE-RSA-AES128-GCM-SHA256
Using delimiter: ;
Server version: 8.0.13 MySQL Community Server - GPL
Protocol version: 10
Connection: localhost via TCP/IP
Server characterset: utf8mb4
Db characterset: utf8mb4
Client characterset: cp852
Conn. characterset: cp852
TCP port: 3306
Uptime: 3 hours 32 min 40 sec
Threads: 3 Questions: 197 Slow queries: 0 Opens: 214 Flush tables: 2 Open tables: 190 Queries per second avg: 0.015
--------------
I found a solution:
print("My message here");
If you need to split something into 3 pieces, such as an email address and you don't know the length of the middle part, try this (I just ran this on sqlserver 2012 so I know it works):
SELECT top 2000
emailaddr_ as email,
SUBSTRING(emailaddr_, 1,CHARINDEX('@',emailaddr_) -1) as username,
SUBSTRING(emailaddr_, CHARINDEX('@',emailaddr_)+1, (LEN(emailaddr_) - charindex('@',emailaddr_) - charindex('.',reverse(emailaddr_)) )) domain
FROM
emailTable
WHERE
charindex('@',emailaddr_)>0
AND
charindex('.',emailaddr_)>0;
GO
Hope this helps.
The directory should be empty.
BOOL RemoveDirectory( LPCTSTR lpPathName );
array_count_values
, enjoy :-)
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$vals = array_count_values($array);
echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>';
print_r($vals);
Result:
No. of NON Duplicate Items: 7
Array
(
[12] => 1
[43] => 6
[66] => 1
[21] => 2
[56] => 1
[78] => 2
[100] => 1
)
Edit the tty configuration in /etc/init/tty*.conf
with a shellscript as a parameter :
(...)
exec /sbin/getty -n -l theInputScript.sh -8 38400 tty1
(...)
This is assuming that we're editing tty1 and the script that reads input is theInputScript.sh.
A word of warning this script is run as root, so when you are inputing stuff to it you have root priviliges. Also append a path to the location of the script.
Important: the script when it finishes, has to invoke the /sbin/login otherwise you wont be able to login in the terminal.
You need to run Perfmon (start->control panel->administrative tools->performance). The counters you want, I believe, are in SQL Server:Memory Manager. Target Server Memory is how much it's allowed to take if needed, Total Server Memory is how much it's currently using. If you click on Explain it'll pop open a box with the details.
By default it's uncapped, and should use all but a couple gb of memory (it leaves that for the OS). However, there are various bugs and memory leaks that can cause it to go into paging.
This is interesting, and at the risk of getting this down-voted for putting in my opinion, as I am born deaf, being asked a question like that would require more effort in communicating my thoughts on my part personally.
To be blunt, I really would not read too much of the typical questions, as the underlying paradigm is 'How well can you vocalize your thoughts and understanding?', that is really what the interviewer is looking for. Communicating is always my biggest weakness due to the way I am and can get frustrated quite easily.
It would be ideal to have the knowledge and be the know-it-all type but unfortunately, there are some things I don't know, but not to be afraid if you actually don't know the answer and admit it rather than bluff through it. If an interviewer asked me a question like one of the above, that I would not be sure of or mis-understand/mis-interpret the question, I would say it upfront, which can personally be embarrassing, but have learnt to handle that.
You would be surprised at how many would actually waffle on and bluff through it in which at the end of the day get caught out with their 'pants down' metaphorically speaking.
My 2cents, Best regards, Tom.
Well, you can do
DataTable data = (DataTable)(dgvMyMembers.DataSource);
and then use
data.Columns.Remove(...);
I think it's the fastest way. This will modify data source table, if you don't want it, then copy of table is reqired. Also be aware that DataGridView.DataSource
is not necessarily of DataTable
type.
There are two stages for how events propagate. These are called "capturing" and "bubbling".
| | / \
---------------| |----------------- ---------------| |-----------------
| element1 | | | | element1 | | |
| -----------| |----------- | | -----------| |----------- |
| |element2 \ / | | | |element2 | | | |
| ------------------------- | | ------------------------- |
| Event CAPTURING | | Event BUBBLING |
----------------------------------- -----------------------------------
The capturing stage happen first, and are then followed by the bubbling stage. When you register an event using the regular DOM api, the events will be part of the bubbling stage by default, but this can be specified upon event creation
// CAPTURING event
button.addEventListener('click', handleClick, true)
// BUBBLING events
button.addEventListener('click', handleClick, false)
button.addEventListener('click', handleClick)
In React, bubbling events are also what you use by default.
// handleClick is a BUBBLING (synthetic) event
<button onClick={handleClick}></button>
// handleClick is a CAPTURING (synthetic) event
<button onClickCapture={handleClick}></button>
function handleClick(e) {
// This will prevent any synthetic events from firing after this one
e.stopPropagation()
}
function handleClick(e) {
// This will set e.defaultPrevented to true
// (for all synthetic events firing after this one)
e.preventDefault()
}
If you call e.preventDefault() in all of your events, you can check if an event has already been handled, and prevent it from being handled again:
handleEvent(e) {
if (e.defaultPrevented) return // Exits here if event has been handled
e.preventDefault()
// Perform whatever you need to here.
}
For the difference between synthetic events and native events, see the React documentation: https://reactjs.org/docs/events.html
Dont define varibale in header file , do declaration in header file(good practice ) .. in your case it is working because multiple weak symbols .. Read about weak and strong symbol ....link :http://csapp.cs.cmu.edu/public/ch7-preview.pdf
This type of code create problem while porting.
To exclude the first line (header) from sorting, I split it out into two buffers.
df | awk 'BEGIN{header=""; $body=""} { if(NR==1){header=$0}else{body=body"\n"$0}} END{print header; print body|"sort -nk3"}'
Fun fact, in objective-c if you want to check null / nil For example:
-(NSString*) getSomeStringSafeCheck
{
NSString *string = [self getSomeString];
if(string != nil){
return String;
}
return @"";
}
The quick way to do it is:
-(NSString*) getSomeStringSafeCheck
{
return [self getSomeString] != nil ? [self getSomeString] : @"";
}
Then you can update it to a simplest way:
-(NSString*) getSomeStringSafeCheck
{
return [self getSomeString]?: @"";
}
Because in Objective-C:
So let say you write:
[self getSomeString] != nil?: @"";
the second parameter is returning a boolean value, thus a exception is thrown.
<ng-include src="'views/sidepanel.html'"></ng-include>
OR
<div ng-include="'views/sidepanel.html'"></div>
OR
<div ng-include src="'views/sidepanel.html'"></div>
Points To Remember:
--> No spaces in src
--> Remember to use single quotation in double quotation for src
An alternative to the already provided ways is to simply filter on the column like so
df = df.where(F.col('columnNameHere').isNull())
This has the added benefit that you don't have to add another column to do the filtering and it's quick on larger data sets.
I'm very late to this and I have no idea if this is a good idea, but you can include the $attrs
injectable in the controller function allowing the controller to be initialized using "arguments" provided on an element, e.g.
app.controller('modelController', function($scope, $attrs) {
if (!$attrs.model) throw new Error("No model for modelController");
// Initialize $scope using the value of the model attribute, e.g.,
$scope.url = "http://example.com/fetch?model="+$attrs.model;
})
<div ng-controller="modelController" model="foobar">
<a href="{{url}}">Click here</a>
</div>
Again, no idea if this is a good idea, but it seems to work and is another alternative.
Java 17 comes with a utility to convert byte arrays and numbers to their hexadecimal counterparts. Let's say we have an MD5 digest of "Hello World" as a byte-array:
var md5 = MessageDigest.getInstance("md5");
md5.update("Hello world".getBytes(UTF_8));
var digest = md5.digest();
Now we can use the HexFormat.of().formatHex(byte[])
method to convert the given byte[]
to its hexadecimal form:
jshell> HexFormat.of().formatHex(digest)
$7 ==> "3e25960a79dbc69b674cd4ec67a72c62"
The withUpperCase()
method returns the uppercase version of the previous output:
jshell> HexFormat.of().withUpperCase().formatHex(digest)
$8 ==> "3E25960A79DBC69B674CD4EC67A72C62"
Definitely. Think of it as a dictionary or associative array. You can add to it at any point.
There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.
Given a class with this definition:
public class Class1
{
private int CallMe()
{
return 1;
}
}
You can invoke it using this code:
Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);
int result = (int)callMeMethod.Invoke(c, null);
Console.WriteLine(result);
If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..."
Add an identity column (PeopleID) and then use a correlated subquery to return the first value for each value.
SELECT *
FROM People p
WHERE PeopleID = (
SELECT MIN(PeopleID)
FROM People
WHERE IDNo = p.IDNo
)
just create the empty reference on link such as following
<a href="" onclick="dummy(0);return false;" >
Although this is an old thread, I got this error as well and the solution that worked for me is not mentioned here.
Simply put, in my case the webcam was still in use on the background, as I saw the LED light being on. I have not yet been able to reproduce the issue, so I'm not sure a simple cv2.VideoCapture(0).release()
would have solved it. I'll edit this post if and when I have found it out.
For me a restart of my PC solved the issue, without changing anything to the code.
You can follow the maven documentation to run the unit tests with the build and run the integration tests separately.
<project>
<properties>
<skipTests>true</skipTests>
</properties>
[...]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.20.1</version>
<configuration>
<skipITs>${skipTests}</skipITs>
</configuration>
</plugin>
</plugins>
</build>
[...]
</project>
This will allow you to run with all integration tests disabled by default. To run them, you use this command:
mvn install -DskipTests=false
The easiest way to do this, with excellent performance and compatibility with both old and new browsers, is to include either Lo-Dash or Underscore in your page.
Then you can use either _.size(object)
or _.keys(object).length
For your obj.Data
, you could test this with:
console.log( _.size(obj.Data) );
or:
console.log( _.keys(obj.Data).length );
Lo-Dash and Underscore are both excellent libraries; you would find either one very useful in your code. (They are rather similar to each other; Lo-Dash is a newer version with some advantanges.)
Alternatively, you could include this function in your code, which simply loops through the object's properties and counts them:
function ObjectLength( object ) {
var length = 0;
for( var key in object ) {
if( object.hasOwnProperty(key) ) {
++length;
}
}
return length;
};
You can test this with:
console.log( ObjectLength(obj.Data) );
That code is not as fast as it could be in modern browsers, though. For a version that's much faster in modern browsers and still works in old ones, you can use:
function ObjectLength_Modern( object ) {
return Object.keys(object).length;
}
function ObjectLength_Legacy( object ) {
var length = 0;
for( var key in object ) {
if( object.hasOwnProperty(key) ) {
++length;
}
}
return length;
}
var ObjectLength =
Object.keys ? ObjectLength_Modern : ObjectLength_Legacy;
and as before, test it with:
console.log( ObjectLength(obj.Data) );
This code uses Object.keys(object).length
in modern browsers and falls back to counting in a loop for old browsers.
But if you're going to all this work, I would recommend using Lo-Dash or Underscore instead and get all the benefits those libraries offer.
I set up a jsPerf that compares the speed of these various approaches. Please run it in any browsers you have handy to add to the tests.
Thanks to Barmar for suggesting Object.keys
for newer browsers in his answer.
Set setHasMenuOptions(true)
works if application has a theme with Actionbar
such as Theme.MaterialComponents.DayNight.DarkActionBar
or Activity has it's own Toolbar, otherwise onCreateOptionsMenu
in fragment does not get called.
If you want to use standalone Toolbar you either need to get activity and set your Toolbar as support action bar with
(requireActivity() as? MainActivity)?.setSupportActionBar(toolbar)
which lets your fragment onCreateOptionsMenu to be called.
Other alternative is, you can inflate your Toolbar's own menu with toolbar.inflateMenu(R.menu.YOUR_MENU)
and item listener with
toolbar.setOnMenuItemClickListener {
// do something
true
}
public boolean isAlertPresent() {
try
{
driver.switchTo().alert();
system.out.println(" Alert Present");
}
catch (NoAlertPresentException e)
{
system.out.println("No Alert Present");
}
}
There is a limit on the number of half-open connections, but afaik not for active connections. Although it appears to depend on the type of Windows 2008 server, at least according to this MSFT employee:
It depends on the edition, Web and Foundation editions have connection limits while Standard, Enterprise, and Datacenter do not.
To extend the previous answer even more, like Ankit was saying, for complex objects you need to implement Serializable. For example, for the simple object:
public class MyClass implements Serializable {
private static final long serialVersionUID = -2163051469151804394L;
private int id;
private String created;
}
In you FromFragment:
Bundle args = new Bundle();
args.putSerializable(TAG_MY_CLASS, myClass);
Fragment toFragment = new ToFragment();
toFragment.setArguments(args);
getFragmentManager()
.beginTransaction()
.replace(R.id.body, toFragment, TAG_TO_FRAGMENT)
.addToBackStack(TAG_TO_FRAGMENT).commit();
in your ToFragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
MyClass myClass = (MyClass) args
.getSerializable(TAG_MY_CLASS);
Maybe this code could help:
lastBusDay = datetime.datetime.today()
shift = datetime.timedelta(max(1,(lastBusDay.weekday() + 6) % 7 - 3))
lastBusDay = lastBusDay - shift
The idea is that on Mondays yo have to go back 3 days, on Sundays 2, and 1 in any other day.
The statement (lastBusDay.weekday() + 6) % 7
just re-bases the Monday from 0 to 6.
Really don't know if this will be better in terms of performance.
Short answer: No, the statement in the currently accepted answer is NOT accurate: "The general consensus is that you do not (should not) need to dispose of HttpClient".
Long answer: BOTH of the following statements are true and achieveable at the same time:
IDisposable
object is supposed/recommended to be disposed.And they DO NOT NECESSARILY CONFLICT with each other. It is just a matter of how you organize your code to reuse an HttpClient
AND still dispose it properly.
An even longer answer quoted from my another answer:
It is not a coincidence to see people
in some blog posts blaming how HttpClient
's IDisposable
interface
makes them tend to use the using (var client = new HttpClient()) {...}
pattern
and then lead to exhausted socket handler problem.
I believe that comes down to an unspoken (mis?)conception: "an IDisposable object is expected to be short-lived".
HOWEVER, while it certainly looks like a short-lived thing when we write code in this style:
using (var foo = new SomeDisposableObject())
{
...
}
the official documentation on IDisposable
never mentions IDisposable
objects have to be short-lived.
By definition, IDisposable is merely a mechanism to allow you to release unmanaged resources.
Nothing more. In that sense, you are EXPECTED to eventually trigger the disposal,
but it does not require you to do so in a short-lived fashion.
It is therefore your job to properly choose when to trigger the disposal, base on your real object's life cycle requirement. There is nothing stopping you from using an IDisposable in a long-lived way:
using System;
namespace HelloWorld
{
class Hello
{
static void Main()
{
Console.WriteLine("Hello World!");
using (var client = new HttpClient())
{
for (...) { ... } // A really long loop
// Or you may even somehow start a daemon here
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
With this new understanding, now we revisit that blog post,
we can clearly notice that the "fix" initializes HttpClient
once but never dispose it,
that is why we can see from its netstat output that,
the connection remains at ESTABLISHED state which means it has NOT been properly closed.
If it were closed, its state would be in TIME_WAIT instead.
In practice, it is not a big deal to leak only one connection open after your entire program ends,
and the blog poster still see a performance gain after the fix;
but still, it is conceptually incorrect to blame IDisposable and choose to NOT dispose it.
I was just having this problem on Windows 10 and the issue in my case was that I was just running psql
and it was defaulting to trying to log in with my Windows username ("Nathan"), but there was no PostgreSQL user with that name, and it wasn't telling me that.
So the solution was to run psql -U postgres
rather than just psql
, and then the password I entered at installation worked.
I know this is tagged html/css only, but you can't do that with css only. Easiest way will be using some jQuery.
var fixmeTop = $('.fixme').offset().top; // get initial position of the element
$(window).scroll(function() { // assign scroll event listener
var currentScroll = $(window).scrollTop(); // get current position
if (currentScroll >= fixmeTop) { // apply position: fixed if you
$('.fixme').css({ // scroll to that element or below it
position: 'fixed',
top: '0',
left: '0'
});
} else { // apply position: static
$('.fixme').css({ // if you scroll above it
position: 'static'
});
}
});
Try this: tar -cf file.tar file-to-compress ; xz -z file.tar
Note:
|
because this runs commands simultaneously. Using ;
or &
executes commands one after another.collection : A collection(with small 'c') represents a group of objects/elements.
Collection
: The root interface of Java Collections Framework.
Collections
: A utility class that is a member of the Java Collections Framework.
You are not correct. dict
access is unlikely to be your problem here. It is almost certainly O(1), unless you have some very weird inputs or a very bad hashing function. Paste some sample code from your application for a better diagnosis.
The easiest way to fix this was to press (CTRL) and (,) in VS Code to open Settings.
After that, on the search bar search for code runner, then scroll down and search for Run In Terminal and check that box as highlighted in the below image:
There is a good explanation at https://stackoverflow.com/a/33833319/903783
The values expected seem to be xlCopy and xlCut according to xlCutCopyMode enumeration (https://msdn.microsoft.com/en-us/VBA/Excel-VBA/articles/xlcutcopymode-enumeration-excel), but the 0 value (this is what False equals to in VBA) seems to be useful to clear Excel data put on the Clipboard.
There are a couple ways. Some of the ways that have been mentioned include (I think) tmux, screen, vim, emacs, and the shell. I don't know emacs or screen, so I'll go over the other three.
While not an X selection, tmux has a copy mode accessible via prefix-[
(prefix
is Ctrl+B by default). The buffer used for this mode is separate and exclusive to tmux, which opens up quite a few possibilities and makes it more versatile than the X selections in the right situations.
To exit this mode, hit q; to navigate, use your vim
or emacs
binding (default = vim), so hjkl
for movement, v/V/C-v
for character/line/block selection, etc. When you have your selection, hit Enter to copy and exit the mode.
To paste from this buffer, use prefix-]
.
Any installation of X11
seems to come with two programs by default: xclip
and xsel
(kinda like how it also comes with both startx
and xinit
). Most of the other answers mention xclip
, and I really like xsel
for its brevity, so I'm going to cover xsel
.
From xsel(1x):
Input options
-a, --append
append standard input to the selection. Implies -i.
-f, --follow
append to selection as standard input grows. Implies -i.
-i, --input
read standard input into the selection.
Output options
-o, --output
write the selection to standard output.
Action options
-c, --clear
clear the selection. Overrides all input options.
-d, --delete
Request that the current selection be deleted. This not only clears the selection, but also requests to the program in which the selection resides that the selected contents be deleted. Overrides all input options.
Selection options
-p, --primary
operate on the PRIMARY selection (default).
-s, --secondary
operate on the SECONDARY selection.
-b, --clipboard
operate on the CLIPBOARD selection.
And that's about all you need to know. p
(or nothing) for PRIMARY
, s
for SECONDARY
, b
for CLIPBOARD
, o
for output.
Example: say I want to copy the output of foo
from a TTY and paste it to a webpage for a bug report. To do this, it would be ideal to copy to/from the TTY/X session. So the question becomes how do I access the clipboard from the TTY?
For this example, we'll assume the X session is on display :1
.
$ foo -v
Error: not a real TTY
details:
blah blah @ 0x0000000040abeaf4
blah blah @ 0x0000000040abeaf8
blah blah @ 0x0000000040abeafc
blah blah @ 0x0000000040abeb00
...
$ foo -v | DISPLAY=:1 xsel -b # copies it into clipboard of display :1
Then I can Ctrl-V
it into the form as per usual.
Now say that someone on the support site gives me a command to run to fix the problem. It's complicated and long.
$ DISPLAY=:1 xsel -bo
sudo foo --update --clear-cache --source-list="http://foo-software.com/repository/foo/debian/ubuntu/xenial/164914519191464/sources.txt"
$ $(DISPLAY=:1 xsel -bo)
Password for braden:
UPDATING %%%%%%%%%%%%%%%%%%%%%%% 100.00%
Clearing cache...
Fetching sources...
Reticulating splines...
Watering trees...
Climbing mountains...
Looking advanced...
Done.
$ foo
Thank you for your order. A pizza should arrive at your house in the next 20 minutes. Your total is $6.99
Pizza ordering seems like a productive use of the command line.
...moving on.
If compiled with +clipboard
(This is important! Check your vim --version
), Vim should have access to the X PRIMARY
and CLIPBOARD
selections. The two selections are accessible from the *
and +
registers, respectively, and may be written to and read from at your leisure the same as any other register. For example:
:%y+ ; copy/yank (y) everything (%) into the CLIPBOARD selection (+)
"+p ; select (") the CLIPBOARD selection (+) and paste/put it
ggVG"+y ; Alternative version of the first example
If your copy of vim doesn't directly support access to X selections, though, it's not the end of the world. You can just use the xsel
technique as described in the last section.
:r ! xsel -bo ; read (r) from the stdout of (!) `xsel -bo`
:w ! xsel -b ; write (w) to the stdin of (!) `xsel -b`
Bind a couple key combos and you should be good.
explode('.', $string)
If you know your string has a fixed number of components you could use something like
list($a, $b) = explode('.', 'object.attribute');
echo $a;
echo $b;
Prints:
object
attribute
I wouldn't try to temporarily enable a deprecated feature. According to the MDN documentation for showModalDialog, there's already a polyfill available on Github.
I just used that to add windows.showModalDialog
to a legacy enterprise application as a userscript, but you can obviously also add it in the head of the HTML if you have access to the source.
Update: Though the below compiles, it throws a ArrayStoreException
at runtime. Too bad. I'll let it stay for future reference.
Converting an int[]
, to an Integer[]
:
int[] old;
...
Integer[] arr = new Integer[old.length];
System.arraycopy(old, 0, arr, 0, old.length);
I must admit I was a bit surprised that this compiles, given System.arraycopy
being lowlevel and everything, but it does. At least in java7.
You can convert the other way just as easily.
Try this
ImageView img
Bitmap bmp;
int width=100;
int height=100;
img=(ImageView)findViewById(R.id.imgView);
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.image);//image is your image
bmp=Bitmap.createScaledBitmap(bmp, width,height, true);
img.setImageBitmap(bmp);
Or If you want to load complete image size in memory then you can use
<ImageView
android:id="@+id/img"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/image"
android:scaleType="fitXY"/>
The solution posted by @Linga:
"Get-ChildItem -Recurse 'directory_path' | Measure-Object -Property Length -Sum"
is nice and short. However, it only computes the size of 'directory_path'
, without sub-directories.
Here is a simple solution for listing all sub-directory sizes. With a little pretty-printing added.
(Note: use the -File
option to avoid errors for empty sub-directories)
foreach ($d in gci -Directory -Force) {
'{0:N0}' -f ((gci $d -File -Recurse -Force | measure length -sum).sum) + "`t`t$d"
}
What you can do is
RelationActiveEnum ae = Enum.valueOf(RelationActiveEnum.class,
RelationActiveEnum.ACTIVE.name();
or
RelationActiveEnum ae = RelationActiveEnum.valueOf(
RelationActiveEnum.ACTIVE.name();
or
// not recommended as the ordinal might not match the value
RelationActiveEnum ae = RelationActiveEnum.values()[
RelationActiveEnum.ACTIVE.value];
By if you want to lookup by a field of an enum you need to construct a collection such as a List, an array or a Map.
public enum RelationActiveEnum {
Invited(0),
Active(1),
Suspended(2);
private final int code;
private RelationActiveEnum(final int code) {
this.code = code;
}
private static final Map<Integer, RelationActiveEnum> BY_CODE_MAP = new LinkedHashMap<>();
static {
for (RelationActiveEnum rae : RelationActiveEnum.values()) {
BY_CODE_MAP.put(rae.code, rae);
}
}
public static RelationActiveEnum forCode(int code) {
return BY_CODE_MAP.get(code);
}
}
allows you to write
String name = RelationActiveEnum.forCode(RelationActiveEnum.ACTIVE.code).name();
In your codethis
refers to the select element not to the selected option
to refer the selected option you can do this -
$(this).find('option:selected').attr("name");
I had this exact same problem in VS 2015
. It looks like as of VS 2010
and later you need to include #include "stdafx.h"
in all your projects.
#include "stdafx.h"
#include <iostream>
using namespace std;
The above worked for me. The below did not:
#include <iostream>
using namespace std;
This also failed:
#include <iostream>
using namespace std;
#include "stdafx.h"
In order to do this your JavaScript file would need to be pre-processed on the server side. Essentially, it would have to become an ASP.NET View of some kind, and script
tags which reference the file would essentially be referencing a controller action which responds with that view.
That sounds like a can of worms you don't want to open.
Since JavaScript is client-side, why not just set the value to some client-side element and have the JavaScript interact with that. It's perhaps an additional step of indirection, but it sounds like much less of a headache than creating a JavaScript view.
Something like this:
<script type="text/javascript">
var someValue = @ViewBag.someValue
</script>
Then the external JavaScript file can reference the someValue
JavaScript variable within the scope of that document.
Or even:
<input type="hidden" id="someValue" value="@ViewBag.someValue" />
Then you can access that hidden input.
Unless you come up with some really slick way to actually make your JavaScript file usable as a view. It's certainly doable, and I can't readily think of any problems you'd have (other than really ugly view code since the view engine will get very confused as to what's JavaScript and what's Razor... so expect a ton of <text>
markup), so if you find a slick way to do it that would be pretty cool, albeit perhaps unintuitive to someone who needs to support the code later.
A simple trick that works for me is the following:
Example:
import matplotlib.pyplot as plt
plt.imshow(add_something)
plt.xlabel("x")
plt.ylabel("y")
plt.show(block=False)
#more code here (e.g. do calculations and use print to see them on the screen
plt.show()
Note: plt.show()
is the last line of my script.
pmg is spot on about encapsulation; beyond hiding the function from other translation units (or rather, because of it), making functions static
can also confer performance benefits in the presence of compiler optimizations.
Because a static
function cannot be called from anywhere outside of the current translation unit (unless the code takes a pointer to its address), the compiler controls all the call points into it.
This means that it is free to use a non-standard ABI, inline it entirely, or perform any number of other optimizations that might not be possible for a function with external linkage.
On ubuntu you can add this PPA Repository and use it to install python 3.7: https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.7
Or a different PPA that provides several Python versions is Deadsnakes: https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa
See also here: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get (I know it says 3.6 in the url, but the deadsnakes ppa also contains 3.7 so you can use it for 3.7 just the same)
If you want "official" you'd have to install it from the sources from the site, get the code (which you already downloaded) and do this:
tar -xf Python-3.7.0.tar.xz
cd Python-3.7.0
./configure
make
sudo make install <-- sudo is required.
This might take a while
try this:
SELECT
COUNT(program_name) AS [Count],program_type AS [Type]
FROM (SELECT DISTINCT program_name,program_type
FROM cm_production
WHERE push_number=@push_number
) dt
GROUP BY program_type
Copy this script to notepad and save as .vbs file. Drag&Drop .js files on this script.
ps. This will work only on windows.
set objArgs = Wscript.Arguments
set objFso = CreateObject("Scripting.FileSystemObject")
content = ""
'Iterate through all the arguments passed
for i = 0 to objArgs.count
on error resume next
'Try and treat the argument like a folder
Set folder = objFso.GetFolder(objArgs(i))
'If we get an error, we know it is a file
if err.number <> 0 then
'This is not a folder, treat as file
content = content & ReadFile(objArgs(i))
else
'No error? This is a folder, process accordingly
for each file in folder.Files
content = content & ReadFile(file.path)
next
end if
on error goto 0
next
'Get system Temp folder path
set tempFolderPath = objFso.GetSpecialFolder(2)
'Generate a random filename to use for a temporary file
strTempFileName = objFso.GetTempName
'Create temporary file in Temp folder
set objTempFile = tempFolderPath.CreateTextFile(strTempFileName)
'Write content from JavaScript files to temporary file
objTempFile.WriteLine(content)
objTempFile.Close
'Open temporary file in Notepad
set objShell = CreateObject("WScript.Shell")
objShell.Run("Notepad.exe " & tempFolderPath & "\" & strTempFileName)
function ReadFile(strFilePath)
'If file path ends with ".js", we know it is JavaScript file
if Right(strFilePath, 3) = ".js" then
set objFile = objFso.OpenTextFile(strFilePath, 1, false)
'Read entire contents of a JavaScript file and returns it as a string
ReadFile = objFile.ReadAll & vbNewLine
objFile.Close
else
'Return empty string
ReadFile = ""
end if
end function
This is the way I am requesting User Permissions.
Outside your application tag in AndroidManifest.xml add these permission requests.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Then add Google's Location dependencies in the App Gradle file.
implementation 'com.google.android.gms:play-services-location:15.0.0'
Now declare some Global variables.
private lateinit var mFusedLocationProvider:FusedLocationProviderClient
private lateinit var mLocationCallback: LocationCallback
private lateinit var mLocationRequest: LocationRequest
private var mLocationPermissionGranted:Boolean = false
In OnCreate method of your Activity (I was not able to Format the Code Properly, Apology for that)
mFusedLocationProvider = LocationServices.getFusedLocationProviderClient(this)
//Location Callback
mLocationCallback = object: LocationCallback(){
override fun onLocationResult(p0: LocationResult?) {
if(p0==null){
//todo(request user to enable location from settings then remove return)
return
}else{
getDeviceLocation()
}
}
}
//Location Request
mLocationRequest = LocationRequest.create()
mLocationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
//Set the Interval for Latest Interval Update
mLocationRequest.interval = 5000
//Set How Many Location Updated you Want
mLocationRequest.numUpdates = 1
getLocationPermission()
getDeviceLocation()
Now create both the functions.
private fun getLocationPermission() {
val permission:Array<String> = arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION)
if(ContextCompat.checkSelfPermission(applicationContext,Constant.FINE_LOCATION)== PermissionChecker.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(applicationContext,Constant.COARSE_LOCATION)== PermissionChecker.PERMISSION_GRANTED){
mLocationPermissionGranted = true
}
}else{
ActivityCompat.requestPermissions(this,permission,Constant.LOCATION_REQUEST_CODE)
}
}
Second Method
private fun getDeviceLocation() {
try{
if(mLocationPermissionGranted){
mFusedLocationProvider.lastLocation.addOnCompleteListener(this,{task: Task<Location> ->
if(task.isSuccessful){
var currentLocation: Location? = task.result
if(currentLocation!=null){
Log.i("Location","Latitude is ${currentLocation.latitude} and Longitude" +
"${currentLocation.longitude}")
}
else
mFusedLocationProvider.requestLocationUpdates(mLocationRequest,mLocationCallback,null)
}
})
}
}catch (e:SecurityException){
Log.e("Error", "Security Exception ${e.message}")
}
}
For Constant.kt
class Constant{
companion object {
//Location Request Settings
const val SET_INTERVAL:Long = 2000
const val NUM_UPDATES:Int = 1
//Location Permission
const val FINE_LOCATION:String = android.Manifest.permission.ACCESS_FINE_LOCATION
const val COARSE_LOCATION:String = android.Manifest.permission.ACCESS_COARSE_LOCATION
}
}
From Avinash Kumar Pankaj's example
View v;
then at oncreate method
v = new View(getActivity());
and then onlistitemclick method i wrote
public void onListItemClick(ListView listView, View view, int position,
long id) {
v.setBackgroundResource(0);
view.setBackgroundResource(R.color.green);
v = view;
}
It worked for me. Thank you.
I replaced
v = new View(getActivity());
to
v = new View(this);
and the code worked well.
It is necessary the xml files 'colors' and 'bg_key' from previous examples too, as well as ListView attribute android:background="@drawable/bg_key"
Mauro
I think it's a matter of personal preference. I prefer to do it in the following way:
var /* Variables */
me = this, that = scope,
temp, tempUri, tempUrl,
videoId = getQueryString()["id"],
host = location.protocol + '//' + location.host,
baseUrl = "localhost",
str = "Visit W3Schools",
n = str.search(/w3schools/i),
x = 5,
y = 6,
z = x + y
/* End Variables */;
My preferred is:
This will have some overhead, but technically it does answer your question
echo abc `#put your comment here` \ def `#another chance for a comment` \ xyz etc
And for pipelines specifically, there is a cleaner solution with no overhead
echo abc | # normal comment OK here tr a-z A-Z | # another normal comment OK here sort | # the pipelines are automatically continued uniq # final comment
You have to send
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated
to the picker view before it appears. The documentation states that the method selectedRowInComp... will give -1, thus it is possible that the picker view is in a state with no selected row. It turns out to be in that state when created.
Like @endeR mentioned, if internationalization is a concern, the unicode_utils gem is more than adequate.
$ gem install unicode_utils
$ irb
> require 'unicode_utils'
=> true
> UnicodeUtils.downcase("FEN BILIMLERI", :tr)
=> "fen bilimleri"
String manipulations in Ruby 2.4 are now unicode-sensitive.
This might be the simplest answer and maybe it don't work in all cases, but it is working great for me:
while read line;do echo "$line";done<peptides.txt
if you need to enclose in parenthesis for spaces:
while read line;do echo \"$line\";done<peptides.txt
Ahhh this is pretty much the same as the answer that got upvoted most, but its all on one line.
This will work for most of the website names :
SELECT ID, REVERSE(PARSENAME(REVERSE(WebsiteName), 2)) FROM dbo.YourTable .....
You can use vscode with GitLens, it's a very powerful tool.
After installed GitLens, go to GitLens tab, select FILE HISTORY
and you can browse it.
Steps for BitBucket:
if you dont want to generate new key, SKIP ssh-keygen
ssh-keygen -t rsa
Copy the public key to clipboard:
clip < ~/.ssh/id_rsa.pub
Login to Bit Bucket: Go to View Profile -> Settings -> SSH Keys (In Security tab) Click Add Key, Paste the key in the box, add a descriptive title
Go back to Git Bash :
ssh-add -l
You should get :
2048 SHA256:5zabdekjjjaalajafjLIa3Gl/k832A /c/Users/username/.ssh/id_rsa (RSA)
Now: git pull
should work
It is very straight forward
HTML
<input type="text" placeholder="some text" />
<input type="button" value="button" class="button"/>
<button class="button">Another button</button>
jQuery
$(document).ready(function(){
$('.button').css( 'cursor', 'pointer' );
// for old IE browsers
$('.button').css( 'cursor', 'hand' );
});
Angularjs With Javascript Delete Example
html code
<button ng-click="ConfirmDelete(single_play.play_id)" type="submit" name="actiondelete" value="1"><img src="images/remove.png" alt="Delete"></button>
"single_play.play_id" is any angularjs variable suppose you want to pass any parameter during the delete action
Angularjs code inside the app module
$scope.ConfirmDelete = function(yy)
{
var x = confirm("Are you sure you want to delete?");
if (x) {
// Action for press ok
$http({
method : 'POST',
url : 'sample.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({ delete_play_id : yy})
}).then(function (response) {
$scope.message = response.data;
});
}
else {
//Action for cancel
return false;
}
}
Nope, you'd just have to create your own function:
function printr($data) {
echo "<pre>";
print_r($data);
echo "</pre>";
}
Apparantly, in 2018, people are still coming back to this question. The above would not be my current answer. I'd say: teach your editor to do it for you. I have a whole bunch of debug shortcuts, but my most used is vardd
which expands to: var_dump(__FILE__ . ':' . __LINE__, $VAR$);die();
You can configure this in PHPStorm as a live template.
Also you can use Lodash to direct convert object to array:
_.toArray({0:{a:4},1:{a:6},2:{a:5}})
[{a:4},{a:6},{a:5}]
In your case:
_.toArray(subjects).map((subject, i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">Name: {subject[name]}</span>
</li>
))}
First import the following
import Firebase
import FirebaseAuth
Then
// Check if logged in
if (Auth.auth().currentUser != null) {
// User is logged in
}else{
// User is not logged in
}
Cleaned up what chuycepeda has and put it into a textarea to send back in a form.
google.maps.event.addListener(drawingManager, 'overlaycomplete', function (event) {
var str_input = '{';
if (event.type == google.maps.drawing.OverlayType.POLYGON) {
$.each(event.overlay.getPath().getArray(), function (key, latlng) {
var lat = latlng.lat();
var lon = latlng.lng();
str_input += lat + ', ' + lon + ',';
});
}
str_input = str_input.substr(0, str_input.length - 1) + '}';
$('textarea#Geofence').val(str_input);
});
AGSM's answer shows a convenient way of solving this problem using the python-dateutil
package. But what if you don't want to install that package? You could solve the problem in vanilla Python like this:
from datetime import date
def add_years(d, years):
"""Return a date that's `years` years after the date (or datetime)
object `d`. Return the same calendar date (month and day) in the
destination year, if it exists, otherwise use the following day
(thus changing February 29 to March 1).
"""
try:
return d.replace(year = d.year + years)
except ValueError:
return d + (date(d.year + years, 1, 1) - date(d.year, 1, 1))
If you want the other possibility (changing February 29 to February 28) then the last line should be changed to:
return d + (date(d.year + years, 3, 1) - date(d.year, 3, 1))
You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.
You actually need 3 meta
tags to support Android, iPhone and Windows Phone
<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#4285f4">
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-status-bar-style" content="#4285f4">
function youtube_parser(url){
var match = url.match(/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/);
return (match&&match[7].length==11)?match[7]:false;
}
Shortest and Efficient
grep -n "YOUR SEARCH STRING" * > output-file
The -n
will print the line number and the >
will redirect grep-results to the output-file.
If you want to "clean" the results you can filter them using pipe |
for example:
grep -n "test" * | grep -v "mytest" > output-file
will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v
) - and will redirect the result to an output file.
A few good grep-tips can be found on this post
You can use the storage_path();
function to get storage folder path.
storage_path(); // Return path like: laravel_app\storage
Suppose you want to save your logfile mylog.log
inside Log folder of storage folder. You have to write something like
storage_path() . '/LogFolder/mylog.log'
REPEAT
...
UNTIL cond
Is equivalent to
while True:
...
if cond:
break
Pure JS solution is as follows:
function clearForm(myFormElement) {
var elements = myFormElement.elements;
myFormElement.reset();
for(i=0; i<elements.length; i++) {
field_type = elements[i].type.toLowerCase();
switch(field_type) {
case "text":
case "password":
case "textarea":
case "hidden":
elements[i].value = "";
break;
case "radio":
case "checkbox":
if (elements[i].checked) {
elements[i].checked = false;
}
break;
case "select-one":
case "select-multi":
elements[i].selectedIndex = -1;
break;
default:
break;
}
}
}
You almost never have to write your own loops in C++. Here, you can use std::find.
const int toFind = 42;
int* found = std::find (myArray, std::end (myArray), toFind);
if (found != std::end (myArray))
{
std::cout << "Found.\n"
}
else
{
std::cout << "Not found.\n";
}
std::end
requires C++11. Without it, you can find the number of elements in the array with:
const size_t numElements = sizeof (myArray) / sizeof (myArray[0]);
...and the end with:
int* end = myArray + numElements;
Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" )
. After the required positional arguments, you can specify specific optional arguments by name.
The problem is that tsc
is not in your PATH
if installed locally.
You should modify your .vscode/tasks.json
to include full path to tsc
.
The line to change is probably equal to "command": "tsc"
.
You should change it to "command": "node"
and add the following to your args: "args": ["${workspaceRoot}\\node_modules\\typescript\\bin\\tsc"]
(on Windows).
This will instruct VSCode to:
(that's pretty much what tsc
executable does)
Are you sure you don't want to install Typescript globally? It should make things easier, especially if you're just starting to use it.
I have implemented this function in my application through fragments using SurfaceView. The link to this stackoverflow question and its answer can be found here
Hope this helps :)
More generally, I think you might want to get "top" of the rows that are sorted within a given group.
For the case of where a single value is max'd out, you have essentially sorted by only one column. However, it's often useful to hierarchically sort by multiple columns (for example: a date column and a time-of-day column).
# Answering the question of getting row with max "value".
df %>%
# Within each grouping of A and B values.
group_by( A, B) %>%
# Sort rows in descending order by "value" column.
arrange( desc(value) ) %>%
# Pick the top 1 value
slice(1) %>%
# Remember to ungroup in case you want to do further work without grouping.
ungroup()
# Answering an extension of the question of
# getting row with the max value of the lowest "C".
df %>%
# Within each grouping of A and B values.
group_by( A, B) %>%
# Sort rows in ascending order by C, and then within that by
# descending order by "value" column.
arrange( C, desc(value) ) %>%
# Pick the one top row based on the sort
slice(1) %>%
# Remember to ungroup in case you want to do further work without grouping.
ungroup()
There was a previous question today (no answers) that gave a good example of this functionality. You can check the relevant source code for specifics (search for "toolbar"), but basically they use a combination of webdestroya's solution and a bit of JavaScript:
I'd recommend checking the aforementioned source code though, because they do handle some "gotchas" that you might not immediately think of, such as adjusting scroll position when clicking on anchor links.
Check your X Window environment variables using the "env" command.
$cfg['Servers'][$i]['host'] = '127.0.0.1:3307';
if u change port address
The recommended way to create random integers with NumPy these days is to use numpy.random.Generator.integers
. (documentation)
import numpy as np
import pandas as pd
rng = np.random.default_rng()
df = pd.DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list('ABCD'))
df
----------------------
A B C D
0 58 96 82 24
1 21 3 35 36
2 67 79 22 78
3 81 65 77 94
4 73 6 70 96
... ... ... ... ...
95 76 32 28 51
96 33 68 54 77
97 76 43 57 43
98 34 64 12 57
99 81 77 32 50
100 rows × 4 columns
Interesting question! While there are plenty of guides on horizontally and vertically centering a div, an authoritative treatment of the subject where the centered div is of an unpredetermined width is conspicuously absent.
Let's apply some basic constraints:
table-cell
, which is of questionable support statusGiven this, my entry into the fray is the use of the inline-block
display property to horizontally center the span within an absolutely positioned div of predetermined height, vertically centered within the parent container in the traditional top: 50%; margin-top: -123px
fashion.
Markup: div > div > span
CSS:
body > div { position: relative; height: XYZ; width: XYZ; }
div > div {
position: absolute;
top: 50%;
height: 30px;
margin-top: -15px;
text-align: center;}
div > span { display: inline-block; }
Source: http://jsfiddle.net/38EFb/
An alternate solution that doesn't require extraneous markups but that very likely produces more problems than it solves is to use the line-height property. Don't do this. But it is included here as an academic note: http://jsfiddle.net/gucwW/
Why use jQuery for this?
str = "123-4";
alert(str.substring(0,str.length - 1));
Of course if you must:
Substr w/ jQuery:
//example test element
$(document.createElement('div'))
.addClass('test')
.text('123-4')
.appendTo('body');
//using substring with the jQuery function html
alert($('.test').html().substring(0,$('.test').html().length - 1));
If the maximum number of digits in the counter is known (e.g., n = 3 for counters 1..876), you can do
str = "file_" + i.to_s.rjust(n, "0")
Why do you need to list the attributes? Seems that semantically your class is a collection. In this cases I recommend to use enum:
import enum
class myClass(enum.Enum):
a = "12"
b = "34"
List your attributes? Nothing easier than this:
for attr in myClass:
print("Name / Value:", attr.name, attr.value)
Safest method, which I use frequently:
git clean -fd
Syntax explanation as per /docs/git-clean
page:
-f
(alias: --force
). If the Git configuration variable clean.requireForce is not set to false, git clean will refuse to delete files or directories unless given -f, -n or -i. Git will refuse to delete directories with .git sub directory or file unless a second -f is given.-d
. Remove untracked directories in addition to untracked files. If an untracked directory is managed by a different Git repository, it is not removed by default. Use -f option twice if you really want to remove such a directory.As mentioned in the comments, it might be preferable to do a git clean -nd
which does a dry run and tells you what would be deleted before actually deleting it.
Link to git clean
doc page:
https://git-scm.com/docs/git-clean
There is no need to have two functions within one element, you need just one that calls the other two!
<a href="#" onclick="my_func()" >click</a>
function my_func() {
my_func_1();
my_func_2();
}
Constructor injection is used when the class cannot function without the dependent class.
Property injection is used when the class can function without the dependent class.
As a concrete example, consider a ServiceRepository which depends on IService to do its work. Since ServiceRepository cannot function usefully without IService, it makes sense to have it injected via the constructor.
The same ServiceRepository class may use a Logger to do tracing. The ILogger can be injected via Property injection.
Other common examples of Property injection are ICache (another aspect in AOP terminology) or IBaseProperty (a property in the base class).
The pack
method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize
or setBounds
(which also sets the frame location). In general, using pack is preferable to calling setSize
, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.
From Java tutorial
You should also refer to Javadocs any time you need additional information on any Java API
This is the method which i used to convert the integer to string.Correct me if i did wrong.
/**
* @param a
* @return
*/
private String convertToString(int a) {
int c;
char m;
StringBuilder ans = new StringBuilder();
// convert the String to int
while (a > 0) {
c = a % 10;
a = a / 10;
m = (char) ('0' + c);
ans.append(m);
}
return ans.reverse().toString();
}
Use this also
NSString *ChkStr = [MyString substringWithRange:NSMakeRange(5, 26)];
Note - Your NSMakeRange(start, end)
should be NSMakeRange(start, end- start)
;
The TortoiseSVN TSVN Manual is based on subversion book, but available in a lot more languages.
You never really specified how you wanted them disabled, or what would cause the disabling.
First, you want to figure out how to set the value to disabled, for that you would use JQuery's Attribute Functions, and have that function happen on an event, like a click, or the loading of the document.
You'll need to compile it using:
g++ inputfile.cpp -o outputbinary
The file you are referring has a missing #include <cstdlib>
directive, if you also include that in your file, everything shall compile fine.
Select the commit you would like to roll back to and reverse the changes by clicking Reverse File
, Reverse Hunk
or Reverse Selected Lines
. Do this for all the commits after the commit you would like to roll back to also.
Right click on the commit and click on Reset current branch to this commit
.
Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);
The following works how you want it, but it is not ideal.
public class Tester extends Activity {
String[] vals = { "here", "are", "some", "values" };
Spinner spinner;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner) findViewById(R.id.spin);
ArrayAdapter<String> ad = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, vals);
spinner.setAdapter(ad);
Log.i("", "" + spinner.getChildCount());
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
int a = spinner.getCount();
int b = spinner.getChildCount();
System.out.println("Count =" + a);
System.out.println("ChildCount =" + b);
for (int i = 0; i < b; i++) {
View v = spinner.getChildAt(i);
if (v == null) {
System.out.println("View not found");
} else {
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("","click");
}
});
}
}
}
}, 500);
}
}
Let me know exactly how you need the spinner to behave, and we can work out a better solution.
structure is collection of different data type where different type of data can reside in it and every one get its own block of memory
we usually used union when we sure that only one of the variable will be used at once and you want fully utilization of present memory because it get only one block of memory which is equal to the biggest type.
struct emp
{
char x;//1 byte
float y; //4 byte
} e;
total memory it get =>5 byte
union emp
{
char x;//1 byte
float y; //4 byte
} e;
total memory it get =4 byte
Plain ES6:
var foo = {
bar: "Yes"
};
const res = Object.keys(foo).filter(i => foo[i] === 'Yes')
console.log(res)
// ["bar"]
aws sync is the perfect solution. It does not do a two way.. it is a one way from source to destination. Also, if you have lots of items in bucket it will be a good idea to create s3 endpoint first so that download happens faster (because download does not happen via internet but via intranet) and no charges
An update to show how to do it in the recent versions of OpenCV:
import cv2
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
if vc.isOpened(): # try to get the first frame
rval, frame = vc.read()
else:
rval = False
while rval:
cv2.imshow("preview", frame)
rval, frame = vc.read()
key = cv2.waitKey(20)
if key == 27: # exit on ESC
break
cv2.destroyWindow("preview")
vc.release()
It works in OpenCV-2.4.2 for me.
NOTE: I am sharing this. It is not mean that here is not good answer but because I easily understood.
Answer:
When a class is conceptualized, what are the properties we can have in it given the context. If we are designing a class Animal in the context of a zoo, it is important that we have an attribute as animalType to describe domestic or wild. This attribute may not make sense when we design the class in a different context.
Similarly, what are the behaviors we are going to have in the class? Abstraction is also applied here. What is necessary to have here and what will be an overdose? Then we cut off some information from the class. This process is applying abstraction.
When we ask for difference between encapsulation and abstraction, I would say, encapsulation uses abstraction as a concept. So then, is it only encapsulation. No, abstraction is even a concept applied as part of inheritance and polymorphism.
Go here for more explanation about this topic.
Just another possible solution I found having the same error message.
When trying to setup a .NET 4.0 web application to a new applicition pool I was receiving this strange error telling me it was trying to process my aspx file with the static file handler, which didn't make sense.
For some reason the ISAPI for .NET 4.0 was set to disabled in the ISAPI and CGI Restrictions area of the server level in the IIS manager. Setting it to enabled was all that was required, however the IIS 7.5 manager is so convoluted and hard to follow it took me a long time to figure this out.
I'm guessing that since it was a 4.0 Application that could not be processed by the 4.0 Engine the static file handler was being used by default.
To print stacktrace of Error
in console in more readable way:
console.log(ex, ex.stack.split("\n"));
Example result:
[Error] [ 'Error',
' at repl:1:7',
' at REPLServer.self.eval (repl.js:110:21)',
' at Interface.<anonymous> (repl.js:239:12)',
' at Interface.EventEmitter.emit (events.js:95:17)',
' at Interface._onLine (readline.js:202:10)',
' at Interface._line (readline.js:531:8)',
' at Interface._ttyWrite (readline.js:760:14)',
' at ReadStream.onkeypress (readline.js:99:10)',
' at ReadStream.EventEmitter.emit (events.js:98:17)',
' at emitKey (readline.js:1095:12)' ]
The split work until 4000 chars depending on the characters that you are inserting. If you are inserting special characters it can fail. The only secure way is to declare a variable.
I don't know if this is good practice or not, but casting a Context object to an Activity object compiles fine.
Try this: ((Activity) mContext).startActivity(...)
Try this in git bash, to fetch and prune references to deleted branches, and then prune the local branches that were tracking the removed ones:
git fetch -p && git branch -d `git branch -vv | grep ': gone]' | awk '{print $1}' | xargs`
Remember to checkout first a branch that won't be deleted, so that does not block the deleting of the branch.
Download jansi-1.4.jar and Set classpath and Try This code 100% working :
import org.fusesource.jansi.AnsiConsole;
import static org.fusesource.jansi.Ansi.*;
import static org.fusesource.jansi.Ansi.Color.*;
public class SampleColour
{
public static void main(String[] args)
{
AnsiConsole.systemInstall();
System.out.println(ansi().fg(RED).a("Hello World").reset());
System.out.println("My Name is Raman");
AnsiConsole.systemUninstall();
}
}
I know it's been a little over two years... but I was looking for a way to do this, and wasn't overly happy with the solution posted (it works fine, but I wanted a little more information as the import happens). When combining all the SQL files in to one, you don't get any sort of progress updates.
So I kept digging for an answer and thought this might be a good place to post what I found for future people looking for the same answer. Here's a command line in Windows that will import multiple SQL files from a folder. You run this from the command line while in the directory where mysql.exe is located.
for /f %f in ('dir /b <dir>\<mask>') do mysql --user=<user> --password=<password> <dbname> < <dir>\%f
With some assumed values (as an example):
for /f %f in ('dir /b c:\sqlbackup\*.sql') do mysql --user=mylogin --password=mypass mydb < c:\sqlbackup\%f
If you had two sets of SQL backups in the folder, you could change the *.sql to something more specific (like mydb_*.sql).
Yes you need an encapsulating div:
<div id="logo"><img src="logo.jpg"></div>
with something like:
#logo { height: 100px; width: 200px; overflow: hidden; }
Other solutions (padding, margin) are more tedious (in that you need to calculate the right value based on the image's dimensions) but also don't effectively allow the container to be smaller than the image.
Also, the above can be adapted much more easily for different layouts. For example, if you want the image at the bottom right:
#logo { position: relative; height: 100px; width: 200px; }
#logo img { position: absolute; right: 0; bottom: 0; }
Go to the Sql tab run one of the below query:
delete from tableName;
Delete: will delete all rows from your table. Next insert will take next auto increment id.
or
truncate tableName;
Truncate: will also delete the rows from your table but it will start from new row with 1.
A detailed blog with example: http://sforsuresh.in/phpmyadmin-deleting-rows-mysql-table/
Just noting this here in case anyone else has a similar issue.
If you're directing a request directly to a JSP, using Apache Tomcat web.xml configuration, then ${requestScope.attr}
doesn't seem to work, instead ${param.attr}
contains the request attribute attr
.
This is best solution : https://developer.android.com/studio/write/tool-attributes
This is design attributes we can set activty context in xml like
tools:context=".activity.ActivityName"
Adapter:
tools:context="com.PackegaName.AdapterName"
You can navigate to java class when clicking on the marked icon and tools have more features like
tools:text=""
tools:visibility:""
tools:listItems=""//for recycler view
etx
Even though methai's answer is correct if you manually run the query, a problem occurs when 2 concurrent transaction/connections actually execute this query at runtime in production (for instance).
Just tried manually in MySQL workbench with 2 connections opened simultaneously:
CREATE TABLE translation (
id BIGINT PRIMARY KEY AUTO_INCREMENT
);
# Suppose we have already 20 entries, we execute 2 new inserts:
Transaction 1:
21 = SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName' AND TABLE_NAME = 'translation';
insert into translation (id) values (21);
Transaction 2:
21 = SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName' AND TABLE_NAME = 'translation';
insert into translation (id) values (21);
# commit transaction 1;
# commit transaction 2;
Insert of transaction 1 is ok: Insert of transaction 2 goes in error: Error Code: 1062. Duplicate entry '21' for key 'PRIMARY'.
A good solution would be jvdub's answer because per transaction/connection the 2 inserts will be:
Transaction 1:
insert into translation (id) values (null);
21 = SELECT LAST_INSERT_ID();
Transaction 2:
insert into translation (id) values (null);
22 = SELECT LAST_INSERT_ID();
# commit transaction 1;
# commit transaction 2;
But we have to execute the last_insert_id() just after the insert! And we can reuse that id to be inserted in others tables where a foreign key is expected!
Also, we cannot execute the 2 queries as following:
insert into translation (id) values ((SELECT AUTO_INCREMENT FROM
information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE()
AND TABLE_NAME='translation'));
because we actually are interested to grab/reuse that ID in other table or to return!
update q
set q.QuestionID = a.QuestionID
from QuestionTrackings q
inner join QuestionAnswers a
on q.AnswerID = a.AnswerID
where q.QuestionID is null -- and other conditions you might want
I recommend to check what the result set to update is before running the update (same query, just with a select):
select *
from QuestionTrackings q
inner join QuestionAnswers a
on q.AnswerID = a.AnswerID
where q.QuestionID is null -- and other conditions you might want
Particularly whether each answer id has definitely only 1 associated question id.
HOW TO MAKE PIPENV A BASIC COMMAND
Pipenv with Python3 needs to be run as "$ python -m pipenv [command]" or "$ python3 -m pipenv [command]"; the "python" command at the beginning varies based on how you activate Python in your shell. To fix and set to "$ pipenv [command]": [example in Git Bash]
$ cd ~
$ code .bash_profile
The first line is necessary as it allows you to access the .bash_profile file. The second line opens .bash_profile in VSCode, so insert your default code editor's command. At this point you'll want to (in .bash_profile) edit the file, adding this line of code:
alias pipenv='python -m pipenv'
Then save the file and into Git Bash, enter:
$ source .bash_profile
You can then use pipenv as a command anywhere, for example: $ pipenv shell Will work.
This method of usage will work for creating commands in Git Bash. For example:
alias python='winpty python.exe'
entered into the .bash_profile and: $ source .bash_profile will allow Python to be run as "python".
You're welcome.
The simplest way to do this is perhaps deleting the file via your application and creating a new one with the same name... in even simpler way just make your application overwrite it with a new file.
You can't use curlies (moustache tags) in attributes. Use the following to concat data:
<img v-bind:src="imgPreUrl + 'img/logo.png'">
Or the short version:
<img :src="imgPreUrl + 'img/logo.png'">
Read more on dynamic attributes in the Vue docs.
Assuming i understand your question.
You can get the selected row using the DataGridView.SelectedRows
Collection. If your DataGridView allows only one selected, have a look at my sample.
DataGridView.SelectedRows Gets the collection of rows selected by the user.
if (dataGridView1.SelectedRows.Count != 0)
{
DataGridViewRow row = this.dataGridView1.SelectedRows[0];
row.Cells["ColumnName"].Value
}
Why not just iterate through the string?
a_string="abcd"
for letter in a_string:
print letter
returns
a
b
c
d
So, in pseudo-ish code, I would do this:
user_string = raw_input()
list_of_output = []
for letter in user_string:
list_of_output.append(morse_code_ify(letter))
output_string = "".join(list_of_output)
Note: the morse_code_ify
function is pseudo-code.
You definitely want to make a list of the characters you want to output rather than just concatenating on them on the end of some string. As stated above, it's O(n^2): bad. Just append them onto a list, and then use "".join(the_list)
.
As a side note: why are you removing the spaces? Why not just have morse_code_ify(" ")
return a "\n"
?
Using display: flex
you can control the vertical alignment of HTML elements.
.box {_x000D_
height: 100px;_x000D_
display: flex;_x000D_
align-items: center; /* Vertical */_x000D_
justify-content: center; /* Horizontal */_x000D_
border:2px solid black;_x000D_
}_x000D_
_x000D_
.box div {_x000D_
width: 100px;_x000D_
height: 20px;_x000D_
border:1px solid;_x000D_
}
_x000D_
<div class="box">_x000D_
<div>Hello</div>_x000D_
<p>World</p>_x000D_
</div>
_x000D_
In neither case can you modify a string literal, regardless of whether the pointer to that string literal is declared as char *
or const char *
.
However, the difference is that if the pointer is const char *
then the compiler must give a diagnostic if you attempt to modify the pointed-to value, but if the pointer is char *
then it does not.
Open github app. Then, add the Folder of files into the github repo file onto your computer (You WILL need to copy the repo onto your computer. Most repo files are located in the following directory: C:\Users\USERNAME\Documents\GitHub\REPONAME) Then, in the github app, check our your repo. You can easily commit from there.
You can use this example for dynamically calling the Where NOT IN
$user = User::where('company_id', '=', 1)->select('id)->get()->toArray(); $otherCompany = User::whereNotIn('id', $user)->get();
An old thread, but...Answer of Konerak works, but why would you even set size of a container by default. What I prefer is to use code wherever no matter of hog big page size is. So this my code:
<style>
#container {
position: relative;
height: 100%;
}
#footer {
position: absolute;
bottom: 0;
}
</style>
</HEAD>
<BODY>
<div id="container">
<h1>Some heading</h1>
<p>Some text you have</p>
<br>
<br>
<div id="footer"><p>Rights reserved</p></div>
</div>
</BODY>
</HTML>
The trick is in <br>
where you break new line. So, when page is small you'll see footer at bottom of page, as you want.
BUT, when a page is big SO THAT YOU MUST SCROLL IT DOWN, then your footer is going to be 2 new lines under the whole content above. And If you will then make page bigger, your footer is allways going to go DOWN. I hope somebody will find this useful.
NOTE! "The static factory method is NOT the same as the Factory Method pattern" (c) Effective Java, Joshua Bloch.
Factory Method: "Define an interface for creating an object, but let the classes which implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses" (c) GoF.
"Static factory method is simply a static method that returns an instance of a class." (c) Effective Java, Joshua Bloch. Usually this method is inside a particular class.
The difference:
The key idea of static factory method is to gain control over object creation and delegate it from constructor to static method. The decision of object to be created is like in Abstract Factory made outside the method (in common case, but not always). While the key (!) idea of Factory Method is to delegate decision of what instance of class to create inside Factory Method. E.g. classic Singleton implementation is a special case of static factory method. Example of commonly used static factory methods:
In the Solution Explorer, right-click any ASPX page and select "Browse With" and select IE as the default.
Note... the same steps can be used to add Google Chrome as a browser option and to optionally set it as the default browser.
here is how to fix it:
Go to Start->Control Panel->System->Advanced(tab)->Environment Variables->System
Variables->New: Variable name: _JAVA_OPTIONS
Variable value: -Xmx512M
Variable name: Path
Variable value: %PATH%;C:\Program Files\Java\jre6\bin;F:\JDK\bin;
Change this to your appropriate path.
Maybe
df <- do.call("cbind", list(df, rep(list(NA),length(namevector))))
colnames(df)[-1*(1:(ncol(df) - length(namevector)))] <- namevector
The following worked for me.
This would create the required meta data and other internal eclipse project file system which will display your project's files.
You can also import the project directly as a file system. Follow the above steps if you are unable to import it directly.
The issue is this, you want to know if the error is not empty.
public function getError() {
return $this->error;
}
Adding a method isErrorSet() will solve the problem.
public function isErrorSet() {
if (isset($this->error) && !empty($this->error)) {
return true;
} else {
return false;
}
}
Now this will work fine with this code with no notice.
if (!($x->isErrorSet())) {
echo $x->getError();
}
Bootstrap 2 , 3 Check is any modal open in page :
if($('.modal.in').length)
compatible version Bootstrap 2 , 3 , 4+
if($('.modal.in, .modal.show').length)
Only Bootstrap 4+
if($('.modal.show').length)
try this:
OnClientClick='return (confirm("Are you sure you want to delete this comment?"));'
Look at array_intersect().
$containsSearch = count(array_intersect($search_this, $all)) == count($search_this);
#include <iostream>
int main()
{
int v[100] = {5,14,2,4,6};
int n = 5;
int mic = v[0];
for(int i = 0; i != n; ++i)
{
if(v[i] < mic)
mic = v[i];
}
std:cout << mic << std::endl;;
}
I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).
Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.
Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.
Neither one of the solutions worked form me. The only one that worked for me in Spring form is:
action="./upload?${_csrf.parameterName}=${_csrf.token}"
REPLACED WITH:
action="./upload?_csrf=${_csrf.token}"
(Spring 5 with enabled csrf in java configuration)
There is package called rimraf that is very handy. It is the UNIX command rm -rf for node.
Nevertheless, it can be too powerful too because you can delete folders very easily using it. The following commands will delete the files inside the folder. If you remove the *, you will remove the log folder.
const rimraf = require('rimraf');
rimraf('./log/*', function () { console.log('done'); });
Use str_replace
to remove the spaces first ?
hi i have a code to save the contact in your database by shared preference here is my code
public class Main22Activity extends AppCompatActivity {
EditText nameInput,phoneInput;
TextView LargeText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main22);
nameInput = (EditText) findViewById(R.id.nameInput);
phoneInput = (EditText) findViewById(R.id.phoneInput);
LargeText = (TextView) findViewById(R.id.textView2);
}
public void saveInfo (View view){
SharedPreferences sharedPref = getSharedPreferences("nameInfo" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor= sharedPref.edit();
editor.putString("name", nameInput.getText().toString());
editor.putString("phone", phoneInput.getText().toString());
editor.apply();
Toast.makeText(this, "Saved", Toast.LENGTH_LONG).show();
}
public void displayData(View view){
SharedPreferences sharedPref = getSharedPreferences("nameInfo" , Context.MODE_PRIVATE);
String name = sharedPref.getString("name", "");
String ph = sharedPref.getString ("phone","");
LargeText.setText(name + " " + ph);
}
}
I've used this trick to center an absolutely positioned element. Though, you have to know the element's width.
.divtagABS {
width: 100px;
position: absolute;
left: 50%;
margin-left: -50px;
}
Basically, you use left: 50%, then back it out half of it's width with a negative margin.
I would just do
int pnSize = primeNumber.size();
for (int i = 0; i < pnSize; i++)
cout << primeNumber[i] << ' ';
For Asp.net Core 2
ViewContext.ModelState["id"].AttemptedValue
You can sit elements next to each other by using the CSS float property:
#first {
float: left;
}
#second {
float: left;
}
You'd need to make sure that the wrapper div allows for the floating in terms of width, and margins etc are set correctly.
If this is ASP.net-Core then you are mixing web API versions. Have the action return a derived IActionResult
because in your current code the framework is treating HttpResponseMessage
as a model.
[Route("api/[controller]")]
public class DownloadController : Controller {
//GET api/download/12345abc
[HttpGet("{id}"]
public async Task<IActionResult> Download(string id) {
Stream stream = await {{__get_stream_based_on_id_here__}}
if(stream == null)
return NotFound(); // returns a NotFoundResult with Status404NotFound response.
return File(stream, "application/octet-stream"); // returns a FileStreamResult
}
}
Sometimes "Nothing to be done for all" error can be caused by spaces before command in makefile rule instead of tab. Please ensure that you use tabs instead of spaces inside of your rules.
all:
<\t>$(CC) $(CFLAGS) ...
instead of
all:
$(CC) $(CFLAGS) ...
Please see the GNU make manual for the rule syntax description: https://www.gnu.org/software/make/manual/make.html#Rule-Syntax
You can also have this
name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n{name}.".format(name=name)
I had this problem, or one that looked superficially similar, yesterday. It turned out that I wasn't being careful when mixing jQuery and prototype. I found several solutions at http://docs.jquery.com/Using_jQuery_with_Other_Libraries. I opted for
var $j = jQuery.noConflict();
but there are other reasonable options described there.
Regarding @lambinator's solution... I was getting the following error in angular.js 1.2.4:
Error: [$rootScope:inprog] $digest already in progress
I'm not sure if I did something wrong or if this is a change in Angular, but removing the scope.$apply
statements resolved the problem and the classes/states are still getting updated.
If you are also seeing this error, give the following a try:
var blurFocusDirective = function () {
return {
restrict: 'E',
require: '?ngModel',
link: function (scope, elm, attr, ctrl) {
if (!ctrl) {
return;
}
elm.on('focus', function () {
elm.addClass('has-focus');
ctrl.$hasFocus = true;
});
elm.on('blur', function () {
elm.removeClass('has-focus');
elm.addClass('has-visited');
ctrl.$hasFocus = false;
ctrl.$hasVisited = true;
});
elm.closest('form').on('submit', function () {
elm.addClass('has-visited');
scope.$apply(function () {
ctrl.hasFocus = false;
ctrl.hasVisited = true;
});
});
}
};
};
app.directive('input', blurFocusDirective);
app.directive('select', blurFocusDirective);
If your server starts up, then that socket was not used.
EDIT
Something like:
ServerSocket s = null ;
try {
s = new ServerSocket( 0 );
} catch( IOException ioe ){
for( int i = START; i < END ; i++ ) try {
s = new ServerSocket( i );
} catch( IOException ioe ){}
}
// At this point if s is null we are helpless
if( s == null ) {
throw new IOException(
Strings.format("Unable to open server in port range(%d-%d)",START,END));
}
There's always a goto
statement, but I would recommend nesting an if
with an inverse of the breaking condition.
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
The solution to this question is very easy: Vectors
std::vector<int> vector;
for(int i = 0; i < 10;i++)
{
vector.push_back(i);
}
std::reverse(vector.begin(), vector.end());
Voila! You are done! =)
Solution details:
This is the most efficent solution: Swap can't swap 3 values but reverse definitely can. Remember to include algorithm. This is so simple that the compiled code is definitely not needed.
I think this solves the OP's problem
If you think there are any errors and problems with this solution please comment below
All procedure at once. Based on @Till Schäfer answer.
In KB...
jstat -gc $(ps axf | egrep -i "*/bin/java *" | egrep -v grep | awk '{print $1}') | tail -n 1 | awk '{split($0,a," "); sum=(a[3]+a[4]+a[6]+a[8]+a[10]); printf("%.2f KB\n",sum)}'
In MB...
jstat -gc $(ps axf | egrep -i "*/bin/java *" | egrep -v grep | awk '{print $1}') | tail -n 1 | awk '{split($0,a," "); sum=(a[3]+a[4]+a[6]+a[8]+a[10])/1024; printf("%.2f MB\n",sum)}'
"Awk sum" reference:
a[1] - S0C
a[2] - S1C
a[3] - S0U
a[4] - S1U
a[5] - EC
a[6] - EU
a[7] - OC
a[8] - OU
a[9] - PC
a[10] - PU
a[11] - YGC
a[12] - YGCT
a[13] - FGC
a[14] - FGCT
a[15] - GCT
Used for "Awk sum":
a[3] -- (S0U) Survivor space 0 utilization (KB).
a[4] -- (S1U) Survivor space 1 utilization (KB).
a[6] -- (EU) Eden space utilization (KB).
a[8] -- (OU) Old space utilization (KB).
a[10] - (PU) Permanent space utilization (KB).
[Ref.: https://docs.oracle.com/javase/7/docs/technotes/tools/share/jstat.html ]
Thanks!
NOTE: Works to OpenJDK!
FURTHER QUESTION: Wrong information?
If you check memory usage with the ps
command, you will see that the java process consumes much more...
ps -eo size,pid,user,command --sort -size | egrep -i "*/bin/java *" | egrep -v grep | awk '{ hr=$1/1024 ; printf("%.2f MB ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' | cut -d "" -f2 | cut -d "-" -f1
UPDATE (2021-02-16):
According to the reference below (and @Till Schäfer comment) "ps can show total reserved memory from OS" (adapted) and "jstat can show used space of heap and stack" (adapted). So, we see a difference between what is pointed out by the ps
command and the jstat
command.
According to our understanding, the most "realistic" information would be the ps
output since we will have an effective response of how much of the system's memory is compromised. The command jstat
serves for a more detailed analysis regarding the java performance in the consumption of reserved memory from OS.
[Ref.: http://www.openkb.info/2014/06/how-to-check-java-memory-usage.html ]
Here's a simple function that does what you need:
<script type="text/javascript">
function minmax(value, min, max)
{
if(parseInt(value) < min || isNaN(parseInt(value)))
return min;
else if(parseInt(value) > max)
return max;
else return value;
}
</script>
<input type="text" name="textWeight" id="txtWeight" maxlength="5" onkeyup="this.value = minmax(this.value, 0, 100)"/>
If the input is not numeric it replaces it with a zero
Here is a nice neat clear answer. I wasn't 100% sure this would work but it seems to be fine. Please let me know if a lib is required for this, but I don't think one is. Also if this doesn't work in x browser please let me know. I tried this in Chrome IE11 and Edge they all seemed to work fine.
var Students = [
{ ID: 1, FName: "Ajay", LName: "Test1", Age: 20},
{ ID: 2, FName: "Jack", LName: "Test2", Age: 21},
{ ID: 3, FName: "John", LName: "Test3", age: 22},
{ ID: 4, FName: "Steve", LName: "Test4", Age: 22}
]
Students.forEach(function (Student) {
if (Student.LName == 'Test1') {
Student.LName = 'Smith'
}
if (Student.LName == 'Test2') {
Student.LName = 'Black'
}
});
Students.forEach(function (Student) {
document.write(Student.FName + " " + Student.LName + "<BR>");
});
Output should be as follows
Ajay Smith
Jack Black
John Test3
Steve Test4
If you are a linux user Update node to a later version by running
sudo apt update
sudo apt install build-essential checkinstall libssl-dev
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash
nvm --version
nvm ls
nvm ls-remote
nvm install [version.number]
this should solve your problem
I want them to cover 75% of the button area.
Use android:padding="20dp"
(adjust the padding as needed) to control how much the image takes up on the button.
but where as some images cover less area, some are too big to fit into the imageButton. How to programatically resize and show them?
Use a android:scaleType="fitCenter"
to have Android scale the images, and android:adjustViewBounds="true"
to have them adjust their bounds due to scaling.
All of these attributes can be set in code on each ImageButton
at runtime. However, it is much easier to set and preview in xml in my opinion.
Also, do not use sp
for anything other than text size, it is scaled depending on the text size preference the user sets, so your sp
dimensions will be larger than your intended if the user has a "large" text setting. Use dp
instead, as it is not scaled by the user's text size preference.
Here's a snippet of what each button should look like:
<ImageButton
android:id="@+id/button_topleft"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="5dp"
android:layout_marginTop="0dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:padding="20dp"
android:scaleType="fitCenter" />
Variant without JavaScript. Only CSS.
CSS:
.toggle_block {
border: 1px solid #ccc;
text-align: left;
background: #fff;
overflow: hidden;
}
.toggle_block .toggle_flag {
display: block;
width: 1px;
height: 1px;
position: absolute;
z-index: 0;
left: -1000px;
}
.toggle_block .toggle_key {
font-size: 16px;
padding: 10px;
cursor: pointer;
-webkit-transition: all 300ms ease;
-moz-transition: all 300ms ease;
-ms-transition: all 300ms ease;
-o-transition: all 300ms ease;
transition: all 300ms ease;
}
.toggle_block .content {
padding: 0 10px;
overflow: hidden;
max-height: 0;
-webkit-transition: all 300ms ease;
-moz-transition: all 300ms ease;
-ms-transition: all 300ms ease;
-o-transition: all 300ms ease;
transition: all 300ms ease;
}
.toggle_block .content .toggle_close {
cursor: pointer;
font-size: 12px;
}
.toggle_block .toggle_flag:checked ~ .toggle_key {
background: #dfd;
}
.toggle_block .toggle_flag:checked ~ .content {
max-height: 1000px;
padding: 10px 10px;
}
HTML:
<div class="toggle_block">
<input type="checkbox" id="toggle_1" class="toggle_flag">
<label for="toggle_1" class="toggle_key">clicker</label>
<div class="content">
Text 1<br>
Text 2<br>
<label for="toggle_1" class="toggle_close">close</label>
</div>
</div>
For next block only change ID and FOR attributes in html.
You could add the following VBA code to your sheet:
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("A1") > 0.5 Then
MsgBox "Discount too high"
End If
End Sub
Every time a cell is changed on the sheet, it will check the value of cell A1.
Notes:
Widor uses a different approach (Worksheet_Calculate
instead of Worksheet_Change
):
Conclusion: use Worksheet_Change
if A1 only depends on data located on the same sheet, use Worksheet_Calculate
if not.
I use a customized version of DX Auth. I found it simple to use, extremely easy to modify and it has a user guide (with great examples) that is very similar to Code Igniter's.
$scope.clearSearch = function () {
$scope.searchAll = "";
};
JsFiddle of how you could do it without using inline JS.
Below snippet code is written to compile and run external JAVA program using ProcessBuilder, same way we can run any external program. Make sure JAVA_HOME must be set in OS environment. see more
package com.itexpert.exam;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JavaProcessBuilder {
/**
* Provide absolute JAVA file path
*/
private static final String JAVA_FILE_LOCATION = "D:\\Test.java";
public static void main(String args[]) throws IOException{
String command[] = {"javac",JAVA_FILE_LOCATION};
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
/**
* Check if any errors or compilation errors encounter then print on Console.
*/
if( process.getErrorStream().read() != -1 ){
print("Compilation Errors",process.getErrorStream());
}
/**
* Check if javac process execute successfully or Not
* 0 - successful
*/
if( process.exitValue() == 0 ){
process = new ProcessBuilder(new String[]{"java","-cp","d:\\","Test"}).start();
/** Check if RuntimeException or Errors encounter during execution then print errors on console
* Otherwise print Output
*/
if( process.getErrorStream().read() != -1 ){
print("Errors ",process.getErrorStream());
}
else{
print("Output ",process.getInputStream());
}
}
}
private static void print(String status,InputStream input) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(input));
System.out.println("************* "+status+"***********************");
String line = null;
while((line = in.readLine()) != null ){
System.out.println(line);
}
in.close();
}
}