One More way to send objects through bundle is by using bundle.putByteArray
Sample code
public class DataBean implements Serializable {
private Date currentTime;
public setDate() {
currentTime = Calendar.getInstance().getTime();
}
public Date getCurrentTime() {
return currentTime;
}
}
put Object of DataBean in to Bundle:
class FirstClass{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Your code...
//When you want to start new Activity...
Intent dataIntent =new Intent(FirstClass.this, SecondClass.class);
Bundle dataBundle=new Bundle();
DataBean dataObj=new DataBean();
dataObj.setDate();
try {
dataBundle.putByteArray("Obj_byte_array", object2Bytes(dataObj));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dataIntent.putExtras(dataBundle);
startActivity(dataIntent);
}
Converting objects to byte arrays
/**
* Converting objects to byte arrays
*/
static public byte[] object2Bytes( Object o ) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
oos.writeObject( o );
return baos.toByteArray();
}
Get Object back from Bundle:
class SecondClass{
DataBean dataBean;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Your code...
//Get Info from Bundle...
Bundle infoBundle=getIntent().getExtras();
try {
dataBean = (DataBean)bytes2Object(infoBundle.getByteArray("Obj_byte_array"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Method to get objects from byte arrays:
/**
* Converting byte arrays to objects
*/
static public Object bytes2Object( byte raw[] )
throws IOException, ClassNotFoundException {
ByteArrayInputStream bais = new ByteArrayInputStream( raw );
ObjectInputStream ois = new ObjectInputStream( bais );
Object o = ois.readObject();
return o;
}
Hope this will help to other buddies.
BundleConfig
is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)
To add this file, first you need to add the Microsoft.AspNet.Web.Optimization
nuget package to your web project:
Install-Package Microsoft.AspNet.Web.Optimization
Then under the App_Start folder create a new cs file called BundleConfig.cs
. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):
using System.Web;
using System.Web.Optimization;
namespace CodeRepository.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
Then modify your Global.asax and add a call to RegisterBundles()
in Application_Start()
:
using System.Web.Optimization;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app
Just tried the Anonymous answer and found there's a little trick here, it doesn't work if there's a space after backslash \
So the following solution doesn't work -
var x = { test:'<?xml version="1.0"?>\ <-- One space here
<?mso-application progid="Excel.Sheet"?>'
};
But when space is removed it works -
var x = { test:'<?xml version="1.0"?>\<-- No space here now
<?mso-application progid="Excel.Sheet"?>'
};
alert(x.test);?
Hope it helps !!
int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");
Created elegant Kotlin
way with extension:
fun TextView.setClickableText(text: Spanned,
clickableText: String,
@ColorInt clickableColor: Int,
clickListener: () -> Unit) {
val spannableString = SpannableString(text)
val startingPosition: Int = text.indexOf(clickableText)
if (startingPosition > -1) {
val clickableSpan: ClickableSpan = object : ClickableSpan() {
override fun onClick(textView: View) {
clickListener()
}
override fun updateDrawState(textPaint: TextPaint) {
super.updateDrawState(textPaint)
textPaint.isUnderlineText = false
}
}
val endingPosition: Int = startingPosition + clickableText.length
spannableString.setSpan(clickableSpan, startingPosition,
endingPosition, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
spannableString.setSpan(ForegroundColorSpan(clickableColor), startingPosition,
endingPosition, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
movementMethod = LinkMovementMethod.getInstance()
highlightColor = Color.TRANSPARENT
}
setText(spannableString)
}
In general:
Database and table names are not case sensitive in Windows, and case sensitive in most varieties of Unix.
In MySQL, databases correspond to directories within the data directory. Each table within a database corresponds to at least one file within the database directory. Consequently, the case sensitivity of the underlying operating system plays a part in the case sensitivity of database and table names.
One can configure how tables names are stored on the disk using the system variable lower_case_table_names
(in the my.cnf configuration file under [mysqld]).
Read the section: 10.2.2 Identifier Case Sensitivity for more information.
Try saving your .c file before building. I believe your computer is referencing a path to a file with no information inside of it.
--Had similar issue when building C projects
The Key Disappears, whether it is numeric or not. Try out the test script below.
<?php
$t = array( 'a', 'b', 'c', 'd' );
foreach($t as $k => $v)
echo($k . ": " . $v . "<br/>");
// Output: 0: a, 1: b, 2: c, 3: d
unset($t[1]);
foreach($t as $k => $v)
echo($k . ": " . $v . "<br/>");
// Output: 0: a, 2: c, 3: d
?>
mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8
This is my function.
benefits :
/**
* Get real user ip
*
* Usage sample:
* GetRealUserIp();
* GetRealUserIp('ERROR',FILTER_FLAG_NO_RES_RANGE);
*
* @param string $default default return value if no valid ip found
* @param int $filter_options filter options. default is FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
*
* @return string real user ip
*/
function GetRealUserIp($default = NULL, $filter_options = 12582912) {
$HTTP_X_FORWARDED_FOR = isset($_SERVER)? $_SERVER["HTTP_X_FORWARDED_FOR"]:getenv('HTTP_X_FORWARDED_FOR');
$HTTP_CLIENT_IP = isset($_SERVER)?$_SERVER["HTTP_CLIENT_IP"]:getenv('HTTP_CLIENT_IP');
$HTTP_CF_CONNECTING_IP = isset($_SERVER)?$_SERVER["HTTP_CF_CONNECTING_IP"]:getenv('HTTP_CF_CONNECTING_IP');
$REMOTE_ADDR = isset($_SERVER)?$_SERVER["REMOTE_ADDR"]:getenv('REMOTE_ADDR');
$all_ips = explode(",", "$HTTP_X_FORWARDED_FOR,$HTTP_CLIENT_IP,$HTTP_CF_CONNECTING_IP,$REMOTE_ADDR");
foreach ($all_ips as $ip) {
if ($ip = filter_var($ip, FILTER_VALIDATE_IP, $filter_options))
break;
}
return $ip?$ip:$default;
}
Maybe it will be helpfull for you. You could use "DirectoryInfo.EnumerateFiles" method and handle UnauthorizedAccessException as you need.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
DirectoryInfo diTop = new DirectoryInfo(@"d:\");
try
{
foreach (var fi in diTop.EnumerateFiles())
{
try
{
// Display each file over 10 MB;
if (fi.Length > 10000000)
{
Console.WriteLine("{0}\t\t{1}", fi.FullName, fi.Length.ToString("N0"));
}
}
catch (UnauthorizedAccessException UnAuthTop)
{
Console.WriteLine("{0}", UnAuthTop.Message);
}
}
foreach (var di in diTop.EnumerateDirectories("*"))
{
try
{
foreach (var fi in di.EnumerateFiles("*", SearchOption.AllDirectories))
{
try
{
// Display each file over 10 MB;
if (fi.Length > 10000000)
{
Console.WriteLine("{0}\t\t{1}", fi.FullName, fi.Length.ToString("N0"));
}
}
catch (UnauthorizedAccessException UnAuthFile)
{
Console.WriteLine("UnAuthFile: {0}", UnAuthFile.Message);
}
}
}
catch (UnauthorizedAccessException UnAuthSubDir)
{
Console.WriteLine("UnAuthSubDir: {0}", UnAuthSubDir.Message);
}
}
}
catch (DirectoryNotFoundException DirNotFound)
{
Console.WriteLine("{0}", DirNotFound.Message);
}
catch (UnauthorizedAccessException UnAuthDir)
{
Console.WriteLine("UnAuthDir: {0}", UnAuthDir.Message);
}
catch (PathTooLongException LongPath)
{
Console.WriteLine("{0}", LongPath.Message);
}
}
}
To force enable TLSv1.2 in JRE7u_80 I had to use following code snippet before creating JDBC connection.
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import javax.net.ssl.SSLContextSpi;
import sun.security.jca.GetInstance;
import sun.security.jca.ProviderList;
import sun.security.jca.Providers;
public static void enableTLSv12ForMssqlJdbc() throws NoSuchAlgorithmException
{
ProviderList providerList = Providers.getProviderList();
GetInstance.Instance instance = GetInstance.getInstance("SSLContext", SSLContextSpi.class, "TLS");
for (Provider provider : providerList.providers())
{
if (provider == instance.provider)
{
provider.put("Alg.Alias.SSLContext.TLS", "TLSv1.2");
}
}
}
Able to connect to Windows 10 with SQL server 2017 & TLSv1.2 enabled OS.
The very purpose of using the static method is to access the method of a class without creating an instance for it.It will make no sense if we override that method since they will be accessed by classname.method()
Here are the different ways in which you can create an array of booleans in typescript:
let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();
let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();
let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];
let arr10 = <boolean[]> [];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();
let arr13 = new Array<boolean>();
let arr14 = Array<boolean>();
You can access them using the index:
console.log(arr[5]);
and you add elements using push:
arr.push(true);
When creating the array you can supply the initial values:
let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);
Loose coupling is and answer to to old style hardcoded dependencies and related issues issues like frequent recompilation when anything changes and code reuse. It stresses on implementing the worker logic in components and avoiding solution specific wire up code there.
You can use the DataGridViewCell.Value Property to retrieve the value stored in a particular cell.
So to retrieve the value of the 'first' selected Cell and display in a MessageBox, you can:
MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());
The above probably isn't exactly what you need to do. If you provide more details we can provide better help.
The clone
method is Ruby's standard, built-in way to do a shallow-copy:
irb(main):003:0> h0 = {"John" => "Adams", "Thomas" => "Jefferson"}
=> {"John"=>"Adams", "Thomas"=>"Jefferson"}
irb(main):004:0> h1 = h0.clone
=> {"John"=>"Adams", "Thomas"=>"Jefferson"}
irb(main):005:0> h1["John"] = "Smith"
=> "Smith"
irb(main):006:0> h1
=> {"John"=>"Smith", "Thomas"=>"Jefferson"}
irb(main):007:0> h0
=> {"John"=>"Adams", "Thomas"=>"Jefferson"}
Note that the behavior may be overridden:
This method may have class-specific behavior. If so, that behavior will be documented under the
#initialize_copy
method of the class.
Here is a good introduction to logging in Java: http://www.javapractices.com/topic/TopicAction.do?Id=143
Java comes with a logging API since it's 1.4.2 version: http://download.oracle.com/javase/1.4.2/docs/guide/util/logging/overview.html
You can also use other logging frameworks like Apache Log4j which is the most popular one: http://logging.apache.org/log4j
I suggest you to use a logging abstraction framework which allows you to change your logging framework without re-factoring you code. So you can starts by using Jul (Java Util Logging) then swith to Log4j without changing you code. The most popular logging facade is slf4j: http://www.slf4j.org/
Regards,
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId != 0 || event.getAction() == KeyEvent.ACTION_DOWN) {
// Action
return true;
} else {
return false;
}
}
});
Xml
<EditText
android:id="@+id/editText2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/password"
android:imeOptions="actionGo|flagNoFullscreen"
android:inputType="textPassword"
android:maxLines="1" />
well I think I have something interesting for you... https://github.com/whizzzkid/phpimageresize. I wrote it for the exact same purpose. Highly customizable, and does it in a great way.
For static assertions, C++11 introduced decltype
which is quite useful in certain scenarios.
You can also use printf to pipe the input to your script.
var=val
printf "yes\nno\nmaybe\n$var\n" | ./your_script.sh
For me everything was working fine until Bitbucket automatically changed their policy today (April 21, 2020). This happens to align with a new feature recently introduced today called Workspaces, so I suspect it has something to do with that.
Workaround: I (as an Admin) followed the instructions to add the email address to Users in the UI (the email you are using can be found git config --list
NumPy's arrays are more compact than Python lists -- a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access in reading and writing items is also faster with NumPy.
Maybe you don't care that much for just a million cells, but you definitely would for a billion cells -- neither approach would fit in a 32-bit architecture, but with 64-bit builds NumPy would get away with 4 GB or so, Python alone would need at least about 12 GB (lots of pointers which double in size) -- a much costlier piece of hardware!
The difference is mostly due to "indirectness" -- a Python list is an array of pointers to Python objects, at least 4 bytes per pointer plus 16 bytes for even the smallest Python object (4 for type pointer, 4 for reference count, 4 for value -- and the memory allocators rounds up to 16). A NumPy array is an array of uniform values -- single-precision numbers takes 4 bytes each, double-precision ones, 8 bytes. Less flexible, but you pay substantially for the flexibility of standard Python lists!
window.location.assign(url)
this fixs the window.open(url)
issue in ios devices
In confing.yml
# app/config/config.yml
twig:
globals:
version: '%app.version%'
In Twig view
# twig view
{{ version }}
You use it like this:
SELECT age, name
FROM users
UNION
SELECT 25 AS age, 'Betty' AS name
Use UNION ALL
to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION
.
Use return statement anywhere you want to exit from function.
if(somecondtion)
return;
if(somecondtion)
return false;
The include path is set against the server configuration (PHP.ini) but the include path you specify is relative to that path so in your case the include path is (actual path in windows):
C:\xampp\php\PEAR\initcontrols\header_myworks.php
providing the path you pasted in the subject is correct. Make sure your file is located there.
For more info you can get and set the include path programmatically.
For modern browsers all you need is this CSS:
img {
pointer-events: none;
}
Older browsers will still allow pointer events on the images, but the CSS above will take care of the vast majority of visitors to your site, and used in conjunction with the contextmenu
methods should give you a very solid solution.
If you are planning to use JSONP
you can use getJSON
which made for that. jQuery has helper methods for JSONP
.
$.getJSON( 'http://someotherdomain.com/service.svc&callback=?', function( result ) {
console.log(result);
});
Read the below links
http://api.jquery.com/jQuery.getJSON/
I hope this is what you are looking for.
class Try:
def do_somthing(self):
print 'Hello'
if __name__ == '__main__':
obj_list = []
for obj in range(10):
obj = Try()
obj_list.append(obj)
obj_list[0].do_somthing()
Output:
Hello
SO thread 'Multiply two arrays element wise, where one of the arrays has arrays as elements' has an example of constructing an array from arrays. If the subarrays are the same size, numpy makes a 2d array. But if they differ in length, it makes an array with dtype=object
, and the subarrays retain their identity.
Following that, you could do something like this:
In [5]: result=np.array([np.zeros((1)),np.zeros((2))])
In [6]: result
Out[6]: array([array([ 0.]), array([ 0., 0.])], dtype=object)
In [7]: np.append([result[0]],[1,2])
Out[7]: array([ 0., 1., 2.])
In [8]: result[0]
Out[8]: array([ 0.])
In [9]: result[0]=np.append([result[0]],[1,2])
In [10]: result
Out[10]: array([array([ 0., 1., 2.]), array([ 0., 0.])], dtype=object)
However, I don't offhand see what advantages this has over a pure Python list or lists. It does not work like a 2d array. For example I have to use result[0][1]
, not result[0,1]
. If the subarrays are all the same length, I have to use np.array(result.tolist())
to produce a 2d array.
with open('output.txt', 'r') as f:
lines = f.read().splitlines()
last_line = lines[-1]
print last_line
Modify your log4j.properties
file accordingly:
log4j.rootLogger=TRACE,stdout
...
log4j.logger.debugLog=TRACE,debugLog
log4j.logger.reportsLog=DEBUG,reportsLog
Change the log levels for each logger depending to your needs.
And to iterate on the files of a directory:
@echo off
setlocal enableDelayedExpansion
set MYDIR=C:\something
for /F %%x in ('dir /B/D %MYDIR%') do (
set FILENAME=%MYDIR%\%%x\log\IL_ERROR.log
echo =========================== Search in !FILENAME! ===========================
c:\utils\grep motiv !FILENAME!
)
You must use "enableDelayedExpansion" and !FILENAME! instead of $FILENAME$. In the second case, DOS will interpret the variable only once (before it enters the loop) and not each time the program loops.
For me much better way is to do it using terminal rather then PhpMyAdmin UI.
The answer is copied from "https://gist.github.com/susanBuck/39d1a384779f3d596afb19fcad6b598c" which I have tried and it works always, try it out..
Find the line [mysqld] and right below it add skip-grant-tables. Example:
[mysqld]
skip-grant-tables
port= 3306
socket = "C:/xampp/mysql/mysql.sock"
basedir = "C:/xampp/mysql"
tmpdir = "C:/xampp/tmp"
[...etc...]
This should allow you to access MySQL if you don't know your password.
C:\xampp\mysql\bin\mysql.exe --user=root
USE mysql;
SELECT * FROM user \G;
UPDATE user SET password = PASSWORD('secret_pass') WHERE user = 'root';
UPDATE user SET password = '' WHERE user = 'root';
When you're done, run exit; to exit the MySQL command line.
Next, re-enable password checking by removing skip-grant-tables
from C:\xampp\mysql\bin\my.ini.
Save changes, restart MySQL from XAMPP.
In my case I could not load one out of 5 projects in my solution.
It helped to close Visual Studio and I had to delete Microsoft.Net.Compilers.1.3.2
nuget folder under packages
folder.
Afterwards, open your solution again and the project loaded as expected
Just to be sure, close all instances of VS before you delete the folder.
This works for me:
@Configuration
public class MyConfig extends WebSecurityConfigurerAdapter {
//...
@Override
protected void configure(HttpSecurity http) throws Exception {
//...
http.cors().configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedHeaders(Collections.singletonList("*"));
config.setAllowedMethods(Collections.singletonList("*"));
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
return config;
}
});
//...
}
//...
}
EDIT: THIS ANSWER IS INCORRECT. I leave it in here as a warning to anyone tempted to use dayofyear
, with a further edit at the end.
If, like me, you do not want to divide by fractional days or risk rounding/leap year errors, I applaud @Bacon Bits comment in a post above https://stackoverflow.com/a/1572257/489865 where he says:
If we're talking about human ages, you should calculate it the way humans calculate age. It has nothing to do with how fast the earth moves and everything to do with the calendar. Every time the same month and day elapses as the date of birth, you increment age by 1. This means the following is the most accurate because it mirrors what humans mean when they say "age".
He then offers:
DATEDIFF(yy, @date, GETDATE()) -
CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) > DAY(GETDATE()))
THEN 1 ELSE 0 END
There are several suggestions here involving comparing the month & day (and some get it wrong, failing to allow for the OR
as correctly here!). But nobody has offered dayofyear
, which seems so simple and much shorter. I offer:
DATEDIFF(year, @date, GETDATE()) -
CASE WHEN DATEPART(dayofyear, @date) > DATEPART(dayofyear, GETDATE()) THEN 1 ELSE 0 END
[Note: Nowhere in SQL BOL/MSDN is what DATEPART(dayofyear, ...)
returns actually documented! I understand it to be a number in the range 1--366; most importantly, it does not change by locale as per DATEPART(weekday, ...)
& SET DATEFIRST
.]
EDIT: Why dayofyear
goes wrong: As user @AeroX has commented, if the birth/start date is after February in a non leap year, the age is incremented one day early when the current/end date is a leap year, e.g. '2015-05-26'
, '2016-05-25'
gives an age of 1 when it should still be 0. Comparing the dayofyear
in different years is clearly dangerous. So using MONTH()
and DAY()
is necessary after all.
Also, in the above case there should be only one
implicit function whose type is double => Int
. Otherwise, the compiler gets confused and won't compile properly.
//this won't compile
implicit def doubleToInt(d: Double) = d.toInt
implicit def doubleToIntSecond(d: Double) = d.toInt
val x: Int = 42.0
A simple way to take a screenshot is through Pygame.
pygame.image.save(Surface, filename)
Where 'Surface' is the surface you are taking a screenshot of, and 'filename' is the file path, name, and type where you save thew image.
You can export as BMP, TGA, PNG, or JPEG. As of Pygame 1.8, PNG, and JPEG also work.
If no file extension is specified it will default to a .TGA file.
You can even use the 'os' library for saving to specific file directories.
An example:
import os
import pygame
surface = pygame.display.set_mode((100, 100), 0, 32)
surface.fill((255, 255, 255))
pygame.draw.circle(surface, (0, 0, 0), (10, 10), 15, 0)
pygame.display.update()
pygame.image.save(surface, os.path.expanduser("~/Desktop/pic.png"))
This saves anything on the 'surface' Surface to the user's desktop as pic.png
The standard C library provides timespec_get
. It can tell time up to nanosecond precision, if the system supports. Calling it, however, takes a bit more effort because it involves a struct. Here's a function that just converts the struct to a simple 64-bit integer so you can get time in milliseconds.
#include <stdio.h>
#include <inttypes.h>
#include <time.h>
int64_t millis()
{
struct timespec now;
timespec_get(&now, TIME_UTC);
return ((int64_t) now.tv_sec) * 1000 + ((int64_t) now.tv_nsec) / 1000000;
}
int main(void)
{
printf("Unix timestamp with millisecond precision: %" PRId64 "\n", millis());
}
Unlike clock
, this function returns a Unix timestamp so it will correctly account for the time spent in blocking functions, such as sleep
.
This would be a get/set in C# using the smallest amount of code possible. You get auto-implemented properties in C# 3.0+.
public class Contact
{
public string Name { get; set; }
}
The short answer here is the serial ID is computed via a hash if you don't specify it. (Static members are not inherited--they are static, there's only (1) and it belongs to the class).
http://docs.oracle.com/javase/6/docs/platform/serialization/spec/class.html
The getSerialVersionUID method returns the serialVersionUID of this class. Refer to Section 4.6, "Stream Unique Identifiers." If not specified by the class, the value returned is a hash computed from the class's name, interfaces, methods, and fields using the Secure Hash Algorithm (SHA) as defined by the National Institute of Standards.
If you alter a class or its hierarchy your hash will be different. This is a good thing. Your objects are different now that they have different members. As such, if you read it back in from its serialized form it is in fact a different object--thus the exception.
The long answer is the serialization is extremely useful, but probably shouldn't be used for persistence unless there's no other way to do it. Its a dangerous path specifically because of what you're experiencing. You should consider a database, XML, a file format and probably a JPA or other persistence structure for a pure Java project.
The easiest way to draw a relationship between items is by understanding them in plain languages. Example
A user can have many cars but then a car can have just one owner. After establishing this, the foreign key should be used on the item with the many relationship. In this case the car. Meaning you'll include user as a foreign key in cars
And a one on one relationship is quite simple. Say a man and a heart. A man has only one heart and a heart can belong to just one man
use:
/^[ A-Za-z0-9_@./#&+-]*$/
You can also use the character class \w to replace A-Za-z0-9_
As DanielaWaranie mentioned in her answer - there is a way to specify the type of $item when you iterating over $items in $collectionObject: Add @return MyEntitiesClassName
to current()
and rest of the Iterator
and ArrayAccess
-methods which return values.
Boom! No need in /** @var SomeObj[] $collectionObj */
over foreach
, and works right with collection object, no need to return collection with specific method described as @return SomeObj[]
.
I suspect not all IDE support it but it works perfectly fine in PhpStorm, which makes me happier.
Example:
class MyCollection implements Countable, Iterator, ArrayAccess {
/**
* @return User
*/
public function current() {
return $this->items[$this->cursor];
}
//... implement rest of the required `interface` methods and your custom
}
In my case current()
and rest of interface
-methods are implemented in Abstract
-collection class and I do not know what kind of entities will eventually be stored in collection.
So here is the trick: Do not specify return type in abstract class, instead use PhpDoc instuction @method
in description of specific collection class.
Example:
class User {
function printLogin() {
echo $this->login;
}
}
abstract class MyCollection implements Countable, Iterator, ArrayAccess {
protected $items = [];
public function current() {
return $this->items[$this->cursor];
}
//... implement rest of the required `interface` methods and your custom
//... abstract methods which will be shared among child-classes
}
/**
* @method User current()
* ...rest of methods (for ArrayAccess) if needed
*/
class UserCollection extends MyCollection {
function add(User $user) {
$this->items[] = $user;
}
// User collection specific methods...
}
Now, usage of classes:
$collection = new UserCollection();
$collection->add(new User(1));
$collection->add(new User(2));
$collection->add(new User(3));
foreach ($collection as $user) {
// IDE should `recognize` method `printLogin()` here!
$user->printLogin();
}
Once again: I suspect not all IDE support it, but PhpStorm does. Try yours, post in comment the results!
Steps (These apply for Linux. For other OS, visit here) -
platform-tools
in android-sdk linux
folder../adb install FileName.apk
For more info can check this link : android videos
Iterate through a copy of the list:
>>> a = ["a", "b", "c", "d", "e"]
>>> for item in a[:]:
print item
if item == "b":
a.remove(item)
a
b
c
d
e
>>> print a
['a', 'c', 'd', 'e']
Personally, I took the strangeness of the Java calendar API as an indication that I needed to divorce myself from the Gregorian-centric mindset and try to program more agnostically in that respect. Specifically, I learned once again to avoid hardcoded constants for things like months.
Which of the following is more likely to be correct?
if (date.getMonth() == 3) out.print("March");
if (date.getMonth() == Calendar.MARCH) out.print("March");
This illustrates one thing that irks me a little about Joda Time - it may encourage programmers to think in terms of hardcoded constants. (Only a little, though. It's not as if Joda is forcing programmers to program badly.)
The above solution is incomplete, it missed the attribute src
.
this.src
and this.attribute('src')
are NOT the same, the first one contains the full reference to the image, for example http://my.host/error.jpg
, but the attribute just keeps the original value, error.jpg
Correct solution
<img src="foo.jpg" onerror="if (this.src != 'error.jpg' && this.attribute('src') != 'error.jpg') this.src = 'error.jpg';" />
Swift is not like languages like JavaScript, where you can call a function without passing the parameters and it will still be called. So to call a function in Swift, you need to assign a value to its parameters.
Default values for parameters allow you to assign a value without specifying it when calling the function. That's why test()
works when you specify a default value on test's declaration.
If you don't include that default value, you need to provide the value on the call: test(nil)
.
Also, and not directly related to this question, but probably worth to note, you are using the "C++" way of dealing with possibly null pointers, for dealing with possible nil optionals in Swift. The following code is safer (specially in multithreading software), and it allows you to avoid the forced unwrapping of the optional:
func test(firstThing: Int? = nil) {
if let firstThing = firstThing {
print(firstThing)
}
print("done")
}
test()
Run cmd as administrator. Type iisreset
. That's it.
You need to set the LayoutParams of the ViewGroup the ImageView is sitting in. For example if your ImageView is inside a LinearLayout, then you create a
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);
This is because it's the parent of the View that needs to know what size to allocate to the View.
The best option by far is to create an INSTEAD OF INSERT trigger for your table, removing the default values from your table, and moving them into the trigger.
This will look like the following:
create trigger dbo.OnInsertIntoT
ON TablenameT
INSTEAD OF INSERT
AS
insert into TablenameT
select
IsNull(column1 ,<default_value>)
,IsNull(column2 ,<default_value>)
...
from inserted
This makes it work NO MATTER what code tries to insert NULLs into your table, avoids stored procedures, is completely transparent, and you only need to maintain your default values in one place, namely this trigger.
Something worth noting is that INSERT IGNORE will still increment the primary key whether the statement was a success or not just like a normal INSERT would.
This will cause gaps in your primary keys that might make a programmer mentally unstable. Or if your application is poorly designed and depends on perfect incremental primary keys, it might become a headache.
Look into innodb_autoinc_lock_mode = 0
(server setting, and comes with a slight performance hit), or use a SELECT first to make sure your query will not fail (which also comes with a performance hit and extra code).
I think you can use SeriesGroupBy.nunique
:
print (df.groupby('param')['group'].nunique())
param
a 2
b 1
Name: group, dtype: int64
Another solution with unique
, then create new df
by DataFrame.from_records
, reshape to Series
by stack
and last value_counts
:
a = df[df.param.notnull()].groupby('group')['param'].unique()
print (pd.DataFrame.from_records(a.values.tolist()).stack().value_counts())
a 2
b 1
dtype: int64
Creating a truly compile-time generated constant dictionary in C# is not really a straightforward task. Actually, none of the answers here really achieve that.
There is one solution though which meets your requirements, although not necessarily a nice one; remember that according to the C# specification, switch-case tables are compiled to constant hash jump tables. That is, they are constant dictionaries, not a series of if-else statements. So consider a switch-case statement like this:
switch (myString)
{
case "cat": return 0;
case "dog": return 1;
case "elephant": return 3;
}
This is exactly what you want. And yes, I know, it's ugly.
Change Column Name/Type/Position/Comment:
ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name]
Example:
CREATE TABLE test_change (a int, b int, c int);
// will change column a's name to a1
ALTER TABLE test_change CHANGE a a1 INT;
Although this question was more specifically about IP addresses in Subject Alt. Names, the commands are similar (using DNS
entries for a host name and IP
entries for IP addresses).
To quote myself:
If you're using
keytool
, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1
Note that you only need Java 7's keytool
to use this command. Once you've prepared your keystore, it should work with previous versions of Java.
(The rest of this answer also mentions how to do this with OpenSSL, but it doesn't seem to be what you're using.)
A see a lot of good answers, but I decide to put my 5 cents just to have good example:
iterates over all enumerable props
let nodes = document.documentElement.childNodes;_x000D_
_x000D_
for (var key in nodes) {_x000D_
console.log( key );_x000D_
}
_x000D_
iterates over all iterable values
let nodes = document.documentElement.childNodes;_x000D_
_x000D_
for (var node of nodes) {_x000D_
console.log( node.toString() );_x000D_
}
_x000D_
PostgreSQL supports boolean types, so your SQL query would work perfectly in PostgreSQL.
An interface is a contract: The person writing the interface says, "hey, I accept things looking that way", and the person using the interface says "OK, the class I write looks that way".
An interface is an empty shell. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern.
For example (pseudo code):
// I say all motor vehicles should look like this:
interface MotorVehicle
{
void run();
int getFuel();
}
// My team mate complies and writes vehicle looking that way
class Car implements MotorVehicle
{
int fuel;
void run()
{
print("Wrroooooooom");
}
int getFuel()
{
return this.fuel;
}
}
Implementing an interface consumes very little CPU, because it's not a class, just a bunch of names, and therefore there isn't any expensive look-up to do. It's great when it matters, such as in embedded devices.
Abstract classes, unlike interfaces, are classes. They are more expensive to use, because there is a look-up to do when you inherit from them.
Abstract classes look a lot like interfaces, but they have something more: You can define a behavior for them. It's more about a person saying, "these classes should look like that, and they have that in common, so fill in the blanks!".
For example:
// I say all motor vehicles should look like this:
abstract class MotorVehicle
{
int fuel;
// They ALL have fuel, so lets implement this for everybody.
int getFuel()
{
return this.fuel;
}
// That can be very different, force them to provide their
// own implementation.
abstract void run();
}
// My teammate complies and writes vehicle looking that way
class Car extends MotorVehicle
{
void run()
{
print("Wrroooooooom");
}
}
While abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are.
In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared.
In Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it's a mix between conventions and special methods that call descriptors (the __method__ methods).
As usual with programming, there is theory, practice, and practice in another language :-)
You may want one of these, so to correspond to the Bootstrap layout:
<div class="col-xs-12">
<hr >
</div>
<!-- or -->
<div class="col-xs-12">
<hr style="border-style: dashed; border-top-width: 2px;">
</div>
<!-- or -->
<div class="col-xs-12">
<hr class="col-xs-1" style="border-style: dashed; border-top-width: 2px;">
</div>
Without a DIV
grid element included, layout may brake on different devices.
Some basic differences can be written in short:
MVC:
Traditional MVC is where there is a
MVP:
Similar to traditional MVC but Controller is replaced by Presenter. But the Presenter, unlike Controller is responsible for changing the view as well. The view usually does not call the presenter.
MVVM
The difference here is the presence of View Model. It is kind of an implementation of Observer Design Pattern, where changes in the model are represented in the view as well, by the VM. Eg: If a slider is changed, not only the model is updated but the data which may be a text, that is displayed in the view is updated as well. So there is a two-way data binding.
Javascript is pass by value, and which essentially means part
is a copy of the value in the array.
To change the value, access the array itself in your loop.
arr[index] = 'new value';
First try:
net stop MySQL
net start MySQL
If that does not work, try using the windows interface:
Start > Control Panel > System and Security > Administrative Tools > Services
Look for your version of MySQL (In my case - MySQL55), highlight and click the green start arrow. The status should change to "Started"
After jQuery 1.6, using promise seems like a better option.
var $div1 = $('#div1');
var fadeOutDone = $div1.fadeOut().promise();
// do your logic here, e.g.fetch your 2nd image url
$.get('secondimageinfo.json').done(function(data){
fadeoOutDone.then(function(){
$div1.html('<img src="' + data.secondImgUrl + '" alt="'data.secondImgAlt'">');
$div1.fadeIn();
});
});
Just like any other click event, you can use jQuery to register an element, set an id to the element and listen to events like so:
$('#myButton').on('click', function(event) {
event.preventDefault(); // To prevent following the link (optional)
...
});
You can also use inline javascript in the onclick attribute:
<a ... onclick="myFunc();">..</a>
I prefer to do the cast, but not manually. My favorite is using g_new
and g_new0
macros from glib. If glib is not used, I would add similar macros. Those macros reduce code duplication without compromising type safety. If you get the type wrong, you would get an implicit cast between non-void pointers, which would cause a warning (error in C++). If you forget to include the header that defines g_new
and g_new0
, you would get an error. g_new
and g_new0
both take the same arguments, unlike malloc
that takes fewer arguments than calloc
. Just add 0
to get zero-initialized memory. The code can be compiled with a C++ compiler without changes.
bool IsPalindrome(const char* psz)
{
int i = 0;
int j;
if ((psz == NULL) || (psz[0] == '\0'))
{
return false;
}
j = strlen(psz) - 1;
while (i < j)
{
if (psz[i] != psz[j])
{
return false;
}
i++;
j--;
}
return true;
}
// STL string version:
bool IsPalindrome(const string& str)
{
if (str.empty())
return false;
int i = 0; // first characters
int j = str.length() - 1; // last character
while (i < j)
{
if (str[i] != str[j])
{
return false;
}
i++;
j--;
}
return true;
}
It's the null coalescing operator.
http://msdn.microsoft.com/en-us/library/ms173224.aspx
Yes, nearly impossible to search for unless you know what it's called! :-)
EDIT: And this is a cool feature from another question. You can chain them.
People are saying "call exit(return code)," but this is bad form. In small programs it is fine, but there are a number of issues with this:
Really, the only time you should exit the problem is with this line in main.cpp:
return 0;
If you are using exit() to handle errors, you should learn about exceptions (and nesting exceptions), as a much more elegant and safe method.
You can use the following formula,
=IF(ISTEXT(REGEXEXTRACT(A1; "Bla")); "Yes";"No")
You can create a string[]
(string array) that contains your string
like :
string someString = "something";
string[] stringArray = new string[]{ someString };
The variable stringArray
will now have a length of 1 and contain someString
.
org.glassfish.jersey.servlet.ServletContainer.class
here remove .class
org.glassfish.jersey.servlet.ServletContainer now you wont get
See C# Operators for C# operators including OR which is ||
Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:
Each marker gets an "infowindow" entry :
function createMarker(lat, lon, html) {
var newmarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
title: html
});
newmarker['infowindow'] = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(newmarker, 'mouseover', function() {
this['infowindow'].open(map, this);
});
}
For MAVEN,
I tried all of the above methods, but couldn't find the solution,
So below are the steps I tried(A mix of some solutions),
mvn clean
mvn idea:clean
(Make sure you don't have extra .iml files other than the project/subprojects .iml files)
I have created a project for basic pinch-zoom that supports Android 2.1+
Available here
You can also use button click event like this:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="MyButtonClick" />
</ItemTemplate>
</asp:TemplateField>
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}
You can do like this to get data:
void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple ButtonField column fields are used, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Select")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Get the last name of the selected author from the appropriate
// cell in the GridView control.
GridViewRow selectedRow = CustomersGridView.Rows[index];
}
}
and Button in gridview should have command like this and handle rowcommand event:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
onrowcommand="CustomersGridView_RowCommand"
runat="server">
<columns>
<asp:buttonfield buttontype="Button"
commandname="Select"
headertext="Select Customer"
text="Select"/>
</columns>
</asp:gridview>
Here is very good visual representation about continue and break statements
The following worked for me:
from pandas import read_excel
my_sheet = 'Sheet1' # change it to your sheet name, you can find your sheet name at the bottom left of your excel file
file_name = 'products_and_categories.xlsx' # change it to the name of your excel file
df = read_excel(file_name, sheet_name = my_sheet)
print(df.head()) # shows headers with top 5 rows
Use file_get_contents
in combination with json_decode
and echo
.
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
}
or you can use like this also
tableView.estimatedSectionHeaderHeight
What works for me on /FF and /Chrome:
body {
position: fixed;
width: 100%;
height: 100%;
}
overflow: hidden
just disables display of the scrollbars. (But you can put it in there if you like to).
There is one drawback I found: If you use this method on a page which you want only temporarily to stop scrolling, setting position: fixed
will scroll it to the top.
This is because position: fixed uses absolute positions which are currently set to 0/0.
This can be repaired e.g. with jQuery:
var lastTop;
function stopScrolling() {
lastTop = $(window).scrollTop();
$('body').addClass( 'noscroll' )
.css( { top: -lastTop } )
;
}
function continueScrolling() {
$('body').removeClass( 'noscroll' );
$(window).scrollTop( lastTop );
}
Here's a rewrite of the accepted answer that ideally clarifies the advantages/risks of possible approaches:
You're trying to cherry pick fd9f578, which was a merge with two parents.
Instead of cherry-picking a merge, the simplest thing is to cherry pick the commit(s) you actually want from each branch in the merge.
Since you've already merged, it's likely all your desired commits are in your list. Cherry-pick them directly and you don't need to mess with the merge commit.
The way a cherry-pick works is by taking the diff that a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying the changeset to your current branch.
If a commit has two or more parents, as is the case with a merge, that commit also represents two or more diffs. The error occurs because of the uncertainty over which diff should apply.
If you determine you need to include the merge vs cherry-picking the related commits, you have two options:
(More complicated and obscure; also discards history) you can indicate which parent should apply.
Use the -m
option to do so. For example, git cherry-pick -m 1 fd9f578
will use the first parent listed in the merge as the base.
Also consider that when you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m
into that one commit. You lose all their history, and glom together all their diffs. Your call.
(Simpler and more familiar; preserves history) you can use git merge
instead of git cherry-pick
.
git merge
, it will attempt to apply all commits that exist on the branch you are merging, and list them individually in your git log.Use a recursive query. Given
create table t (a int, b int, c int);
Run:
with recursive
a (cid, name) as (select cid, name from pragma_table_info('t')),
b (cid, name) as (
select cid, '|' || name || '|' from a where cid = 0
union all
select a.cid, b.name || a.name || '|' from a join b on a.cid = b.cid + 1
)
select name
from b
order by cid desc
limit 1;
Alternatively, just use group_concat
:
select '|' || group_concat(name, '|') || '|' from pragma_table_info('t')
Both yield:
|a|b|c|
It's simple-
SELECT empname,
empid,
(SELECT COUNT (profileid)
FROM profile
WHERE profile.empid = employee.empid)
AS number_of_profiles
FROM employee;
It is even simpler when you use a table join like this:
SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;
Explanation for the subquery:
Essentially, a subquery in a select
gets a scalar value and passes it to the main query. A subquery in select
is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count
to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null
to the main query. Moreover, a subquery can access columns from the from
clause of the main query, as shown in my query where employee.empid
is passed from the outer query to the inner query.
Edit:
When you use a subquery in a select
clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.
Explanation for the left join
A left join is very handy, especially when you want to replace the select
subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN
keyword.
For more information read Oracle Docs on subqueries and left join or left outer join.
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
And during driver setup:
device_create_file(dev, &dev_attr_version);
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
For those who might have the same problem as me, I got this error when the DB I was using was actually master, and not the DB I should have been using.
Just put use [DBName]
on the top of your script, or manually change the DB in use in the SQL Server Management Studio GUI.
To add to vfilby's answer, you can just perform a RegEx replace within your code; no new classes are necessary. In case other newbies like myself stumple upon this question.
using System.Text.RegularExpressions;
Then...
private string StripHtml(string source)
{
string output;
//get rid of HTML tags
output = Regex.Replace(source, "<[^>]*>", string.Empty);
//get rid of multiple blank lines
output = Regex.Replace(output, @"^\s*$\n", string.Empty, RegexOptions.Multiline);
return output;
}
As per docker-compose 1.6.0:
You can now specify both a build and an image key if you're using the new file format.
docker-compose build
will build the image and tag it with the name you've specified, whiledocker-compose pull
will attempt to pull it.
So your docker-compose.yml
would be
version: '2'
services:
wildfly:
build: /path/to/dir/Dockerfile
image: wildfly_server
ports:
- 9990:9990
- 80:8080
To update docker-compose
sudo pip install -U docker-compose==1.6.0
With get()
method you get a collection (all data that match the query), try to use first()
instead, it return only one element, like this:
$about = Page::where('page', 'about-me')->first();
sudo apt-get install ia32-libs
you just use the :nth-child(num) in css for add the colspan like
<style>
div.table
{
display:table;
width:100%;
}
div.table-row
{
display:table-row;
}
div.table-td
{
display:table-cell;
}
div.table-row:nth-child(1)
{
display:block;
}
</style>
<div class="table>
<div class="table-row">test</div>
<div class="table-row">
<div class="table-td">data1</div>
<div class="table-td">data2</div>
</div>
</div>
You are getting that error because when the param1
if statements are evaluated, param is always null due to being scoped variables without delayed expansion.
When parentheses are used, all the commands and variables within those parentheses are expanded. And at that time, param1 has no value making the if statements invalid. When using delayed expansion, the variables are only expanded when the command is actually called.
Also I recommend using if not defined
command to determine if a variable is set.
@echo off
setlocal EnableExtensions EnableDelayedExpansion
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.
set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if not defined a goto :aPrompt
echo %a%
IF "%a%"=="2" (
title USB WRITE LOCK
echo What do you want to do?
echo 1.Apply USB Write Protection
echo 2.Remove USB Write Protection
::param1
set "param1=%globalparam2%"
goto :param1Check
:param1Prompt
set /p "param1=Enter Choice: "
:param1Check
if not defined param1 goto :param1Prompt
echo !param1!
if "!param1!"=="1" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001
echo USB Write is Locked!
)
if "!param1!"=="2" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
echo USB Write is Unlocked!
)
)
pause
endlocal
Yes you only need $()
when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind.
$(this)[0] === this
Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it's going to be in the first element.
$("#myDiv")[0] === document.getElementById("myDiv");
And so on...
I don't know about your Spring/JAXB combination, but the average REST webservice won't return a response body on POST/PUT, just a response status. You'd like to determine it instead of the body.
Replace
InputStream response = con.getInputStream();
by
int status = con.getResponseCode();
All available status codes and their meaning are available in the HTTP spec, as linked before. The webservice itself should also come along with some documentation which overviews all status codes supported by the webservice and their special meaning, if any.
If the status starts with 4nn
or 5nn
, you'd like to use getErrorStream()
instead to read the response body which may contain the error details.
InputStream error = con.getErrorStream();
Be careful, the solution proposed with $a = array_combine($a, $a);
will not work for numeric values.
I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384)
to be the keys as well as the values however PHP manual states:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
So I solved it like this:
foreach($array as $key => $val) {
$new_array[$val]=$val;
}
isset() only checks if a variable is set.. Has got nothing to do with size or what the array contains
For anyone who make it in bigger scale, you might have also check how many file descriptors you have. It will throw this error if you ran out at bad moment.
There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.
cast(str_column as int)
class CountryListView(ListView):
model = Country
def render_to_response(self, context, **response_kwargs):
return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json")
fixed the problem
also mimetype is important.
Use max-width
property of CSS, like this :
img{
max-width:100%;
}
The easiest and the most effective way would be to allow eclipse to generate and override the equals and hashcode method. Just select the attributes to be checked for duplicates when prompted and you should be all set.
Also once the list is ready, put it into a Set and you have the duplicates gone.
For camera access use:
<key>NSCameraUsageDescription</key>
<string>Camera Access Warning</string>
This works too:
String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
Note:
String regex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <http://google.com>
String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <http://google.com>
So probably the first one is more useful for general use.
I had to move the folders inside a folder named "default" to the android-## folder so Eclipse could see the images.
Uninstall(delete) this: jre, jdk, eclipse. Download 32 bit(x86) version of this programs:jre, jdk, eclipse. And install it.
For max value, we can write sql query as
select age from table_name order by age desc limit 1
same way we can write in mongodb too.
db.getCollection('collection_name').find().sort({"age" : -1}).limit(1); //max age
db.getCollection('collection_name').find().sort({"age" : 1}).limit(1); //min age
$http.delete
method doesn't accept request body.
You can try this workaround :
$http( angular.merge({}, config || {}, {
method : 'delete',
url : _url,
data : _data
}));
where in config
you can pass config data like headers etc.
What version of WPF are you using? I tried in both 3.5 and 4.0, and Fill="#FF000000" should work fine in a in the XAML. There is another syntax, however, if it doesn't. Here's a 3.5 XAML that I tested with two different ways. Better yet would be to use a resource.
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Rectangle Height="100" HorizontalAlignment="Left" Margin="100,12,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="200" Fill="#FF00AE00" />
<Rectangle Height="100" HorizontalAlignment="Left" Margin="100,132,0,0" Name="rectangle2" Stroke="Black" VerticalAlignment="Top" Width="200" >
<Rectangle.Fill>
<SolidColorBrush Color="#FF00AE00" />
</Rectangle.Fill>
</Rectangle>
</Grid>
create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS) from PLAYERREGULARSEASON where TEAM = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;
END;
/
2 steps to check if a cronjob is working :
Manually run php command :
/usr/bin/php /mydomain.in/cromail.php
And check if any error is displayed
This is a combination nt.bas's answer and step 9 of Civic's answer with visual examples because it took me a while to find out what was intended since I am new to Android Studio. It has been tested in Android Studio 3.2.1.
Open the project you want to clone in Android Studio. (In this example, the old project name was test5
and the new project name was test6
)
In the left file-overview pane, click: Project (where it might currently say android).
Open app/res/values/strings.xml and change name of the old project (e.g. test5) to the new name of the project in line:
<string name="app_name">test5</string>
Open Gradle scripts/build.gradle (Module:app) and change the line to the same line with your new project name:%fig4
applicationId "com.example.a.test5"
Just Use this method and pass your lat, long.
public static void getAddress(Context context, double LATITUDE, double LONGITUDE) {
//Set Address
try {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
Log.d(TAG, "getAddress: address" + address);
Log.d(TAG, "getAddress: city" + city);
Log.d(TAG, "getAddress: state" + state);
Log.d(TAG, "getAddress: postalCode" + postalCode);
Log.d(TAG, "getAddress: knownName" + knownName);
}
} catch (IOException e) {
e.printStackTrace();
}
return;
}
std::fill(v.begin(), v.end(), 0);
ArrayList<Integer> a = new ArrayList<Number>();
Does not work because the fact that Number is a super class of Integer does not mean that List<Number>
is a super class of List<Integer>
. Generics are removed during compilation and do not exist on runtime, so parent-child relationship of collections cannot be be implemented: the information about element type is simply removed.
ArrayList<? extends Object> a1 = new ArrayList<Object>();
a1.add(3);
I cannot explain why it does not work. It is really strange but it is a fact. Really syntax <? extends Object>
is mostly used for return values of methods. Even in this example Object o = a1.get(0)
is valid.
ArrayList<?> a = new ArrayList<?>()
This does not work because you cannot instantiate list of unknown type...
This may be a long shot, but Crystal Reports for Eclipse is free. I'm not sure if it will work, but if all you need is to edit some static text, you could get that version of CR and get the job done.
The /P
switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
Two ways I've used it... first:
SET /P variable=
When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.
And second:
SET /P variable=<%temp%\filename.txt
Will set variable to contents (the first line) of the txt file. This method won't work unless the /P
is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.
color: transparent;
make the tricks for me
#videos-part:before{
font-size: 35px;
line-height: 33px;
width: 16px;
color: transparent;
content: 'AS YOU LIKE';
background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDUwIDUwIiBoZWlnaHQ9IjUwcHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA1MCA1MCIgd2lkdGg9IjUwcHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik04LDE0TDQsNDloNDJsLTQtMzVIOHoiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzAwMDAwMCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbWl0ZXJsaW1pdD0iMTAiIHN0cm9rZS13aWR0aD0iMiIvPjxyZWN0IGZpbGw9Im5vbmUiIGhlaWdodD0iNTAiIHdpZHRoPSI1MCIvPjxwYXRoIGQ9Ik0zNCwxOWMwLTEuMjQxLDAtNi43NTksMC04ICBjMC00Ljk3MS00LjAyOS05LTktOXMtOSw0LjAyOS05LDljMCwxLjI0MSwwLDYuNzU5LDAsOCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwMDAwIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1taXRlcmxpbWl0PSIxMCIgc3Ryb2tlLXdpZHRoPSIyIi8+PGNpcmNsZSBjeD0iMzQiIGN5PSIxOSIgcj0iMiIvPjxjaXJjbGUgY3g9IjE2IiBjeT0iMTkiIHI9IjIiLz48L3N2Zz4=');
background-size: 25px;
background-repeat: no-repeat;
}
Got an answer for this problem without using ExifInterface. We can get the rotation of the camera either front camera or back camera whichever you are using then while creating the Bitmap we can rotate the bitmap using Matrix.postRotate(degree)
public int getRotationDegree() {
int degree = 0;
for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
degree = info.orientation;
return degree;
}
}
return degree;
}
After calculating the rotation you can rotate you bitmap like below:
Matrix matrix = new Matrix();
matrix.postRotate(getRotationDegree());
Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
Herare bm should be your bitmap.
If you want to know the rotation of your front camera just change Camera.CameraInfo.CAMERA_FACING_BACK to Camera.CameraInfo.CAMERA_FACING_FRONT above.
I hope this helps.
The best simple plug and play solution for pagination.
https://ciphertrick.com/2015/06/01/search-sort-and-pagination-ngrepeat-angularjs/#comment-1002
you would jus need to replace ng-repeat with custom directive.
<tr dir-paginate="user in userList|filter:search |itemsPerPage:7">
<td>{{user.name}}</td></tr>
Within the page u just need to add
<div align="center">
<dir-pagination-controls
max-size="100"
direction-links="true"
boundary-links="true" >
</dir-pagination-controls>
</div>
In your index.html load
<script src="./js/dirPagination.js"></script>
In your module just add dependencies
angular.module('userApp',['angularUtils.directives.dirPagination']);
and thats all needed for pagination.
Might be helpful for someone.
You can put custom image in radiobutton like normal button. for that create one XML file in drawable folder e.g
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/sub_screens_aus_hl"
android:state_pressed="true"/>
<item android:drawable="@drawable/sub_screens_aus"
android:state_checked="true"/>
<item android:drawable="@drawable/sub_screens_aus"
android:state_focused="true" />
<item android:drawable="@drawable/sub_screens_aus_dis" />
</selector>
Here you can use 3 different images for radiobutton
and use this file to RadioButton like:
android:button="@drawable/aus"
android:layout_height="120dp"
android:layout_width="wrap_content"
You can also move mounted
out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.
function init() {
// Use `this` normally
}
new Vue({
methods:{
init
},
mounted(){
init.call(this)
}
})
BEGIN
-END
blocks are the building blocks of PL/SQL, and each PL/SQL unit is contained within at least one such block. Nesting BEGIN
-END
blocks within PL/SQL blocks is usually done to trap certain exceptions and handle that special exception and then raise unrelated exceptions. Nevertheless, in PL/SQL you (the client) must always issue a commit or rollback for the transaction.
If you wish to have atomic transactions within a PL/SQL containing transaction, you need to declare a PRAGMA AUTONOMOUS_TRANSACTION
in the declaration block. This will ensure that any DML within that block can be committed or rolledback independently of the containing transaction.
However, you cannot declare this pragma for nested blocks. You can only declare this for:
Reference: Oracle
The first line of a paragraph is indented by default, thus whether or not you have \indent
there won't make a difference. \indent
and \noindent
can be used to override default behavior. You can see this by replacing your line with the following:
Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented
\noindent override default indentation (not indented)\\
asdf
I found that The Boolean Expression Reducer is much easier to use than Logic Friday. Plus it doesn't require installation and is multi-platform (Java).
Also in Logic Friday the expression A | B
just returns 3 entries in truth table; I expected 4.
IMO, it's better to use the install
command in such situations. I was trying to make systemd-journald
persistent across reboots.
install -d -g systemd-journal -m 2755 -v /var/log/journal
If you're using scss for your styles you can use a mixin to help generate the code. Your styles will quickly get out of hand if you put all the properties every time.
This is a very simple example - really nothing more than a proof of concept, you can extend this with multiple properties and rules as needed.
@mixin mat-table-columns($columns)
{
.mat-column-
{
@each $colName, $props in $columns {
$width: map-get($props, 'width');
&#{$colName}
{
flex: $width;
min-width: $width;
@if map-has-key($props, 'color')
{
color: map-get($props, 'color');
}
}
}
}
}
Then in your component where your table is defined you just do this:
@include mat-table-columns((
orderid: (width: 6rem, color: gray),
date: (width: 9rem),
items: (width: 20rem)
));
This generates something like this:
.mat-column-orderid[_ngcontent-c15] {
flex: 6rem;
min-width: 6rem;
color: gray; }
.mat-column-date[_ngcontent-c15] {
flex: 9rem;
min-width: 9rem; }
In this version width
becomes flex: value; min-width: value
.
For your specific example you could add wrap: true
or something like that as a new parameter.
In the case of winforms:
If you include the images to your resources you can do it like this, very simple and straight forward:
public Form1()
{
InitializeComponent();
button1.MouseEnter += new EventHandler(button1_MouseEnter);
button1.MouseLeave += new EventHandler(button1_MouseLeave);
}
void button1_MouseLeave(object sender, EventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
}
void button1_MouseEnter(object sender, EventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
I would not recommend hardcoding image paths.
As you have altered your question ...
There is no (on)MouseOver in winforms afaik, there are MouseHover and MouseMove events, but if you change image on those, it will not change back, so the MouseEnter + MouseLeave are what you are looking for I think. Anyway, changing the image on Hover or Move :
in the constructor:
button1.MouseHover += new EventHandler(button1_MouseHover);
button1.MouseMove += new MouseEventHandler(button1_MouseMove);
void button1_MouseMove(object sender, MouseEventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
void button1_MouseHover(object sender, EventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
To add images to your resources: Projectproperties/resources/add/existing file
I made code for imageview with pinch to zoom using zoomageview. so user can drag the image off the screen and zoom-In , zoom-out the image.
You can follow this link
to get the Step By Step
Code and also given Output Screenshot.
I got the "No signing certificate" error when running Xcode 11.3 on macOS 10.14.x Mojave. (but after Xcode 12 was released.)
I was also using Fastlane. My fix was to set generate_apple_certs
to false
when running Match. This seemed to generate signing certificates that were backwards-compatible with Xcode 11.3
Match documentation - https://docs.fastlane.tools/actions/match/
This is the relevant section of my Fastfile:
platform :ios do
lane :certs do
force = false
match(type: "development", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.dev")
match(type: "adhoc", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.beta")
match(type: "appstore", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier")
end
...
ISO standards cost money, from a moderate amount (for a PDF version), to a bit more (for a book version).
While they aren't finalised however, they can usually be found online, as drafts. Most of the times the final version doesn't differ significantly from the last draft, so while not perfect, they'll suit just fine.
I only change/remove the class:
function removeClass() {
var element = angular.element('#nameInput');
element.removeClass('nameClass');
};
To access field or method of an object use dot .
:
user = User()
print user.fullName
If a name of the field will be defined at run time, use buildin getattr
function:
field_name = "fullName"
print getattr(user, field_name) # prints content of user.fullName
The most comfortable way to preview HTML files on GitHub is to go to https://htmlpreview.github.io/ or just prepend it to the original URL, i.e.: https://htmlpreview.github.io/?https://github.com/bartaz/impress.js/blob/master/index.html
The DOM element style "property" is a readonly collection of all the style attributes defined on the element. (The collection property is readonly, not necessarily the items within the collection.)
You would be better off using the className "property" on the elements.
This worked for me.
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
DataSet ds = new DataSet();
ds.ReadXml(sr);
ds.Namespace = "";
string outXML = ds.GetXml();
ds.Dispose();
sr.Dispose();
fs.Dispose();
For what it's worth, here's my .bash_profile, that works well for me on a mac with Atom, after installing go with Homebrew:
export GOROOT=`go env GOROOT`
export GOPATH=/Users/yy/Projects/go
export GOBIN=$GOPATH/bin
export PATH=$PATH:$GOBIN
In the simplest terms:
--soft
: uncommit changes, changes are left staged (index).--mixed
(default): uncommit + unstage changes, changes are left in working tree.--hard
: uncommit + unstage + delete changes, nothing left.when you are in El Capitan, will get error: ln: /usr/lib/libmysqlclient.18.dylib: Operation not permitted
need to close the "System Integrity Protection".
first, reboot and hold on cmd + R to enter the Recovery mode, then launch the terminal and type the command: csrutil disable
, now you can reboot and try again.
Instead of using <source>
tag, use <src>
attribute of <video>
as below and you will see the action.
<video width="320" height="240" src="mov1.mov"></video>
or
you can give multiple tags within the tag, each with a different video source. The browser will automatically go through the list and pick the first one it’s able to play. For example:
<video id="sampleMovie" width="640" height="360" preload controls>
<source src="HTML5Sample_H264.mov" />
<source src="HTML5Sample_Ogg.ogv" />
<source src="HTML5Sample_WebM.webm" />
</video>
If you test that code in Chrome, you’ll get the H.264 video. Run it in Firefox, though, and you’ll see the Ogg video in the same place.
Are you sure your HTML form is correct, and does, in fact, do an HTTP POST? I would suggest running Fiddler2, and then trying to log in via your Login.aspx, then the remote HTML site, and then comparing the requests that are sent to the server. For me, ASP.Net always worked fine -- if HTTP request contains a valid POST, I can get to values using Request.Form...
Similarly to @brucexin I needed to get OS-level thread identifier (which != thread.get_ident()
) and use something like below not to depend on particular numbers and being amd64-only:
---- 8< ---- (xos.pyx)
"""module xos complements standard module os"""
cdef extern from "<sys/syscall.h>":
long syscall(long number, ...)
const int SYS_gettid
# gettid returns current OS thread identifier.
def gettid():
return syscall(SYS_gettid)
and
---- 8< ---- (test.py)
import pyximport; pyximport.install()
import xos
...
print 'my tid: %d' % xos.gettid()
this depends on Cython though.
foo.instance_of? String
or
foo.kind_of? String
if you you only care if it is derrived from String
somewhere up its inheritance chain
Just define an empty navbar prior to the fixed one, it will create the space needed.
<nav class="navbar navbar-default ">
</nav>
<nav class="navbar navbar-default navbar-fixed-top ">
<div class="container-fluid">
// Your menu code
</div>
</nav>
You can use the approach below, it works fine:
getActivity().getSupportFragmentManager().popBackStack();
The easiest way to do this, as noted by Umar is, for example
mysql> SET GLOBAL time_zone = 'America/New_York';
Using the named timezone is important for timezone that has a daylights saving adjustment. However, for some linux builds you may get the following response:
#1298 - Unknown or incorrect time zone
If you're seeing this, you may need to run a tzinfo_to_sql translation... it's easy to do, but not obvious. From the linux command line type in:
mysql_tzinfo_to_sql /usr/share/zoneinfo/|mysql -u root mysql -p
Provide your root password (MySQL root, not Linux root) and it will load any definitions in your zoneinfo into mysql. You can then go back and run your
mysql> SET GLOBAL time_zone = timezone;
According to my research there is no way to do this exactly the way you want. You can manually re-create the table and copy the data, or SSMS can (and will) do this for you (when you drag and drop a column to a different order, it does this). In fact it souldn't matter what order the columns are... As an alternative solution you can select the data you want in the order you desired. For example, instead of using asterisk (*) in select, specify the column names in some order... Lets say MyTable has col1, col2, col3, colNew columns.
Instead of:
SELECT * FROM MyTable
You can use:
SELECT col1, colNew, col2, col3 FROM MyTable
One of the usage of nameof
keyword is for setting Binding
in wpf programmatically.
to set Binding
you have to set Path
with string, and with nameof
keyword, it's possible to use Refactor option.
For example, if you have IsEnable
dependency property in your UserControl
and you want to bind it to IsEnable
of some CheckBox
in your UserControl
, you can use these two codes:
CheckBox chk = new CheckBox();
Binding bnd = new Binding ("IsEnable") { Source = this };
chk.SetBinding(IsEnabledProperty, bnd);
and
CheckBox chk = new CheckBox();
Binding bnd = new Binding (nameof (IsEnable)) { Source = this };
chk.SetBinding(IsEnabledProperty, bnd);
It's obvious the first code can't refactor but the secend one...
File
--> Setting
project
section --> Project interpreter
Project interpreter
[NOTE]:
Tested on Pycharm 2018 and 2017.
Visual Studio's Error List pane only shows you the first line of the error. Invoke View
>Output
and I bet you'll see something like:
c:\path\to\your\code.cpp(42): error C2259: 'AmbientOccluder' : cannot instantiate abstract class
due to following members:
'ULONG MysteryUnimplementedMethod(void)' : is abstract
c:\path\to\some\include.h(8) : see declaration of 'MysteryUnimplementedMethod'
You can use the u
button to undo the last modification. (And Ctrl+R to redo it).
Read more about it at: http://vim.wikia.com/wiki/Undo_and_Redo
If it needs to run on the onload
event of the page, meaning that the document and all its assets have loaded, this needs to be in a content script embedded in each page for which you wish to track onload
.
If you want just to test a cross domain application in which the browser blocks your request, then you can just open your browser in unsafe mode and test your application without changing your code and without making your code unsafe. From MAC OS you can do this from the terminal line:
open -a Google\ Chrome --args --disable-web-security --user-data-dir
Reading CSV format description makes me feel that using 3rd party library would be less headache than writing it myself:
Wikipedia lists 10 or something known libraries:
I compared libs listed using some kind of check list. OpenCSV turned out a winner to me (YMMV) with the following results:
+ maven
+ maven - release version // had some cryptic issues at _Hudson_ with snapshot references => prefer to be on a safe side
+ code examples
+ open source // as in "can hack myself if needed"
+ understandable javadoc // as opposed to eg javadocs of _genjava gj-csv_
+ compact API // YAGNI (note *flatpack* seems to have much richer API than OpenCSV)
- reference to specification used // I really like it when people can explain what they're doing
- reference to _RFC 4180_ support // would qualify as simplest form of specification to me
- releases changelog // absence is quite a pity, given how simple it'd be to get with maven-changes-plugin // _flatpack_, for comparison, has quite helpful changelog
+ bug tracking
+ active // as in "can submit a bug and expect a fixed release soon"
+ positive feedback // Recommended By 51 users at sourceforge (as of now)
I got the same problem after upgrading java from 1.8.0_202 to 1.8.0_211
Problem:
Here are directories where new version of 1.8.0_211 of Java installed:
Directory of c:\Program Files\Java\jre1.8.0_211\bin Directory of c:\Program Files (x86)\Common Files\Oracle\Java\javapath
So one is located in 32 bit and second is in 64 bit Program files folder. The one that is specified in the PATH is 32 bit version (c:\Program Files (x86)\Common Files\Oracle\Java\javapath), even though it was 64 bit version of the Java that was installed.
Solution:
Change system environments variable PATH from c:\Program Files (x86)\Common Files\Oracle\Java\javapath to c:\Program Files\Java\jre1.8.0_211\bin
The first thing you need to decide is whether the data structure needs to be mutable or not. As has been mentioned, lists are mutable, tuples are not. This also means that tuples can be used for dictionary keys, wheres lists cannot.
In my experience, tuples are generally used where order and position is meaningful and consistant. For example, in creating a data structure for a choose your own adventure game, I chose to use tuples instead of lists because the position in the tuple was meaningful. Here is one example from that data structure:
pages = {'foyer': {'text' : "some text",
'choices' : [('open the door', 'rainbow'),
('go left into the kitchen', 'bottomless pit'),
('stay put','foyer2')]},}
The first position in the tuple is the choice displayed to the user when they play the game and the second position is the key of the page that choice goes to and this is consistent for all pages.
Tuples are also more memory efficient than lists, though I'm not sure when that benefit becomes apparent.
Also check out the chapters on lists and tuples in Think Python.
No need to do your own implementation. I can recommend using geolocationmarker
from google-maps-utility-library-v3.
The path is in the registry but usually you edit through this interface:
Control Panel
-> System
-> System settings
-> Environment Variables
.PATH
.c:\path;c:\path2
This work for me
<%= f.select :status, [["Single", "single"], ["Married", "married"], ["Engaged", "engaged"], ["In a Relationship", "relationship"]], {}, {class: "form-control"} %>
ui-router v1.0.18
introduces support for ng-disabled
on anchor tags
Example: <a ui-sref="go" ng-disabled="true">nogo</a>
the easiest way is to use position:absolute
on both elements. You can absolutely position relative to the page, or you can absolutely position relative to a container div by setting the container div to position:relative
<div id="container" style="position:relative;">
<div id="div1" style="position:absolute; top:0; left:0;"></div>
<div id="div2" style="position:absolute; top:0; left:0;"></div>
</div>
Here is simple way to delete:
public void deleteItem(Item item) {
SQLiteDatabase db = getWritableDatabase();
String whereClause = "id=?";
String whereArgs[] = {item.id.toString()};
db.delete("Items", whereClause, whereArgs);
}
Here whereClause
is optional, passing null will delete all rows in table. delete function will return number of affected row if whereClause
passed otherwise will return 0.
Important Note: If you want to remove all rows and require count of deleted ones also then pass 1 as
whereClause
.
I believe this does it:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
It's got built-in patterns for stuff like URLs and e-mail addresses, and I think you can have it use your own as well.
background.xml in drawable folder.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke
android:width="3dp"
android:color="#0FECFF" />
//specify gradient
<gradient
android:startColor="#ffffffff"
android:endColor="#110000FF"
android:angle="90"/>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:orientation="vertical"
android:layout_marginBottom="10dp"
android:background="@drawable/background">
You can check the String.match
() or the String.indexOf()
methods.
I'm guessing - are you trying to create Dialog using.
getApplicationContext()
mContext which is passed by activity.
if You displaying dialog non activity class then you have to pass activity as a parameter.
Activity activity=YourActivity.this;
Now it will be work great.
If you find any trouble then let me know.
Do you mean full calendar days, or groups of 24 hours?
For simply 24 hours, assuming you're using Python's datetime, then the timedelta object already has a days property:
days = (a - b).days
For calendar days, you'll need to round a down to the nearest day, and b up to the nearest day, getting rid of the partial day on either side:
roundedA = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
roundedB = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
days = (roundedA - roundedB).days
You can easily create your own style of arrow with the .slick-next:before
and the .slick-prev:after
pseudo-classes.
Here's an example:
.slick-prev:before {
content: "<";
color: red;
font-size: 30px;
}
.slick-next:before {
content: ">";
color: red;
font-size: 30px;
}
In these two lines:
mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
frame = cv2.circle(frame,(a, b),5,color[i].tolist(),-1)
try instead:
cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
cv2.circle(frame,(a, b),5,color[i].tolist(),-1)
I had the same problem and the variables were being returned empty
If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.
Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.
If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.
There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd
on Mac and ifconfig
works differently.
The following table is useful for knowing the various unix shells.
sh The original Bourne shell Present on every unix system
ksh Original Korn shell Richer shell programming environment than sh
csh Original C-shell C-like syntax; early versions buggy
tcsh Enhanced C-shell User-friendly and less buggy csh implementation
bash GNU Bourne-again shell Enhanced and free sh implementation
zsh Z shell Enhanced, user-friendly ksh-like shell
You may also find these guides helpful:
http://homepage.mac.com/rgriff/files/TerminalBasics.pdf
http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html
On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile
on OSX) file with aliases, some examples below.
I now placed all my aliases in a separate .bash_aliases file and include it with:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
in the .bashrc or .bash_profile file.
Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto
. The first time I did this (without knowing) I redefined ls
to be invalid which was a bit alarming until I removed --auto-color
!
You may also find https://unix.stackexchange.com/q/127799/10043 useful
# ~/.bash_aliases
# ls variants
#alias l='ls -CF'
alias la='ls -A'
alias l='ls -alFtr'
alias lsd='ls -d .*'
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i'
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed'
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status'
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'
else if (File.Exists(path))
{
using (StreamWriter w = File.AppendText(path))
{
w.WriteLine("The next line!");
w.Close();
}
}
You typically use it when you want to instantiate something the first time its actually used. This delays the cost of creating it till if/when it's needed instead of always incurring the cost.
Usually this is preferable when the object may or may not be used and the cost of constructing it is non-trivial.
Simplyfing for the begginers:
If you want to select an element immediatly after another element you use the +
selector.
For example:
div + p
The "+" element selects all <p>
elements that are placed immediately after <div>
elements
If you want to learn more about selectors use this table
That's a lot of work for:
public static int byteArrayToLeInt(byte[] b) {
final ByteBuffer bb = ByteBuffer.wrap(b);
bb.order(ByteOrder.LITTLE_ENDIAN);
return bb.getInt();
}
public static byte[] leIntToByteArray(int i) {
final ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.putInt(i);
return bb.array();
}
This method uses the Java ByteBuffer
and ByteOrder
functionality in the java.nio
package. This code should be preferred where readability is required. It should also be very easy to remember.
I've shown Little Endian byte order here. To create a Big Endian version you can simply leave out the call to order(ByteOrder)
.
In code where performance is higher priority than readability (about 10x as fast):
public static int byteArrayToLeInt(byte[] encodedValue) {
int value = (encodedValue[3] << (Byte.SIZE * 3));
value |= (encodedValue[2] & 0xFF) << (Byte.SIZE * 2);
value |= (encodedValue[1] & 0xFF) << (Byte.SIZE * 1);
value |= (encodedValue[0] & 0xFF);
return value;
}
public static byte[] leIntToByteArray(int value) {
byte[] encodedValue = new byte[Integer.SIZE / Byte.SIZE];
encodedValue[3] = (byte) (value >> Byte.SIZE * 3);
encodedValue[2] = (byte) (value >> Byte.SIZE * 2);
encodedValue[1] = (byte) (value >> Byte.SIZE);
encodedValue[0] = (byte) value;
return encodedValue;
}
Just reverse the byte array index to count from zero to three to create a Big Endian version of this code.
Notes:
Integer.BYTES
constant, which is more succinct than Integer.SIZE / Byte.SIZE
.Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point
Inspired by unutbu
print(df.dtypes) #Make sure the format is 'object'. Rerunning this after index will not show values.
columnName = 'YourColumnName'
df[columnName+'index'] = df[columnName] #Create a new column for index
df.set_index(columnName+'index', inplace=True) #To build index on the timestamp/dates
df.loc['2020-09-03 01:00':'2020-09-06'] #Select range from the index. This is your new Dataframe.
Use the following code
$("#modal").trigger('click');
A HashSet
holds a set of objects, but in a way that it allows you to easily and quickly determine whether an object is already in the set or not. It does so by internally managing an array and storing the object using an index which is calculated from the hashcode of the object. Take a look here
HashSet
is an unordered collection containing unique elements. It has the standard collection operations Add, Remove, Contains, but since it uses a hash-based implementation, these operations are O(1). (As opposed to List for example, which is O(n) for Contains and Remove.) HashSet
also provides standard set operations such as union, intersection, and symmetric difference. Take a look here
There are different implementations of Sets. Some make insertion and lookup operations super fast by hashing elements. However, that means that the order in which the elements were added is lost. Other implementations preserve the added order at the cost of slower running times.
The HashSet
class in C# goes for the first approach, thus not preserving the order of elements. It is much faster than a regular List
. Some basic benchmarks showed that HashSet is decently faster when dealing with primary types (int, double, bool, etc.). It is a lot faster when working with class objects. So that point is that HashSet is fast.
The only catch of HashSet
is that there is no access by indices. To access elements you can either use an enumerator or use the built-in function to convert the HashSet
into a List
and iterate through that. Take a look here
In Unix shells, you can quote almost every character in single quotes '
. Except the single quote itself, and you can't express control characters, because \
is not expanded. Accessing the single quote itself from within a quoted string is possible, because you can concatenate strings with single and double quotes, like 'I'"'"'m'
which can be used to access a file called "I'm"
(double quote also possible here).
So you should avoid all control characters, because they are too difficult to enter in the shell. The rest still is funny, especially files starting with a dash, because most commands read those as options unless you have two dashes --
before, or you specify them with ./
, which also hides the starting -
.
If you want to be nice, don't use any of the characters the shell and typical commands use as syntactical elements, sometimes position dependent, so e.g. you can still use -
, but not as first character; same with .
, you can use it as first character only when you mean it ("hidden file"). When you are mean, your file names are VT100 escape sequences ;-), so that an ls garbles the output.
You can try this as well:
from time import perf_counter
t0 = perf_counter()
...
t1 = perf_counter()
time_taken = t1 - t0
DataFrame.reset_index
is what you're looking for. If you don't want it saved as a column, then do:
df = df.reset_index(drop=True)
If you don't want to reassign:
df.reset_index(drop=True, inplace=True)
Found another solution:
Command-line arguments are passed in the first String[]
parameter to main()
, e.g.
public static void main( String[] args ) {
}
In the example above, args
contains all the command-line arguments.
The short, sweet answer to the question posed is:
public static void main( String[] args ) {
if( args.length > 0 && args[0].equals( "a" ) ) {
// first argument is "a"
} else {
// oh noes!?
}
}
If you don't need multi-column, chosen is another good choice. MIT Licensed
As noted in a prior answer, although git merge-base
works,
$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
If myfeature
is the current branch, as is common, you can use --fork-point
:
$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.
For full commit info, consider:
$ git log -1 $(git merge-base --fork-point develop)
This will scroll to the end of the textbox when the text is changed, but still allows the user to scroll up
outbox.SelectionStart = outbox.Text.Length;
outbox.ScrollToEnd();
tested on Visual Studio Enterprise 2017
You're missing *
s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2
as an attempt to call a function named 0.207
...
For example:
> 1 + 2*(3)
[1] 7
> 1 + 2 (3)
Error: attempt to apply non-function
Your (unreproducible) expression should read:
censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) +
0.207* (log(DIAM93))^2 -
0.0281*(log(DIAM93))^3)
Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...
All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used.
If all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, "CHECKPOINT REACHED @ %s:%i\n", __FILE__, __LINE__);
) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints.
It's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing)
I've had a similar problem when building Clang from source (but not with sudo apt-get install
. This might depend on the version of Ubuntu which you're running).
It might be worth checking if clang++
can find the correct locations of your C++ libraries:
Compare the results of g++ -v <filename.cpp>
and clang++ -v <filename.cpp>
, under "#include < ... > search starts here:".
You are right. ArrayList.contains() tests equals(), not object identity:
returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e))
If you got a NullPointerException, verify that you initialized your list, either in a constructor or the declaration. For example:
private List<String> rssFeedURLs = new ArrayList<String>();
My smarty pants answer:
"Evasive answer to: "How to make block level element a hyperlink and validate in XHTML 1.1"
Just use HTML5 DOCTYPE DTD."
Didn't actually hold true for ie7
onclick="location.href='page.html';"
Works IE7-9, Chrome, Safari, Firefox,