What worked for me (on Windows, using git version 1.8.3.msysgit.0):
git submodule init
and git submodule update
After doing all that, everything is in the state I would expect. I imagine other users of the repository will have similar pain when they come to update though - it would be wise to explain these steps in your commit message!
This should get you access to applicationContext
from anywhere allowing you to get applicationContext
anywhere that can use it; Toast
, getString()
, sharedPreferences
, etc.
The Singleton:
package com.domain.packagename;
import android.content.Context;
/**
* Created by Versa on 10.09.15.
*/
public class ApplicationContextSingleton {
private static PrefsContextSingleton mInstance;
private Context context;
public static ApplicationContextSingleton getInstance() {
if (mInstance == null) mInstance = getSync();
return mInstance;
}
private static synchronized ApplicationContextSingleton getSync() {
if (mInstance == null) mInstance = new PrefsContextSingleton();
return mInstance;
}
public void initialize(Context context) {
this.context = context;
}
public Context getApplicationContext() {
return context;
}
}
Initialize the Singleton in your Application
subclass:
package com.domain.packagename;
import android.app.Application;
/**
* Created by Versa on 25.08.15.
*/
public class mApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ApplicationContextSingleton.getInstance().initialize(this);
}
}
If I´m not wrong, this gives you a hook to applicationContext everywhere, call it with ApplicationContextSingleton.getInstance.getApplicationContext();
You shouldn´t need to clear this at any point, as when application closes, this goes with it anyway.
Remember to update AndroidManifest.xml
to use this Application
subclass:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.domain.packagename"
>
<application
android:allowBackup="true"
android:name=".mApplication" <!-- This is the important line -->
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:icon="@drawable/app_icon"
>
Please let me know if you see anything wrong here, thank you. :)
For my case handling UIDeviceOrientationDidChangeNotification
was not good solution as it is called more frequent and UIDeviceOrientation
is not always equal to UIInterfaceOrientation
because of (FaceDown, FaceUp).
I handle it using UIApplicationDidChangeStatusBarOrientationNotification
:
//To add the notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeOrientation:)
//to remove the
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
...
- (void)didChangeOrientation:(NSNotification *)notification
{
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsLandscape(orientation)) {
NSLog(@"Landscape");
}
else {
NSLog(@"Portrait");
}
}
ldd
to list shared libraries for each executable.To find the answer for all executables in the "/bin" directory:
find /bin -type f -perm /a+x -exec ldd {} \; \
| grep so \
| sed -e '/^[^\t]/ d' \
| sed -e 's/\t//' \
| sed -e 's/.*=..//' \
| sed -e 's/ (0.*)//' \
| sort \
| uniq -c \
| sort -n
Change "/bin" above to "/" to search all directories.
Output (for just the /bin directory) will look something like this:
1 /lib64/libexpat.so.0
1 /lib64/libgcc_s.so.1
1 /lib64/libnsl.so.1
1 /lib64/libpcre.so.0
1 /lib64/libproc-3.2.7.so
1 /usr/lib64/libbeecrypt.so.6
1 /usr/lib64/libbz2.so.1
1 /usr/lib64/libelf.so.1
1 /usr/lib64/libpopt.so.0
1 /usr/lib64/librpm-4.4.so
1 /usr/lib64/librpmdb-4.4.so
1 /usr/lib64/librpmio-4.4.so
1 /usr/lib64/libsqlite3.so.0
1 /usr/lib64/libstdc++.so.6
1 /usr/lib64/libz.so.1
2 /lib64/libasound.so.2
2 /lib64/libblkid.so.1
2 /lib64/libdevmapper.so.1.02
2 /lib64/libpam_misc.so.0
2 /lib64/libpam.so.0
2 /lib64/libuuid.so.1
3 /lib64/libaudit.so.0
3 /lib64/libcrypt.so.1
3 /lib64/libdbus-1.so.3
4 /lib64/libresolv.so.2
4 /lib64/libtermcap.so.2
5 /lib64/libacl.so.1
5 /lib64/libattr.so.1
5 /lib64/libcap.so.1
6 /lib64/librt.so.1
7 /lib64/libm.so.6
9 /lib64/libpthread.so.0
13 /lib64/libselinux.so.1
13 /lib64/libsepol.so.1
22 /lib64/libdl.so.2
83 /lib64/ld-linux-x86-64.so.2
83 /lib64/libc.so.6
Edit - Removed "grep -P"
>>> max(enumerate([1,2,3,32,1,5,7,9]),key=lambda x: x[1])
>>> (3, 32)
Other Significant practical differences:
// Boolean
var str3 = true ;
alert(str3);
alert(str3 instanceof Boolean); // false: expect true
alert(typeof str3 == "boolean" ); // true
// Number
var str4 = 100 ;
alert(str4);
alert(str4 instanceof Number); // false: expect true
alert(typeof str4 == "number" ); // true
With PowerShell but without the need to create a script:
Invoke-WebRequest https://dist.nuget.org/win-x86-commandline/latest/nuget.exe -OutFile Nuget.exe
Based on your question, I believe the answer is how to trigger a blur, not just (or even) set the event:
$('#textArea').trigger('blur');
Using jQuery:
$('#Button').click(function(){
$(this).addClass("active");
});
This way, you don't have to pollute your HTML markup with onclick
handlers.
Achieve this by using the toolbar
like this :
<android.support.v7.widget.Toolbar
android:id="@+id/base_toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
I know that JPA entities must have primary key but I can't change database structure due to reasons beyond my control.
More precisely, a JPA entity must have some Id
defined. But a JPA Id
does not necessarily have to be mapped on the table primary key (and JPA can somehow deal with a table without a primary key or unique constraint).
Is it possible to create JPA (Hibernate) entities that will be work with database structure like this?
If you have a column or a set of columns in the table that makes a unique value, you can use this unique set of columns as your Id
in JPA.
If your table has no unique columns at all, you can use all of the columns as the Id
.
And if your table has some id but your entity doesn't, make it an Embeddable
.
-apple-system allows you to pick San Francisco in Safari. BlinkMacSystemFont is the corresponding alternative for Chrome.
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
Roboto or Helvetica Neue could be inserted as fallbacks even before sans-serif.
https://www.smashingmagazine.com/2015/11/using-system-ui-fonts-practical-guide/#details-of-approach-a (how or previously http://furbo.org/2015/07/09/i-left-my-system-fonts-in-san-francisco/ do a great job explaining the details.
If you are a windows 10 + TortoiseGit 2.7 user:
Pre- and Post-Build Events run as a batch script. You can do a conditional statement on $(ConfigurationName)
.
For instance
if $(ConfigurationName) == Debug xcopy something somewhere
inner shadow
.shadow {_x000D_
-webkit-box-shadow: inset 0 0 9px #000;_x000D_
-moz-box-shadow: inset 0 0 9px #000;_x000D_
box-shadow: inset 0 0 9px #000;_x000D_
}
_x000D_
<div class="shadow">wefwefwef</div>
_x000D_
The result produced by the Query is having no of rows that need proper handling this issue can be resolved if you provide the valid handler in the query like 1. limiting the query to return one single row 2. this can also be done by providing "select max(column)" that will return the single row
It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here: https://android.stackexchange.com/questions/32366/which-browser-does-support-proxies
Using NAT (the default) this is not possible. Bridged Networking should allow it. If bridged does not work for you (this may be the case when your network adminstration does not allow multiple IP addresses on one physical interface), you could try 'Host-only networking' instead.
For configuration of Host-only here is a quote from the vbox manual(which is pretty good). http://www.virtualbox.org/manual/ch06.html:
For host-only networking, like with internal networking, you may find the DHCP server useful that is built into VirtualBox. This can be enabled to then manage the IP addresses in the host-only network since otherwise you would need to configure all IP addresses statically.
In the VirtualBox graphical user interface, you can configure all these items in the global settings via "File" -> "Settings" -> "Network", which lists all host-only networks which are presently in use. Click on the network name and then on the "Edit" button to the right, and you can modify the adapter and DHCP settings.
The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();
You can also use something like
<c:if test="${ testObject.testPropert == "testValue" }">...</c:if>
from user import User
from dir import Dir
You can use DropDownButton
class in order to create drop down list :
...
...
String dropdownValue = 'One';
...
...
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: DropdownButton<String>(
value: dropdownValue,
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: <String>['One', 'Two', 'Free', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
);
...
...
please refer to this flutter web page
I am using those two collectors:
public static <T> Collector<T, ?, Optional<T>> zeroOrOne() {
return Collectors.reducing((a, b) -> {
throw new IllegalStateException("More than one value was returned");
});
}
public static <T> Collector<T, ?, T> onlyOne() {
return Collectors.collectingAndThen(zeroOrOne(), Optional::get);
}
<select class="custom-select">
<option>option1</option>
<option>option2</option>
<option>option3</option>
<option>option4</option>
</select>
<style>
.custom-select {
display: inline-block;
border: 2px solid #bbb;
padding: 4px 3px 3px 5px;
margin: 0;
font: inherit;
outline:none; /* remove focus ring from Webkit */
line-height: 1.2;
background: #f8f8f8;
-webkit-appearance:none; /* remove the strong OSX influence from Webkit */
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
}
/* for Webkit's CSS-only solution */
@media screen and (-webkit-min-device-pixel-ratio:0) {
.custom-select {
padding-right:30px;
}
}
/* Since we removed the default focus styles, we have to add our own */
.custom-select:focus {
-webkit-box-shadow: 0 0 3px 1px #c00;
-moz-box-shadow: 0 0 3px 1px #c00;
box-shadow: 0 0 3px 1px #c00;
}
/* Select arrow styling */
.custom-select:after {
content: "?";
position: absolute;
top: 0;
right: 0;
bottom: 0;
font-size: 60%;
line-height: 30px;
padding: 0 7px;
background: #bbb;
color: white;
pointer-events:none;
-webkit-border-radius: 0 6px 6px 0;
-moz-border-radius: 0 6px 6px 0;
border-radius: 0 6px 6px 0;
}
</style>
Even this question have already answered. I have a different approach to use RegExp and match to ignore case sensitive. Please see my link https://jsfiddle.net/marchdave/7v8bd7dq/27/
$("#btnGuess").click(guessWord);
function guessWord() {
var letter = $("#guessLetter").val();
var word = 'ABC';
var pattern = RegExp(letter, 'gi'); // pattern: /a/gi
var result = word.match(pattern);
alert('Ignore case sensitive:' + result);
}
For Angular 9/8
Source Link with Examples
export class AppComponent {
isDone = true;
}
1) *ngIf
<div *ngIf="isDone">
It's Done!
</div>
<!-- Negation operator-->
<div *ngIf="!isDone">
It's Not Done!
</div>
2) *ngIf and Else
<ng-container *ngIf="isDone; else elseNotDone">
It's Done!
</ng-container>
<ng-template #elseNotDone>
It's Not Done!
</ng-template>
3) *ngIf, Then and Else
<ng-container *ngIf="isDone; then iAmDone; else iAmNotDone">
</ng-container>
<ng-template #iAmDone>
It's Done!
</ng-template>
<ng-template #iAmNotDone>
It's Not Done!
</ng-template>
An alternative in Java 8:
String[] strings = list.stream().toArray(String[]::new);
Loop through the file.
f = open("masters.txt")
lines = f.readlines()
for line in lines:
print line
The class is .navbar-default. You need to create a class on your custom css .navbar-default.And follow the css code. Also if you don’t want box-shadow on your menu, you can put on the same class.
.navbar-default {
background-color:transparent !important;
border-color:transparent;
background-image:none;
box-shadow:none;
}
To change font navbar color, the class is to change – .navbar-default .navbar-nav>li>a see the code bellow:
.navbar-default .navbar-nav>li>a {
font-size:20px;
color:#fff;
}
ref : http://twitterbootstrap.org/bootstrap-navbar-background-color-transparent/
The map()
function is there to apply the same procedure to every item in an iterable data structure, like lists, generators, strings, and other stuff.
Let's look at an example:
map()
can iterate over every item in a list and apply a function to each item, than it will return (give you back) the new list.
Imagine you have a function that takes a number, adds 1 to that number and returns it:
def add_one(num):
new_num = num + 1
return new_num
You also have a list of numbers:
my_list = [1, 3, 6, 7, 8, 10]
if you want to increment every number in the list, you can do the following:
>>> map(add_one, my_list)
[2, 4, 7, 8, 9, 11]
Note: At minimum map()
needs two arguments. First a function name and second something like a list.
Let's see some other cool things map()
can do.
map()
can take multiple iterables (lists, strings, etc.) and pass an element from each iterable to a function as an argument.
We have three lists:
list_one = [1, 2, 3, 4, 5]
list_two = [11, 12, 13, 14, 15]
list_three = [21, 22, 23, 24, 25]
map()
can make you a new list that holds the addition of elements at a specific index.
Now remember map()
, needs a function. This time we'll use the builtin sum()
function. Running map()
gives the following result:
>>> map(sum, list_one, list_two, list_three)
[33, 36, 39, 42, 45]
REMEMBER:
In Python 2 map()
, will iterate (go through the elements of the lists) according to the longest list, and pass None
to the function for the shorter lists, so your function should look for None
and handle them, otherwise you will get errors. In Python 3 map()
will stop after finishing with the shortest list. Also, in Python 3, map()
returns an iterator, not a list.
if you generate new angular project using "ng new", you may skip a generating of spec.ts files. For this you should apply --skip-tests option.
ng new ng-app-name --skip-tests
I had the same problem even though I have 64-bit Windows 7 and i was loading a 64bit DLL b/c in Project properties | Build I had "Prefer 32-bit" checked. (Don't know why that's set by default). Once I unchecked that, everything ran fine
Officially not.
But here's a patch: http://rt.openssl.org/Ticket/Display.html?id=2651&user=guest&pass=guest
As of SciPy version 1.1, you can also use find_peaks. Below are two examples taken from the documentation itself.
Using the height
argument, one can select all maxima above a certain threshold (in this example, all non-negative maxima; this can be very useful if one has to deal with a noisy baseline; if you want to find minima, just multiply you input by -1
):
import matplotlib.pyplot as plt
from scipy.misc import electrocardiogram
from scipy.signal import find_peaks
import numpy as np
x = electrocardiogram()[2000:4000]
peaks, _ = find_peaks(x, height=0)
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.plot(np.zeros_like(x), "--", color="gray")
plt.show()
Another extremely helpful argument is distance
, which defines the minimum distance between two peaks:
peaks, _ = find_peaks(x, distance=150)
# difference between peaks is >= 150
print(np.diff(peaks))
# prints [186 180 177 171 177 169 167 164 158 162 172]
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.show()
I recommend Derek Bruening's bar graph generator Perl script. Available at http://www.burningcutlery.com/derek/bargraph/
With HttpClient 4.5 you can do this:
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(new PoolingHttpClientConnectionManager()).build();
Note that this one implements Closeable (for shutting down of the connection manager).
To get employee names starting with A or B listed in order...
select employee_name
from employees
where employee_name LIKE 'A%' OR employee_name LIKE 'B%'
order by employee_name
If you are using Microsoft SQL Server you could use
....
where employee_name LIKE '[A-B]%'
order by employee_name
This is not standard SQL though it just gets translated to the following which is.
WHERE employee_name >= 'A'
AND employee_name < 'C'
For all variants you would need to consider whether you want to include accented variants such as Á
and test whether the queries above do what you want with these on your RDBMS and collation options.
Slightly modified conventional binary conversion algorithm utilizing some more ES6 syntax and auto-features:
Convert binary sequence string to Array (assuming it wasnt already passed as array)
Reverse sequence to force 0 index to start at right-most binary digit as binary is calculated right-left
'reduce' Array function traverses array, performing summation of (2^index) per binary digit [only if binary digit === 1] (0 digit always yields 0)
NOTE: Binary conversion formula:
{where d=binary digit, i=array index, n=array length-1 (starting from right)}
n
? (d * 2^i)
i=0
let decimal = Array.from(binaryString).reverse().reduce((total, val, index)=>val==="1"?total + 2**index:total, 0);
console.log(`Converted BINARY sequence (${binaryString}) to DECIMAL (${decimal}).`);
1 console.log(new Date())
2. document.getElementById("date").valueAsDate = new Date();
1st log showing correct in console =Wed Oct 07 2020 00:40:54 GMT+0530 (India Standard Time)
2nd 06-10-2020 which is incorrect and today date is 07 and here showing 06.
There are at least two, easy_install and its successor pip.
This should do the trick:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
} // Author: silentnuke
Don't forget to add the internet permission in your manifest.
I wrote this extension:
extension UIView {
func lf_removeAllSubviews() {
for view in self.subviews {
view.removeFromSuperview()
}
}
}
So that you can use self.view.lf_removeAllSubviews in a UIViewController. I'll put this in the swift version of my https://github.com/superarts/LFramework later, when I have more experience in swift (1 day exp so far, and yes, for API I gave up underscore).
Expanding on @goodside's repsonse:
In some cases you may want to pad a string with zeros (e.g. fips codes or other numeric-like factors). In OSX/Linux:
> sprintf("%05s", "104")
[1] "00104"
But because sprintf()
calls the OS's C sprintf()
command, discussed here, in Windows 7 you get a different result:
> sprintf("%05s", "104")
[1] " 104"
So on Windows machines the work around is:
> sprintf("%05d", as.numeric("104"))
[1] "00104"
According to the create table statement, the default charset of the table is already utf8mb4. It seems that you have a wrong connection charset.
In Java, set the datasource url like this: jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf-8.
"?useUnicode=true&characterEncoding=utf-8" is necessary for using utf8mb4.
It works for my application.
Perform rotation using transform: rotate(xdeg)
and also apply overflow: hidden
to the parent component to avoid overlapping effect
.div-parent {
overflow: hidden
}
.div-child {
transform: rotate(270deg);
}
Here is a copy of code which works fine for me
import json
with open("test.json") as json_file:
json_data = json.load(json_file)
print(json_data)
with the data
{
"a": [1,3,"asdf",true],
"b": {
"Hello": "world"
}
}
you may want to wrap your json.load line with a try catch because invalid JSON will cause a stacktrace error message.
Historically, in early C times, when processors had 8 or 16 bit wordlength,int
was identical to todays short
(16 bit). In a certain sense, int is a more abstract data type thanchar
,short
,long
orlong long
, as you cannot be sure about the bitwidth.
When definingint n;
you could translate this with "give me the best compromise of bitwidth and speed on this machine for n". Maybe in the future you should expect compilers to translateint
to be 64 bit. So when you want your variable to have 32 bits and not more, better use an explicitlong
as data type.
[Edit: #include <stdint.h>
seems to be the proper way to ensure bitwidths using the int##_t types, though it's not yet part of the standard.]
It exists, but it's hard to search for. I think most people call it the "splat" operator.
It's in the documentation as "Unpacking argument lists".
You'd use it like this: foo(*values)
. There's also one for dictionaries:
d = {'a': 1, 'b': 2}
def foo(a, b):
pass
foo(**d)
If the switch value (switch(variable)) can't reach the default case, then default case is not at all needed. Even if we keep the default case, it is not at all executed. It is dead code.
In my case, I had to specify messageEncoding to Mtom in app.config of the client application like that:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="IntegrationServiceSoap" messageEncoding="Mtom"/>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:29495/IntegrationService.asmx"
binding="basicHttpBinding" bindingConfiguration="IntegrationServiceSoap"
contract="IntegrationService.IntegrationServiceSoap" name="IntegrationServiceSoap" />
</client>
</system.serviceModel>
</configuration>
Both my client and server use basicHttpBinding. I hope this helps the others :)
You can use DecoratedBox
.
@override
Widget build(BuildContext context) {
return DecoratedBox(
decoration: BoxDecoration(
image: DecorationImage(image: AssetImage("your_asset"), fit: BoxFit.cover),
),
child: Center(child: FlutterLogo(size: 300)),
);
}
Output:
Compass adjusts the way partials are imported. It allows importing components based solely on their name, without specifying the path.
Before you can do @import 'compass';
, you should:
Install Compass as a Ruby gem:
gem install compass
After that, you should use Compass's own command line tool to compile your SASS code:
cd path/to/your/project/
compass compile
Note that Compass reqiures a configuration file called config.rb
. You should create it for Compass to work.
The minimal config.rb
can be as simple as this:
css_dir = "css"
sass_dir = "sass"
And your SASS code should reside in sass/
.
Instead of creating a configuration file manually, you can create an empty Compass project with compass create <project-name>
and then copy your SASS code inside it.
Note that if you want to use Compass extensions, you will have to:
config.rb
;More info here: http://compass-style.org/help/
//using System;
//using System.Collections.Generic;
//using System.Linq;
private void Form1_Load(object sender, EventArgs e)
{
FocusOnOtherControl(Controls.Cast<Control>(), button1);
}
private void FocusOnOtherControl<T>(IEnumerable<T> controls, Control focusOnMe) where T : Control
{
foreach (var control in controls)
{
if (control.GetType().Equals(typeof(TextBox)))
{
control.TabStop = false;
control.LostFocus += new EventHandler((object sender, EventArgs e) =>
{
focusOnMe.Focus();
});
}
}
}
Just (array)
is missing in your code before the simplexml object:
...
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
$array = json_decode(json_encode((array)$xml), TRUE);
^^^^^^^
...
Try this [reverse order traversal]:
var childs = document.getElementById('parent').childNodes;
var len = childs.length;
if(len --) do {
console.log('node: ', childs[len]);
} while(len --);
OR [in order traversal]
var childs = document.getElementById('parent').childNodes;
var len = childs.length, i = -1;
if(++i < len) do {
console.log('node: ', childs[i]);
} while(++i < len);
Faced similar issue, and here is the solution
Example :
In elasticsearch.yml add the below properties
cluster.name: production
node.name: node1
network.bind_host: 10.0.1.22
network.host: 0.0.0.0
transport.tcp.port: 9300
Add the following in Java Elastic API for Bulk Push (just a code snippet). For IP Address add public IP address of elastic search machine
Client client;
BulkRequestBuilder requestBuilder;
try {
client = TransportClient.builder().settings(Settings.builder().put("cluster.name", "production").put("node.name","node1")).build().addTransportAddress(
new InetSocketTransportAddress(InetAddress.getByName(""), 9300));
requestBuilder = (client).prepareBulk();
}
catch (Exception e) {
}
Open the Firewall ports for 9200,9300
I'm afraid there is not such a function. You'll need a macro to acomplish this task.
You could do something like this in column E(remember to set custom format "dd/mm/yyyy hh:mm"):
=If(B1="";"";Now())
But it will change value everytime file opens.
You'll need save the value via macro.
The main problem is that the browser won't even send a request with a fragment part. The fragment part is resolved right there in the browser. So it's reachable through JavaScript.
Anyway, you could parse a URL into bits, including the fragment part, using parse_url(), but it's obviously not your case.
Also you can try zenity !
user=$(zenity --entry --text 'Please enter the username:') || exit 1
You tried to start Tomcat and got the following error:
Could not load the Tomcat server configuration at /Servers/Tomcat v7.0 Server at localhost-config. The configuration may be corrupt or incomplete
How to solve:
use this artisan command for create shortcut in public folder
php artisan storage:link
Than you will able to access posted img or file
Android 22 minimal runnable example
Source:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final RelativeLayout relativeLayout = new RelativeLayout(this);
final TextView tv1;
tv1 = new TextView(this);
tv1.setText("tv1");
// Setting an ID is mandatory.
tv1.setId(View.generateViewId());
relativeLayout.addView(tv1);
// tv2.
final TextView tv2;
tv2 = new TextView(this);
tv2.setText("tv2");
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.FILL_PARENT);
lp.addRule(RelativeLayout.BELOW, tv1.getId());
relativeLayout.addView(tv2, lp);
// tv3.
final TextView tv3;
tv3 = new TextView(this);
tv3.setText("tv3");
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
lp2.addRule(RelativeLayout.BELOW, tv2.getId());
relativeLayout.addView(tv3, lp2);
this.setContentView(relativeLayout);
}
}
Works with the default project generated by android create project ...
. GitHub repository with minimal build code.
I'm not about to repeat all the other answers, but there's one aspect that I haven't yet seen mentioned - it's the story of disappearing data. I don't know where to find it, but...
Basically it's about a web application that mysteriously every few night did loose all its data and nobody knew why. Inspecting the Logs later revealed that the site was found by google or another arbitrary spider, that happily GET (read: GOT) all the links it found on the site - including the "delete this entry" and "are you sure?" links.
Actually - part of this has been mentioned. This is the story behind "don't change data on GET but only on POST". Crawlers will happily follow GET, never POST. Even robots.txt doesn't help against misbehaving crawlers.
Excel export script works on IE7+, Firefox and Chrome.
function fnExcelReport()
{
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
tab = document.getElementById('headerTable'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text=tab_text+"</table>";
tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
}
else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
Just create a blank iframe:
<iframe id="txtArea1" style="display:none"></iframe>
Call this function on:
<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>
You can use CFArray instead of NSArray. Here is an article explaining how.
CFMutableArrayRef ar = CFArrayCreateMutable(NULL, 0, NULL);
for (NSUInteger i = 0; i < 1000; i++)
{
CFArrayAppendValue(ar, (void*)i);
}
CFRelease(ar); /* Releasing the array */
The same applies for the CoreFoundation version of the other containers too.
Here is another one which has the schema name beside the sequence name
select nspname,relname from pg_class c join pg_namespace n on c.relnamespace=n.oid where relkind = 'S' order by nspname
You don't need usebackq:
FOR /F delims^= %%A IN ('DIR/AD/B/S^|SORT/R') DO RD "%%A"
To expand upon nosklo's explanation:
a = {}
b = ['some', 'list']
a[b] = 'some' # this won't work
a[tuple(b)] = 'some' # this will, same as a['some', 'list']
I found this code to work if you're trying to refresh a bound datagridview with updated data from a dataset. Obviously, this was after I sent the update to the database.
'clear out the datasource for the Grid view
Me.DataGridView1.DataSource = Nothing
'refill the table adapter from the dataset table
Me.viewABCTableAdapter.Fill(Me.yourDataSet.viewABC)
'reset the datasource from the binding source
Me.DataGridView1.DataSource = Me.viewABCBindingSource
'should redraw with the new data
Me.DataGridView1.Refresh()
I am using Windows 10 Home edition.
I tried various combination,
netsh wlan show drivers
netsh wlan show hostednetwork
netsh wlan set hostednetwork mode=allow ssid=happy key=12345678
netsh wlan start hostednetwork
and also,
Control Panel\Network and Internet\Network Connections\Ethernet Properties\Sharing\Internet Connection Sharing\Allow other network users to connect through this computer Internet connection...
But still cannot activate WiFi hotspot.
While I have given up, somehow I click on Network icon on the taskbar, suddenly I see the buttons:
[ Wi-Fi ] [ Airplane Mode ] [ Mobile hotspot ]
Just like how our mobile phone can enable Mobile hotspot, Windows 10 has Mobile hotspot build-in. Just click on [ Mobile hotspot ] button and it works.
You can also use something like:
imageView.setImageDrawable(ActivityCompat.getDrawable(getContext(),
R.drawable.generatedID));
or using Picasso:
Picasso.with(getContext()).load(R.drawable.generatedId).into(imageView);
I am using git-bash in windows.The simplest way is to change the path address to have the forward slashes:
git clone C:/Dev/proposed
P.S: Start the git-bash on the destination folder.
Path used in clone ---> c:/Dev/proposed
Original path in windows ---> c:\Dev\proposed
When running a Python script from Powershell under Windows, this should work:
$pathToSourceRoot = "C:/Users/Steve/YourCode"
$env:PYTHONPATH = "$($pathToSourceRoot);$($pathToSourceRoot)/subdirs_if_required"
# Now run the actual script
python your_script.py
Since it sounds like your JAVA_HOME variable is not set correctly, follow the instructions for setting that.
Setting JAVA_HOME environment variable on MAC OSX 10.9
I would imagine once you set this, it will stop complaining.
You need the WHERE clause to replace ONLY the records that complies with the condition in the WHERE clause (as opposed to all records). You use % sign to indicate partial string: I.E.
LIKE ('...//domain1.com/images/%');
means all records that BEGIN with "...//domain1.com/images/"
and have anything AFTER (that's the %
for...)
Another example:
LIKE ('%http://domain1.com/images/%')
which means all records that contains "http://domain1.com/images/"
in any part of the string...
I see the many types of uses, but I find this layout more useful as a reference tool:
SELECT DATE_FORMAT('2004-01-20' ,'%Y-%m-01');
Yes you can use CASE
UPDATE table
SET columnB = CASE fieldA
WHEN columnA=1 THEN 'x'
WHEN columnA=2 THEN 'y'
ELSE 'z'
END
WHERE columnC = 1
Right click on the web page you want to use as the default page and choose "Set as Start Page" whenever you run the web application from Visual Studio, it will open the selected page.
First, don't use print
s for logging, there is astable, proven and well-thought out stdlib module to do that: logging
. You definitely should use it instead.
Second, don't be tempted to do a mess with unrelated tools when there is native and simple approach. Here it is:
log = logging.getLogger(__name__)
try:
call_code_that_fails()
except MyError:
log.exception('Any extra info you want to see in your logs')
That's it. You are done now.
What log.exception
is actually doing is just a call to log.error
(that is, log event with level ERROR
) and print traceback then.
Well, here is some considerations:
traceback
or call logger with exc_info=True
or get their hands dirty with sys.exc_info
?Well, just because! They all exist for different purposes. For example, traceback.print_exc
's output is a little bit different from tracebacks produced by the interpreter itself. If you use it, you will confuse anyone who reads your logs, they will be banging their heads against them.
Passing exc_info=True
to log calls is just inappropriate. But, it is useful when catching recoverable errors and you want to log them (using, e.g INFO
level) with tracebacks as well, because log.exception
produces logs of only one level - ERROR
.
And you definitely should avoid messing with sys.exc_info
as much as you can. It's just not a public interface, it's an internal one - you can use it if you definitely know what you are doing. It is not intended for just printing exceptions.
Update
Apparently, moment now provides its own type definitions (according to sivabudh at least from 2.14.1 upwards), thus you do not need typings
or @types
at all.
import * as moment from 'moment'
should load the type definitions provided with the npm package.
That said however, as said in moment/pull/3319#issuecomment-263752265 the moment team seems to have some issues in maintaining those definitions (they are still searching someone who maintains them).
You need to install moment
typings without the --ambient
flag.
Then include it using import * as moment from 'moment'
They are project files, that hold the module information and meta data.
Just add *.iml
to .gitignore
.
In Android Studio: Press CTRL + F9 to rebuild your project. The missing *.iml
files will be generated.
As the others said, you can use Firebug, and that will sort you out no worries on Firefox. Chrome & Safari both have a built-in developer console which has an almost identical interface to Firebug's console, so your code should be portable across those browsers. For other browsers, there's Firebug Lite.
If Firebug isn't an option for you, then try this simple script:
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
alert(out);
// or, if you wanted to avoid alerts...
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre)
}
I'd recommend against alerting each individual property: some objects have a LOT of properties and you'll be there all day clicking "OK", "OK", "OK", "O... dammit that was the property I was looking for".
You could also use alias_attribute
if you still want to be able to refer to them as tasks as well:
class User < ActiveRecord::Base
alias_attribute :jobs, :tasks
has_many :tasks
end
This works perfectly fine for me:
AdapterChart adapterChart = new AdapterChart(getContext(),messageList);
recyclerView.setAdapter(adapterChart);
recyclerView.scrollToPosition(recyclerView.getAdapter().getItemCount()-1);
For collapse, you can try CTRL + M + O and expand using CTRL + M + P. This works in VS2008.
For me the problem was the execution of clone via sudo.
If you clone to a directory where you have user permission ( /home/user/git) it will work fine.
(Explanation: Running a command as superuser will not work with the same public key as running a command as user. Therefore Github refused the connection.)
This solution requires a SSH key already to be set up: https://help.github.com/articles/generating-ssh-keys
Okay so little bit of digging and I found these gems from Bill Philips article on RecycleView
RecyclerView can do more than ListView, but the RecyclerView class itself has fewer responsibilities than ListView. Out of the box, RecyclerView does not:
- Position items on the screen
- Animate views
- Handle any touch events apart from scrolling
All of this stuff was baked in to ListView, but RecyclerView uses collaborator classes to do these jobs instead.
The ViewHolders you create are beefier, too. They subclass
RecyclerView.ViewHolder
, which has a bunch of methodsRecyclerView
uses.ViewHolders
know which position they are currently bound to, as well as which item ids (if you have those). In the process,ViewHolder
has been knighted. It used to be ListView’s job to hold on to the whole item view, andViewHolder
only held on to little pieces of it.Now, ViewHolder holds on to all of it in the
ViewHolder.itemView
field, which is assigned in ViewHolder’s constructor for you.
I found that the cleanest way to do this is to create a custom TwigExtension and override its getGlobals()
method. Rather than using $_SESSION
, it's also better to use Symfony's Session
class since it handles automatically starting/stopping the session.
I've got the following extension in /src/AppBundle/Twig/AppExtension.php:
<?php
namespace AppBundle\Twig;
use Symfony\Component\HttpFoundation\Session\Session;
class AppExtension extends \Twig_Extension {
public function getGlobals() {
$session = new Session();
return array(
'session' => $session->all(),
);
}
public function getName() {
return 'app_extension';
}
}
Then add this in /app/config/services.yml:
services:
app.twig_extension:
class: AppBundle\Twig\AppExtension
public: false
tags:
- { name: twig.extension }
Then the session can be accessed from any view using:
{{ session.my_variable }}
I took the following approach, which uses a simple modal progress indicator widget that wraps whatever you want to make modal during an async call.
The example in the package also addresses how to handle form validation while making async calls to validate the form (see flutter/issues/9688 for details of this problem). For example, without leaving the form, this async form validation method can be used to validate a new user name against existing names in a database while signing up.
https://pub.dartlang.org/packages/modal_progress_hud
Here is the demo of the example provided with the package (with source code):
Example could be adapted to other modal progress indicator behaviour (like different animations, additional text in modal, etc..).
As others have pointed out you are looking for std::numeric_limits<double>::quiet_NaN()
although I have to say I prefer the cppreference.com documents. Especially because this statement is a little vague:
Only meaningful if std::numeric_limits::has_quiet_NaN == true.
and it was simple to figure out what this means on this site, if you check their section on std::numeric_limits::has_quiet_NaN
it says:
This constant is meaningful for all floating-point types and is guaranteed to be true if std::numeric_limits::is_iec559 == true.
which as explained here if true
means your platform supports IEEE 754
standard. This previous thread explains this should be true for most situations.
I was trying to do this and found that, using the answers above, when using Functions.identity()
for the key to the Map, then I had issues with using a local method like this::localMethodName
to actually work because of typing issues.
Functions.identity()
actually does something to the typing in this case so the method would only work by returning Object
and accepting a param of Object
To solve this, I ended up ditching Functions.identity()
and using s->s
instead.
So my code, in my case to list all directories inside a directory, and for each one use the name of the directory as the key to the map and then call a method with the directory name and return a collection of items, looks like:
Map<String, Collection<ItemType>> items = Arrays.stream(itemFilesDir.listFiles(File::isDirectory))
.map(File::getName)
.collect(Collectors.toMap(s->s, this::retrieveBrandItems));
Only to supplement:
dir()
is the most powerful/fundamental tool. (Most recommended)Solutions other than dir()
merely provide their way of dealing the output of dir()
.
Listing 2nd level attributes or not, it is important to do the sifting by yourself, because sometimes you may want to sift out internal vars with leading underscores __
, but sometimes you may well need the __doc__
doc-string.
__dir__()
and dir()
returns identical content.__dict__
and dir()
are different. __dict__
returns incomplete content.IMPORTANT: __dir__()
can be sometimes overwritten with a function, value or type, by the author for whatever purpose.
Here is an example:
\\...\\torchfun.py in traverse(self, mod, search_attributes)
445 if prefix in traversed_mod_names:
446 continue
447 names = dir(m)
448 for name in names:
449 obj = getattr(m,name)
TypeError: descriptor __dir__
of 'object'
object needs an argument
The author of PyTorch modified the __dir__()
method to something that requires an argument. This modification makes dir()
fail.
If you want a reliable scheme to traverse all attributes of an object, do remember that every pythonic standard can be overridden and may not hold, and every convention may be unreliable.
When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead.
For more take a look at the MDN docs page for return
.
Hello was looking for the same, and it could be also
unlist(lapply(mtcars,class))
You need to ensure that C:\Python35\Sripts
is in your system path. Follow the top answer instructions here to do that:
You run the command in windows command prompt, not in the python interpreter that you have open.
Press:
Win + R
Type CMD
in the run window which has opened
Type pip install openpyxl
in windows command prompt.
Following on Omar's answer, I created a new class file in my REST API project called WebConfig.java
with this configuration:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
}
This allows any origin to access the API and applies it to all controllers in the Spring project.
I was getting this on an asp.net 2.0 iis7 Windows2008 site. Same code on iis6 worked fine. It was causing an issue for me because it was messing up the login process. User would login and get a 302 to default.asxp, which would get through page_load, but not as far as pre-render before iis7 would send a 302 back to login.aspx without the auth cookie. I started playing with app pool settings, and for some reason 'enable 32 bit applications' seems to have fixed it. No idea why, since this site isn't doing anything special that should require any 32 bit drivers. We have some sites that still use Access that require 32bit, but not our straight SQL sites like this one.
In my case the problem is actually with OpenFeint API project. I have added OpenFeint as library project:
.
It is also added into build path, ADT tools 16 gives error with this sceneario.
Right click on your project and click build path, configure the build path and then see the image and remove your project OpenFeint from here and all is done :)
I think these is the two most simple ways to run Redis on Windows
As described here on Option 3) Running Microsoft's native port of Redis:
- Download the redis-latest.zip native 64bit Windows port of redis
wget https://github.com/ServiceStack/redis-windows/raw/master/downloads/redis-latest.zip
Extract redis64-latest.zip in any folder, e.g. in c:\redis
Run the redis-server.exe using the local configuration
cd c:\redis
redis-server.exe redis.conf
- Run redis-cli.exe to connect to your redis instance
cd c:\redis
redis-cli.exe
You can use Redis on Windows with Vagrant, as described here:
Install Vagrant on Windows
Download the vagrant-redis.zip vagrant configuration
wget https://raw.github.com/ServiceStack/redis-windows/master/downloads/vagrant-redis.zip
Extract vagrant-redis.zip in any folder, e.g. in c:\vagrant-redis
Launch the Virtual Box VM with vagrant up:
cd c:\vagrant-redis
vagrant up
This will launch a new Ubuntu VM instance inside Virtual Box that will automatically install and start the latest stable version of redis.
I have seen most of the people saying explicit parent to child casting is not possible, that actually is not true. Let's take a revised start and try proving it by examples.
As we know in .net all castings have two broad categories.
Reference type has further three main situational cases in which any scenario can lie.
Case 1. Child to any direct or indirect parent
Employee e = new Employee();
Person p = (Person)e; //Allowed
Case 2. Parent variable holding parent object (Not allowed)
Person p = new Person(); // p is true Person object
Employee e = (Employee)p; //Runtime err : InvalidCastException <-------- Yours issue
Case 3. Parent variable holding child object (Always Successful)
Note: Because objects has polymorphic nature, it is possible for a variable of a parent class type to hold a child type.
Person p = new Employee(); // p actually is Employee
Employee e = (Employee)p; // Casting allowed
Conclusion : After reading above all, hope it will make sense now like how parent to child conversion is possible(Case 3).
Answer To The Question :
Your answer is in case 2.Where you can see such casting is not allowed by OOP and you are trying to violate one of OOP's basic rule.So always choose safe path.
Further more, to avoid such exceptional situations .net has recommended using is/as operators those will help you to take informed decisions and provide safe casting.
In Bjarne Stroustrup's C++ programming language book, you can read that he's proposing to overload the operator++
for your specific enum
. enum
are user-defined types and overloading operator exists in the language for these specific situations.
You'll be able to code the following:
#include <iostream>
enum class Colors{red, green, blue};
Colors& operator++(Colors &c, int)
{
switch(c)
{
case Colors::red:
return c=Colors::green;
case Colors::green:
return c=Colors::blue;
case Colors::blue:
return c=Colors::red; // managing overflow
default:
throw std::exception(); // or do anything else to manage the error...
}
}
int main()
{
Colors c = Colors::red;
// casting in int just for convenience of output.
std::cout << (int)c++ << std::endl;
std::cout << (int)c++ << std::endl;
std::cout << (int)c++ << std::endl;
std::cout << (int)c++ << std::endl;
std::cout << (int)c++ << std::endl;
return 0;
}
test code: http://cpp.sh/357gb
Mind that I'm using enum class
. Code works fine with enum
also. But I prefer enum class
since they are strong typed and can prevent us to make mistake at compile time.
CREATE UNIQUE INDEX foo ON table_name (field_name)
You have to remove duplicate values on that column before executes that sql. Any existing duplicate value on that column will lead you to mysql error 1062
You can't because Nullable<DateTime>
is a different type to DateTime
.
You need to write your own function to do it,
public bool TryParse(string text, out Nullable<DateTime> nDate)
{
DateTime date;
bool isParsed = DateTime.TryParse(text, out date);
if (isParsed)
nDate = new Nullable<DateTime>(date);
else
nDate = new Nullable<DateTime>();
return isParsed;
}
Hope this helps :)
EDIT: Removed the (obviously) improperly tested extension method, because (as Pointed out by some bad hoor) extension methods that attempt to change the "this" parameter will not work with Value Types.
P.S. The Bad Hoor in question is an old friend :)
For my case, I npm install
all modules on my local machine (Mac), and I did not include node_modules
in .gitignore
and uploaded to github. Then I cloned the project to my aws, as you know, it is running Linux, so I got the errors. What I did is just include node_modules
in .gitignore
, and use npm install
in my aws instance, then it works.
If you just have a plain url string (and therefore don't have a hash attribute) you can also use a regular expression:
var url = "www.example.com/task1/1.3.html#a_1"
var anchor = url.match(/#(.*)/)[1]
my code works for txt,doc,docx,pdf,ppt,pptx,jpg,png,zip extensions and I think its better to use the actual MIME types explicitly.
$file_name = "a.txt";
// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.')+1);
header('Content-disposition: attachment; filename='.$file_name);
if(strtolower($ext) == "txt")
{
header('Content-type: text/plain'); // works for txt only
}
else
{
header('Content-type: application/'.$ext); // works for all extensions except txt
}
readfile($decrypted_file_path);
Set it the same way you'd set the width of any other HTML element, with CSS:
audio { width: 200px; }
Note that audio
is an inline element by default in Firefox, so you might also want to set it to display: block
. Here's an example.
It's the comma which is providing that extra white space.
One way is to use the string %
method:
print 'Value is "%d"' % (value)
which is like printf
in C, allowing you to incorporate and format the items after %
by using format specifiers in the string itself. Another example, showing the use of multiple values:
print '%s is %3d.%d' % ('pi', 3, 14159)
For what it's worth, Python 3 greatly improves the situation by allowing you to specify the separator and terminator for a single print
call:
>>> print(1,2,3,4,5)
1 2 3 4 5
>>> print(1,2,3,4,5,end='<<\n')
1 2 3 4 5<<
>>> print(1,2,3,4,5,sep=':',end='<<\n')
1:2:3:4:5<<
From the AWS documentation:
Amazon SNS allows applications to send time-critical messages to multiple subscribers through a “push” mechanism, eliminating the need to periodically check or “poll” for updates.
Amazon SQS is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components—without requiring each component to be concurrently available.
If you are building UI without drag and drop (without using storyboard) and want to navigate default page or ViewController.swift to another page? Follow these steps 1) add a class (.swift) 2) Import UIKit 3) Declare class name like
class DemoNavigationClass :UIViewController{
override func viewDidLoad(){
let lbl_Hello = UILabel(frame: CGRect(x:self.view.frame.width/3, y:self.view.frame.height/2, 200, 30));
lbl_Hello.text = "You are on Next Page"
lbl_Hello.textColor = UIColor.white
self.view.addSubview(lbl_Hello)
}
}
after creating second page come back to first page (ViewController.swift) Here make a button in viewDidLoad method
let button = UIButton()
button.frame = (frame: CGRect(x: self.view.frame.width/3, y: self.view.frame.height/1.5, width: 200, height: 50))
button.backgroundColor = UIColor.red
button.setTitle("Go to Next ", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
now define buttonAction method outside of viewDidLoad() in same class
func buttonAction(sender: UIButton!)
{
let obj : DemoNavigationClass = DemoNavigationClass();
self.navigationController?.pushViewController(obj, animated: true)
}
Keep one thing that i forget in main.storyboard there is a scene with a arrow, select that arrow and press delete button
now drag and drop a navigationcontroller and delete tableview which comes with navaigation controller. select navigationcontroller press control on keyboard and drag it in to another scene on storyboard that is ViewController. This mean that your viewcontroller become root viewcontroller hope this help you Thanks in main.storyboard , drag and drop navigationcontroller,
I'd use
files=(*)
And then if you need data about the file, such as size, use the stat
command on each file.
We could simply write the following method
public static void ClearLine()
{
Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, Console.CursorTop - 1);
}
and then call it when needed like this
Console.WriteLine("Test");
ClearLine();
It works fine for me.
in my case i fix the problem in chrome with this
<form id="form1" runat="server" autocomplete="off">
where i need to clear the content of a previus form data when the users click button back for security reasons
To add onto bobince's answer... If whatever tool/library you using uses Xpath 2.0, you can also do this:
//*[count(index-of(tokenize(@class, '\s+' ), $classname)) = 1]
count() is apparently needed because index-of() returns a sequence of each index it has a match at in the string.
&& ; || are logical operators.... short circuit
& ; | are boolean logical operators.... Non-short circuit
Moving to differences in execution on expressions. Bitwise operators evaluate both sides irrespective of the result of left hand side. But in the case of evaluating expressions with logical operators, the evaluation of the right hand expression is dependent on the left hand condition.
For Example:
int i = 25;
int j = 25;
if(i++ < 0 && j++ > 0)
System.out.println("OK");
System.out.printf("i = %d ; j = %d",i,j);
This will print i=26 ; j=25, As the first condition is false the right hand condition is bypassed as the result is false anyways irrespective of the right hand side condition.(short circuit)
int i = 25;
int j = 25;
if(i++ < 0 & j++ > 0)
System.out.println("OK");
System.out.printf("i = %d ; j = %d",i,j);
But, this will print i=26; j=26,
To clarify the terminology right: arrays are fixed length structures (and the length of an existing cannot be altered) the expression add at the end is meaningless (by itself).
What you can do is create a new array one element larger and fill in the new element in the last slot:
public static int[] append(int[] array, int value) {
int[] result = Arrays.copyOf(array, array.length + 1);
result[result.length - 1] = value;
return result;
}
This quickly gets inefficient, as each time append is called a new array is created and the old array contents is copied over.
One way to drastically reduce the overhead is to create a larger array and keep track of up to which index it is actually filled. Adding an element becomes as simple a filling the next index and incrementing the index. If the array fills up completely, a new array is created with more free space.
And guess what ArrayList does: exactly that. So when a dynamically sized array is needed, ArrayList is a good choice. Don't reinvent the wheel.
Hope this helps.
According to this blog post you can load controller within another controller in codeigniter.
http://www.techsirius.com/2013/01/load-controller-within-another.html
First of all you need to extend CI_Loader
<?php
class MY_Loader extends CI_Loader {
public function __construct() {
parent::__construct();
}
public function controller($file_name) {
$CI = & get_instance();
$file_path = APPPATH.'controllers/' . $file_name . '.php';
$object_name = $file_name;
$class_name = ucfirst($file_name);
if (file_exists($file_path)) {
require $file_path;
$CI->$object_name = new $class_name();
}
else {
show_error('Unable to load the requested controller class: ' . $class_name);
}
}
}
then load controller within another controller.
Using a in b
is simply translates to b.__contains__(a)
, which should return if b includes a or not.
But, your example looks a little weird, it takes an input from user and assigns its integer value to how_much
variable if the input contains "0"
or "1"
.
declare @starttime datetime = '2012-03-07 22:58:00'
SELECT BookingId, StartTime
FROM Booking
WHERE ABS( DATEDIFF( minute, StartTime, @starttime ) ) <= 60
I think init_js should use declare instead of local!
function scan3() {
declare -n outvar=$1 # -n makes it a nameref.
local nl=$'\x0a'
outvar="output${nl}${nl}" # two total. quotes preserve newlines
}
If you've tried modifying etc/hosts and adding java.rmi.server.hostname property as well but still registry is being bind to 127.0.0.1
the issue for me was resolved after explicitly setting System property through code though the same property wasn't picked from jvm args
For delete file from folder you can use unlink and if you want to delete data from database you can use delete() in laravel
Delete file from folder
unlink($image_path);
For delete record from database
$flight = Flight::find(1);
$flight->delete();
I don't see an obvious problem with the above.
It's possible your ldap.conf
is being overridden, but the command-line options will take precedence, ldapsearch
will ignore BINDDN
in the main ldap.conf
, so the only parameter that could be wrong is the URI.
(The order is ETCDIR/ldap.conf
then ~/ldaprc
or ~/.ldaprc
and then ldaprc
in the current directory, though there environment variables which can influence this too, see man ldapconf
.)
Try an explicit URI:
ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
or prevent defaults with:
LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd
binary for these):
make sure your slapd.conf
is being used and is correct (as root)
slapd -T test -f slapd.conf -d 65535
You may have a left-over or default slapd.d
configuration directory which takes preference over your slapd.conf
(unless you specify your config explicitly with -f
, slapd.conf
is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.
stop OpenLDAP, then manually start slapd
in a separate terminal/console with debug enabled (as root, ^C to quit)
slapd -h ldap://localhost -d 481
then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd
without the -u
/-g
options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap
)
if debug is enabled, then try also
ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
Try this :
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
This checks if jQuery is available or not, if not it will add one dynamically from path specified.
Ref: Simulate an "include_once" for jQuery
OR
include_once equivalent for js. Ref: https://raw.github.com/kvz/phpjs/master/functions/language/include_once.js
function include_once (filename) {
// http://kevin.vanzonneveld.net
// + original by: Legaev Andrey
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Michael White (http://getsprink.com)
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// - depends on: include
// % note 1: Uses global: php_js to keep track of included files (though private static variable in namespaced version)
// * example 1: include_once('http://www.phpjs.org/js/phpjs/_supporters/pj_test_supportfile_2.js');
// * returns 1: true
var cur_file = {};
cur_file[this.window.location.href] = 1;
// BEGIN STATIC
try { // We can't try to access on window, since it might not exist in some environments, and if we use "this.window"
// we risk adding another copy if different window objects are associated with the namespaced object
php_js_shared; // Will be private static variable in namespaced version or global in non-namespaced
// version since we wish to share this across all instances
} catch (e) {
php_js_shared = {};
}
// END STATIC
if (!php_js_shared.includes) {
php_js_shared.includes = cur_file;
}
if (!php_js_shared.includes[filename]) {
if (this.include(filename)) {
return true;
}
} else {
return true;
}
return false;
}
Like this post suggests, this can be done in the following way:
int Foo(CancellationToken token)
{
Thread t = Thread.CurrentThread;
using (token.Register(t.Abort))
{
// compute-bound work here
}
}
Although it works, it's not recommended to use such approach. If you can control the code that executes in task, you'd better go with proper handling of cancellation.
byte[] data = dbEntity.getBlobData();
response.getOutputStream().write();
I think this is better since you already have an existing OutputStream in the response object. no need to create a new OutputStream.
The hash solution is nice but not really human readable when you want to know what version of file is sitting in your local web folder. The solution is to date/time
stamp your version so you can easily compare it against your server file.
For example, if your .js or .css
file is dated 2011-02-08 15:55:30
(last modification) then the version should equal to .js?v=20110208155530
Should be easy to read properties of any file in any language. In ASP.Net it's really easy...
".js?v=" + File.GetLastWriteTime(HttpContext.Current.Request.PhysicalApplicationPath + filename).ToString("yyMMddHHHmmss");
Of coz get it nicely refactored into properties/functions first and off you go. No more excuses.
Good luck, Art.
I would recommend using the visual designer built into VS2008, as updating the dbml also updates the code that is generated for you. Modifying the dbml outside of the visual designer would result in the underlying code being out of sync.
try like this
css
*{
box-sizing: border-box;
-webkit-box-sizing: border-box;
-msbox-sizing: border-box;
}
body{
overflow-x: hidden;
}
img{
max-width:100%;
}
Use a for
loop instead of .forEach()
var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false
for(var call of myObj) {
console.log(call)
var a = call['a'], b = call['b']
if(a == null || b == null) {
result = false
break
}
}
Drawable myDrawable = getResources().getDrawable(R.drawable.logo);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
Since API 22 getResources().getDrawable()
is deprecated, so we can use following solution.
Drawable vectorDrawable = VectorDrawableCompat.create(getResources(), R.drawable.logo, getContext().getTheme());
Bitmap myLogo = ((BitmapDrawable) vectorDrawable).getBitmap();
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSS3 Button</title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="container">
<a href="#" class="btn">Push</a>
</div>
</body>
</html>
CSS styling
a.btn {
display: block; width: 250px; height: 60px; padding: 40px 0 0 0; margin: 0 auto;
background: #398525; /* old browsers */
background: -moz-linear-gradient(top, #8DD297 0%, #398525 100%); /* firefox */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#8DD297), color-stop(100%,#398525)); /* webkit */
box-shadow: inset 0px 0px 6px #fff;
-webkit-box-shadow: inset 0px 0px 6px #fff;
border: 1px solid #5ea617;
border-radius: 10px;
}
The general practice is to have the central repository to which you push as a bare repo.
If you have SVN background, you can relate an SVN repo to a Git bare repo. It doesn't have the files in the repo in the original form. Whereas your local repo will have the files that form your "code" in addition.
You need to add a remote to the bare repo from your local repo and push your "code" to it.
It will be something like:
git remote add central <url> # url will be ssh based for you
git push --all central
MonoDevelop, the IDE associated with Mono Project should be enough for C# development on Linux. Now I don't know any good profilers and other tools for C# development on Linux. But then again mind you, that C# is a language more native to windows. You are better developing C# apps for windows than for linux.
EDIT: When you download MonoDevelop from the Ubuntu Software Center, it will contain pretty much everything you need to get started right away (Compiler, Runtime Environment, IDE). If you would like more information, see the following links:
Use the sleep
command.
Example:
sleep .5 # Waits 0.5 second.
sleep 5 # Waits 5 seconds.
sleep 5s # Waits 5 seconds.
sleep 5m # Waits 5 minutes.
sleep 5h # Waits 5 hours.
sleep 5d # Waits 5 days.
One can also employ decimals when specifying a time unit; e.g. sleep 1.5s
Try this:
Write-Host ($obj | Format-Table | Out-String)
or
Write-Host ($obj | Format-List | Out-String)
You can try this:
OffsetDateTime currentDateTime = OffsetDateTime.now();
for (OffsetDateTime date = currentDateTime; date.isAfter(currentDateTime.minusYears(YEARS)); date = date.minusWeeks(1))
{
...
}
Try this updated code :
$(bla).click(function(){
if (something) {
console.log($target.prev("input")) // gives out the right object
$target.toggleClass("open").prev("input").attr("disabled", "true");
}else{
$target.toggleClass("open").prev("input").removeAttr("disabled"); //this works
}
})
Like samplebias answer, again if Javascript is an acceptable answer, I made a jQuery plugin specifically for this purpose: https://github.com/marcogrcr/jquery-tableoverflow
To use the plugin just type
$('selector').tableoverflow();
Full example: http://jsfiddle.net/Cw7TD/3/embedded/result/
Edits:
You can use strtotime() for time calculation. Here is an example:
$checkTime = strtotime('09:00:59');
echo 'Check Time : '.date('H:i:s', $checkTime);
echo '<hr>';
$loginTime = strtotime('09:01:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!'; echo '<br>';
echo 'Time diff in sec: '.abs($diff);
echo '<hr>';
$loginTime = strtotime('09:00:59');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
echo '<hr>';
$loginTime = strtotime('09:00:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
Check the already-asked question - how to get time difference in minutes:
Subtract the past-most one from the future-most one and divide by 60.
Times are done in unix format so they're just a big number showing the number of seconds from January 1 1970 00:00:00 GMT
Apple users can download your .apk file, however they cannot run it. It is a different file format than iPhone apps (.ipa)
You could just use:
<div id="GridDiv">
// gridview inside...
</div>
<a href="#GridDiv">Scroll to top</a>
I know this post is a little dated, and CakePHP versions have flourished since. In the current (2.1.x) version of CakePHP and even in 1.3.x if I am not mistaken, one can get the current controller/view url like this:
$this->params['url'];
While this method does NOT return the parameters, it is handy if you want to append parameters to a link when building new URL's. For example, we have the current URL:
projects/edit/6
And we want to append a custom parameter action called c_action with a value of remove_image, one could make use of $this->params['url];
and merge it with an array of custom parameter key => value pairs:
echo $this->Html->link('remove image', array_merge($this->params['url'], array('c_action' => 'remove_image'));
Using the above method we are able to append our custom parameters to the link and not cause a long chain on parameters to build up on the URL, because $this->params['url] only ever returns the controll action URL.
In the above example we'd need to manually add the ID of 6 back into the URL, so perahaps the final link build would be like this:
echo $this->Html->link('remove image', array_merge($this->params['url'], array($id,'c_action' => 'remove_image'));
Where $is is a the ID of the project and you would have assigned it to the variable $id at controller level. The new URL will then be:
projects/edit/6/c_action:remove_image
Sorry if this is in the slightest unrelated, but I ran across this question when searching for a method to achieve the above and thought others may benefit from it.
Call the TreeView.OnAfterSelect()
protected method after you programatically select the node.
dump and restore with --no-owner --no-privileges
flags
e.g.
dump - pg_dump --no-owner --no-privileges --format=c --dbname=postgres://userpass:username@postgres:5432/schemaname > /tmp/full.dump
restore - pg_restore --no-owner --no-privileges --format=c --dbname=postgres://userpass:username@postgres:5432/schemaname /tmp/full.dump
If you have multiple inputs as text in a form or a table that you need to iterate through, I did this:
var $list = $("#tableOrForm :input[type='text']");
$list.each(function(){
// Go on with your code.
});
What I did was I checked each input to see if the type is set to "text", then it'll grab that element and store it in the jQuery list. Then, it would iterate through that list. You can set a temp variable for the current iteration like this:
var $currentItem = $(this);
This will set the current item to the current iteration of your for each loop. Then you can do whatever you want with the temp variable.
Hope this helps anyone!
To input AN ENTIRE LINE containing lot of spaces you can use getline(cin,string_variable);
eg:
string input;
getline(cin, input);
This format captures all the spaces in the sentence untill return
is pressed
For example, you might want to make sure that when you free the memory of something you set the pointer to null afterwards.
void safeFree(void** memory) {
if (*memory) {
free(*memory);
*memory = NULL;
}
}
When you call this function you'd call it with the address of a pointer
void* myMemory = someCrazyFunctionThatAllocatesMemory();
safeFree(&myMemory);
Now myMemory
is set to NULL and any attempt to reuse it will be very obviously wrong.
you can try the following code
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("PayScale", typeof(string));
dt.Columns.Add("IncrementAmt", typeof(string));
dt.Columns.Add("Period", typeof(string));
}
DataRow NewRow = dt.NewRow();
NewRow[0] = TextBox1.Text;
NewRow[1] = TextBox2.Text;
dt.Rows.Add(NewRow);
GridView1.DataSource = dt;
GridViewl.DataBind();
}
here payscale,incrementamt and period are database field name.
The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.
Conclusion
Let's me explain more detail:
Question: How many Transaction we have? Answer: Only one
Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.
Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction
Go to the catch outside
Spring will set the rollBackOnly to true -> it determine we must
rollback the caller (processNextRegistrationMessage) also.
The persist() will rollback itself first.
Question: Why we change PROPAGATION to REQUIRES_NEW, it works?
Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.
Thanks
I've faced the exactly same problem but I've fixed it with another approache.
Using Ubuntu 18.04, first disable systemd-resolved
service.
sudo systemctl disable systemd-resolved.service
Stop the service
sudo systemctl stop systemd-resolved.service
Then, remove the link to /run/systemd/resolve/stub-resolv.conf
in /etc/resolv.conf
sudo rm /etc/resolv.conf
Add a manually created resolv.conf
in /etc/
sudo vim /etc/resolv.conf
Add your prefered DNS server there
nameserver 208.67.222.222
I've tested this with success.
Check also that you don't have this turned on: Configuration Properties -> C/C++ -> Preprocessor -> Preprocess to a File.
The LDF file holds the database transaction log. See, for example, http://www.databasedesign-resource.com/sql-server-transaction-log.html for a full explanation. There are ways to shrink the transaction file; for example, see http://support.microsoft.com/kb/873235.
In Eclipse Select Help -> Marketplace
Enter "Maven" in Find box and click on Go button
Click on "Install" button for Maven Integration for Eclipse (Juno and newer)
With this, maven should get install without any problem.
I'm using the following code in xml
android:adjustViewBounds="true"
android:scaleType="centerInside"
sp_msforeachdb 'use ?;select name,''?'' from sys.procedures where object_definition(object_id) like ''%text%'''
This will search in all stored procedure of all databases. This will also work for long procedures.
You may use:
$("#foo").unbind('click');
to make sure all click events are unbinded, then attach your event
One way to do it must be if (typeof myObj.prop1 != "undefined") {...}
import telnetlib
user = "admin"
password = "\r"
def connect(A):
tnA = telnetlib.Telnet(A)
tnA.read_until('username: ', 3)
tnA.write(user + '\n')
tnA.read_until('password: ', 3)
tnA.write(password + '\n')
return tnA
def quit_telnet(tn)
tn.write("bye\n")
tn.write("quit\n")
This works for me
Move your .htaccess file to root folder (locate before application folder in my case)
RewriteEngine on
RewriteBase /yourProjectFolder
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
Mine config.php looks like this (application/config/config.php)
$config['base_url'] = "";
$config['index_page'] = "index.php";
$config['uri_protocol'] = "AUTO";
Let me know if its working for you guys too ! Cheers !
you may use opacity:0.5;//what ever you wish between 0 and 1
for this.
working Fiddle
I've created a module called cors-bypass
, that allows you to do this without the need for a server. It uses postMessage
to send cross-domain events, which is used to provide mock HTTP APIs (fetch
, WebSocket
, XMLHTTPRequest
etc.).
It fundamentally does the same as the answer by Endless, but requires no code changes to use it.
Example usage:
import { Client, WebSocket } from 'cors-bypass'
const client = new Client()
await client.openServerInNewTab({
serverUrl: 'http://random-domain.com/server.html',
adapterUrl: 'https://your-site.com/adapter.html'
})
const ws = new WebSocket('ws://echo.websocket.org')
ws.onopen = () => ws.send('hello')
ws.onmessage = ({ data }) => console.log('received', data)
A simple answer would be : No, it doesn't
Explanation : According to the definition of unique constraints (SQL-92)
A unique constraint is satisfied if and only if no two rows in a table have the same non-null values in the unique columns
This statement can have two interpretations as :
NULL
and NULL
is not allowedNULL
and NULL
is fine, but StackOverflow
and StackOverflow
is not allowedSince MySQL follows second interpretation, multiple NULL
values are allowed in UNIQUE
constraint column. Second, if you would try to understand the concept of NULL
in SQL, you will find that two NULL
values can be compared at all since NULL
in SQL refers to unavailable or unassigned value (you can't compare nothing with nothing). Now, if you are not allowing multiple NULL
values in UNIQUE
constraint column, you are contracting the meaning of NULL
in SQL. I would summarise my answer by saying :
MySQL supports UNIQUE constraint but not on the cost of ignoring NULL values
First let us understand Spring:
Spring is a lightweight and flexible framework.
Bean: is an object, which is created, managed and destroyed in Spring Container. We can inject an object into the Spring Container through the metadata(either xml or annotation), which is called inversion of control.
Analogy: Let us assume farmer is having a farmland cultivating by seeds(or beans). Here, Farmer is Spring Framework, Farmland land is Spring Container, Beans are Spring Beans, Cultivating is Spring Processors.
Like bean life-cycle, spring beans too having it's own life-cycle.
Following is sequence of a bean lifecycle in Spring:
Instantiate: First the spring container finds the bean’s definition from the XML file and instantiates the bean.
Populate properties: Using the dependency injection, spring populates all of the properties as specified in the bean definition.
Set Bean Name: If the bean implements BeanNameAware
interface, spring passes the bean’s id to setBeanName()
method.
Set Bean factory: If Bean implements BeanFactoryAware
interface, spring passes the beanfactory to setBeanFactory()
method.
Pre-Initialization: Also called post process of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization()
method.
Initialize beans: If the bean implements IntializingBean
,its afterPropertySet()
method is called. If the bean has init method declaration, the specified initialization method is called.
Post-Initialization: – If there are any BeanPostProcessors
associated with the bean, their postProcessAfterInitialization()
methods will be called.
Ready to use: Now the bean is ready to use by the application
Destroy: If the bean implements DisposableBean
, it will call the destroy()
method
My first answer was an extremely simplified introduction to move semantics, and many details were left out on purpose to keep it simple. However, there is a lot more to move semantics, and I thought it was time for a second answer to fill the gaps. The first answer is already quite old, and it did not feel right to simply replace it with a completely different text. I think it still serves well as a first introduction. But if you want to dig deeper, read on :)
Stephan T. Lavavej took the time to provide valuable feedback. Thank you very much, Stephan!
Move semantics allows an object, under certain conditions, to take ownership of some other object's external resources. This is important in two ways:
Turning expensive copies into cheap moves. See my first answer for an example. Note that if an object does not manage at least one external resource (either directly, or indirectly through its member objects), move semantics will not offer any advantages over copy semantics. In that case, copying an object and moving an object means the exact same thing:
class cannot_benefit_from_move_semantics
{
int a; // moving an int means copying an int
float b; // moving a float means copying a float
double c; // moving a double means copying a double
char d[64]; // moving a char array means copying a char array
// ...
};
Implementing safe "move-only" types; that is, types for which copying does not make sense, but moving does. Examples include locks, file handles, and smart pointers with unique ownership semantics. Note: This answer discusses std::auto_ptr
, a deprecated C++98 standard library template, which was replaced by std::unique_ptr
in C++11. Intermediate C++ programmers are probably at least somewhat familiar with std::auto_ptr
, and because of the "move semantics" it displays, it seems like a good starting point for discussing move semantics in C++11. YMMV.
The C++98 standard library offers a smart pointer with unique ownership semantics called std::auto_ptr<T>
. In case you are unfamiliar with auto_ptr
, its purpose is to guarantee that a dynamically allocated object is always released, even in the face of exceptions:
{
std::auto_ptr<Shape> a(new Triangle);
// ...
// arbitrary code, could throw exceptions
// ...
} // <--- when a goes out of scope, the triangle is deleted automatically
The unusual thing about auto_ptr
is its "copying" behavior:
auto_ptr<Shape> a(new Triangle);
+---------------+
| triangle data |
+---------------+
^
|
|
|
+-----|---+
| +-|-+ |
a | p | | | |
| +---+ |
+---------+
auto_ptr<Shape> b(a);
+---------------+
| triangle data |
+---------------+
^
|
+----------------------+
|
+---------+ +-----|---+
| +---+ | | +-|-+ |
a | p | | | b | p | | | |
| +---+ | | +---+ |
+---------+ +---------+
Note how the initialization of b
with a
does not copy the triangle, but instead transfers the ownership of the triangle from a
to b
. We also say "a
is moved into b
" or "the triangle is moved from a
to b
". This may sound confusing because the triangle itself always stays at the same place in memory.
To move an object means to transfer ownership of some resource it manages to another object.
The copy constructor of auto_ptr
probably looks something like this (somewhat simplified):
auto_ptr(auto_ptr& source) // note the missing const
{
p = source.p;
source.p = 0; // now the source no longer owns the object
}
The dangerous thing about auto_ptr
is that what syntactically looks like a copy is actually a move. Trying to call a member function on a moved-from auto_ptr
will invoke undefined behavior, so you have to be very careful not to use an auto_ptr
after it has been moved from:
auto_ptr<Shape> a(new Triangle); // create triangle
auto_ptr<Shape> b(a); // move a into b
double area = a->area(); // undefined behavior
But auto_ptr
is not always dangerous. Factory functions are a perfectly fine use case for auto_ptr
:
auto_ptr<Shape> make_triangle()
{
return auto_ptr<Shape>(new Triangle);
}
auto_ptr<Shape> c(make_triangle()); // move temporary into c
double area = make_triangle()->area(); // perfectly safe
Note how both examples follow the same syntactic pattern:
auto_ptr<Shape> variable(expression);
double area = expression->area();
And yet, one of them invokes undefined behavior, whereas the other one does not. So what is the difference between the expressions a
and make_triangle()
? Aren't they both of the same type? Indeed they are, but they have different value categories.
Obviously, there must be some profound difference between the expression a
which denotes an auto_ptr
variable, and the expression make_triangle()
which denotes the call of a function that returns an auto_ptr
by value, thus creating a fresh temporary auto_ptr
object every time it is called. a
is an example of an lvalue, whereas make_triangle()
is an example of an rvalue.
Moving from lvalues such as a
is dangerous, because we could later try to call a member function via a
, invoking undefined behavior. On the other hand, moving from rvalues such as make_triangle()
is perfectly safe, because after the copy constructor has done its job, we cannot use the temporary again. There is no expression that denotes said temporary; if we simply write make_triangle()
again, we get a different temporary. In fact, the moved-from temporary is already gone on the next line:
auto_ptr<Shape> c(make_triangle());
^ the moved-from temporary dies right here
Note that the letters l
and r
have a historic origin in the left-hand side and right-hand side of an assignment. This is no longer true in C++, because there are lvalues that cannot appear on the left-hand side of an assignment (like arrays or user-defined types without an assignment operator), and there are rvalues which can (all rvalues of class types with an assignment operator).
An rvalue of class type is an expression whose evaluation creates a temporary object. Under normal circumstances, no other expression inside the same scope denotes the same temporary object.
We now understand that moving from lvalues is potentially dangerous, but moving from rvalues is harmless. If C++ had language support to distinguish lvalue arguments from rvalue arguments, we could either completely forbid moving from lvalues, or at least make moving from lvalues explicit at call site, so that we no longer move by accident.
C++11's answer to this problem is rvalue references. An rvalue reference is a new kind of reference that only binds to rvalues, and the syntax is X&&
. The good old reference X&
is now known as an lvalue reference. (Note that X&&
is not a reference to a reference; there is no such thing in C++.)
If we throw const
into the mix, we already have four different kinds of references. What kinds of expressions of type X
can they bind to?
lvalue const lvalue rvalue const rvalue
---------------------------------------------------------
X& yes
const X& yes yes yes yes
X&& yes
const X&& yes yes
In practice, you can forget about const X&&
. Being restricted to read from rvalues is not very useful.
An rvalue reference
X&&
is a new kind of reference that only binds to rvalues.
Rvalue references went through several versions. Since version 2.1, an rvalue reference X&&
also binds to all value categories of a different type Y
, provided there is an implicit conversion from Y
to X
. In that case, a temporary of type X
is created, and the rvalue reference is bound to that temporary:
void some_function(std::string&& r);
some_function("hello world");
In the above example, "hello world"
is an lvalue of type const char[12]
. Since there is an implicit conversion from const char[12]
through const char*
to std::string
, a temporary of type std::string
is created, and r
is bound to that temporary. This is one of the cases where the distinction between rvalues (expressions) and temporaries (objects) is a bit blurry.
A useful example of a function with an X&&
parameter is the move constructor X::X(X&& source)
. Its purpose is to transfer ownership of the managed resource from the source into the current object.
In C++11, std::auto_ptr<T>
has been replaced by std::unique_ptr<T>
which takes advantage of rvalue references. I will develop and discuss a simplified version of unique_ptr
. First, we encapsulate a raw pointer and overload the operators ->
and *
, so our class feels like a pointer:
template<typename T>
class unique_ptr
{
T* ptr;
public:
T* operator->() const
{
return ptr;
}
T& operator*() const
{
return *ptr;
}
The constructor takes ownership of the object, and the destructor deletes it:
explicit unique_ptr(T* p = nullptr)
{
ptr = p;
}
~unique_ptr()
{
delete ptr;
}
Now comes the interesting part, the move constructor:
unique_ptr(unique_ptr&& source) // note the rvalue reference
{
ptr = source.ptr;
source.ptr = nullptr;
}
This move constructor does exactly what the auto_ptr
copy constructor did, but it can only be supplied with rvalues:
unique_ptr<Shape> a(new Triangle);
unique_ptr<Shape> b(a); // error
unique_ptr<Shape> c(make_triangle()); // okay
The second line fails to compile, because a
is an lvalue, but the parameter unique_ptr&& source
can only be bound to rvalues. This is exactly what we wanted; dangerous moves should never be implicit. The third line compiles just fine, because make_triangle()
is an rvalue. The move constructor will transfer ownership from the temporary to c
. Again, this is exactly what we wanted.
The move constructor transfers ownership of a managed resource into the current object.
The last missing piece is the move assignment operator. Its job is to release the old resource and acquire the new resource from its argument:
unique_ptr& operator=(unique_ptr&& source) // note the rvalue reference
{
if (this != &source) // beware of self-assignment
{
delete ptr; // release the old resource
ptr = source.ptr; // acquire the new resource
source.ptr = nullptr;
}
return *this;
}
};
Note how this implementation of the move assignment operator duplicates logic of both the destructor and the move constructor. Are you familiar with the copy-and-swap idiom? It can also be applied to move semantics as the move-and-swap idiom:
unique_ptr& operator=(unique_ptr source) // note the missing reference
{
std::swap(ptr, source.ptr);
return *this;
}
};
Now that source
is a variable of type unique_ptr
, it will be initialized by the move constructor; that is, the argument will be moved into the parameter. The argument is still required to be an rvalue, because the move constructor itself has an rvalue reference parameter. When control flow reaches the closing brace of operator=
, source
goes out of scope, releasing the old resource automatically.
The move assignment operator transfers ownership of a managed resource into the current object, releasing the old resource. The move-and-swap idiom simplifies the implementation.
Sometimes, we want to move from lvalues. That is, sometimes we want the compiler to treat an lvalue as if it were an rvalue, so it can invoke the move constructor, even though it could be potentially unsafe.
For this purpose, C++11 offers a standard library function template called std::move
inside the header <utility>
.
This name is a bit unfortunate, because std::move
simply casts an lvalue to an rvalue; it does not move anything by itself. It merely enables moving. Maybe it should have been named std::cast_to_rvalue
or std::enable_move
, but we are stuck with the name by now.
Here is how you explicitly move from an lvalue:
unique_ptr<Shape> a(new Triangle);
unique_ptr<Shape> b(a); // still an error
unique_ptr<Shape> c(std::move(a)); // okay
Note that after the third line, a
no longer owns a triangle. That's okay, because by explicitly writing std::move(a)
, we made our intentions clear: "Dear constructor, do whatever you want with a
in order to initialize c
; I don't care about a
anymore. Feel free to have your way with a
."
std::move(some_lvalue)
casts an lvalue to an rvalue, thus enabling a subsequent move.
Note that even though std::move(a)
is an rvalue, its evaluation does not create a temporary object. This conundrum forced the committee to introduce a third value category. Something that can be bound to an rvalue reference, even though it is not an rvalue in the traditional sense, is called an xvalue (eXpiring value). The traditional rvalues were renamed to prvalues (Pure rvalues).
Both prvalues and xvalues are rvalues. Xvalues and lvalues are both glvalues (Generalized lvalues). The relationships are easier to grasp with a diagram:
expressions
/ \
/ \
/ \
glvalues rvalues
/ \ / \
/ \ / \
/ \ / \
lvalues xvalues prvalues
Note that only xvalues are really new; the rest is just due to renaming and grouping.
C++98 rvalues are known as prvalues in C++11. Mentally replace all occurrences of "rvalue" in the preceding paragraphs with "prvalue".
So far, we have seen movement into local variables, and into function parameters. But moving is also possible in the opposite direction. If a function returns by value, some object at call site (probably a local variable or a temporary, but could be any kind of object) is initialized with the expression after the return
statement as an argument to the move constructor:
unique_ptr<Shape> make_triangle()
{
return unique_ptr<Shape>(new Triangle);
} \-----------------------------/
|
| temporary is moved into c
|
v
unique_ptr<Shape> c(make_triangle());
Perhaps surprisingly, automatic objects (local variables that are not declared as static
) can also be implicitly moved out of functions:
unique_ptr<Shape> make_square()
{
unique_ptr<Shape> result(new Square);
return result; // note the missing std::move
}
How come the move constructor accepts the lvalue result
as an argument? The scope of result
is about to end, and it will be destroyed during stack unwinding. Nobody could possibly complain afterward that result
had changed somehow; when control flow is back at the caller, result
does not exist anymore! For that reason, C++11 has a special rule that allows returning automatic objects from functions without having to write std::move
. In fact, you should never use std::move
to move automatic objects out of functions, as this inhibits the "named return value optimization" (NRVO).
Never use
std::move
to move automatic objects out of functions.
Note that in both factory functions, the return type is a value, not an rvalue reference. Rvalue references are still references, and as always, you should never return a reference to an automatic object; the caller would end up with a dangling reference if you tricked the compiler into accepting your code, like this:
unique_ptr<Shape>&& flawed_attempt() // DO NOT DO THIS!
{
unique_ptr<Shape> very_bad_idea(new Square);
return std::move(very_bad_idea); // WRONG!
}
Never return automatic objects by rvalue reference. Moving is exclusively performed by the move constructor, not by
std::move
, and not by merely binding an rvalue to an rvalue reference.
Sooner or later, you are going to write code like this:
class Foo
{
unique_ptr<Shape> member;
public:
Foo(unique_ptr<Shape>&& parameter)
: member(parameter) // error
{}
};
Basically, the compiler will complain that parameter
is an lvalue. If you look at its type, you see an rvalue reference, but an rvalue reference simply means "a reference that is bound to an rvalue"; it does not mean that the reference itself is an rvalue! Indeed, parameter
is just an ordinary variable with a name. You can use parameter
as often as you like inside the body of the constructor, and it always denotes the same object. Implicitly moving from it would be dangerous, hence the language forbids it.
A named rvalue reference is an lvalue, just like any other variable.
The solution is to manually enable the move:
class Foo
{
unique_ptr<Shape> member;
public:
Foo(unique_ptr<Shape>&& parameter)
: member(std::move(parameter)) // note the std::move
{}
};
You could argue that parameter
is not used anymore after the initialization of member
. Why is there no special rule to silently insert std::move
just as with return values? Probably because it would be too much burden on the compiler implementors. For example, what if the constructor body was in another translation unit? By contrast, the return value rule simply has to check the symbol tables to determine whether or not the identifier after the return
keyword denotes an automatic object.
You can also pass the parameter
by value. For move-only types like unique_ptr
, it seems there is no established idiom yet. Personally, I prefer to pass by value, as it causes less clutter in the interface.
C++98 implicitly declares three special member functions on demand, that is, when they are needed somewhere: the copy constructor, the copy assignment operator, and the destructor.
X::X(const X&); // copy constructor
X& X::operator=(const X&); // copy assignment operator
X::~X(); // destructor
Rvalue references went through several versions. Since version 3.0, C++11 declares two additional special member functions on demand: the move constructor and the move assignment operator. Note that neither VC10 nor VC11 conforms to version 3.0 yet, so you will have to implement them yourself.
X::X(X&&); // move constructor
X& X::operator=(X&&); // move assignment operator
These two new special member functions are only implicitly declared if none of the special member functions are declared manually. Also, if you declare your own move constructor or move assignment operator, neither the copy constructor nor the copy assignment operator will be declared implicitly.
What do these rules mean in practice?
If you write a class without unmanaged resources, there is no need to declare any of the five special member functions yourself, and you will get correct copy semantics and move semantics for free. Otherwise, you will have to implement the special member functions yourself. Of course, if your class does not benefit from move semantics, there is no need to implement the special move operations.
Note that the copy assignment operator and the move assignment operator can be fused into a single, unified assignment operator, taking its argument by value:
X& X::operator=(X source) // unified assignment operator
{
swap(source); // see my first answer for an explanation
return *this;
}
This way, the number of special member functions to implement drops from five to four. There is a tradeoff between exception-safety and efficiency here, but I am not an expert on this issue.
Consider the following function template:
template<typename T>
void foo(T&&);
You might expect T&&
to only bind to rvalues, because at first glance, it looks like an rvalue reference. As it turns out though, T&&
also binds to lvalues:
foo(make_triangle()); // T is unique_ptr<Shape>, T&& is unique_ptr<Shape>&&
unique_ptr<Shape> a(new Triangle);
foo(a); // T is unique_ptr<Shape>&, T&& is unique_ptr<Shape>&
If the argument is an rvalue of type X
, T
is deduced to be X
, hence T&&
means X&&
. This is what anyone would expect.
But if the argument is an lvalue of type X
, due to a special rule, T
is deduced to be X&
, hence T&&
would mean something like X& &&
. But since C++ still has no notion of references to references, the type X& &&
is collapsed into X&
. This may sound confusing and useless at first, but reference collapsing is essential for perfect forwarding (which will not be discussed here).
T&& is not an rvalue reference, but a forwarding reference. It also binds to lvalues, in which case
T
andT&&
are both lvalue references.
If you want to constrain a function template to rvalues, you can combine SFINAE with type traits:
#include <type_traits>
template<typename T>
typename std::enable_if<std::is_rvalue_reference<T&&>::value, void>::type
foo(T&&);
Now that you understand reference collapsing, here is how std::move
is implemented:
template<typename T>
typename std::remove_reference<T>::type&&
move(T&& t)
{
return static_cast<typename std::remove_reference<T>::type&&>(t);
}
As you can see, move
accepts any kind of parameter thanks to the forwarding reference T&&
, and it returns an rvalue reference. The std::remove_reference<T>::type
meta-function call is necessary because otherwise, for lvalues of type X
, the return type would be X& &&
, which would collapse into X&
. Since t
is always an lvalue (remember that a named rvalue reference is an lvalue), but we want to bind t
to an rvalue reference, we have to explicitly cast t
to the correct return type.
The call of a function that returns an rvalue reference is itself an xvalue. Now you know where xvalues come from ;)
The call of a function that returns an rvalue reference, such as
std::move
, is an xvalue.
Note that returning by rvalue reference is fine in this example, because t
does not denote an automatic object, but instead an object that was passed in by the caller.
$(document).ready(function(){
$("#example1").datetimepicker({
allowMultidate: true,
multidateSeparator: ','
});
});
/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
using import matplotlib.pyplot as plt
Method 1: specify the fontsize when calling legend (repetitive)
plt.legend(fontsize=20) # using a size in points
plt.legend(fontsize="x-large") # using a named size
With this method you can set the fontsize for each legend at creation (allowing you to have multiple legends with different fontsizes). However, you will have to type everything manually each time you create a legend.
(Note: @Mathias711 listed the available named fontsizes in his answer)
Method 2: specify the fontsize in rcParams (convenient)
plt.rc('legend',fontsize=20) # using a size in points
plt.rc('legend',fontsize='medium') # using a named size
With this method you set the default legend fontsize, and all legends will automatically use that unless you specify otherwise using method 1. This means you can set your legend fontsize at the beginning of your code, and not worry about setting it for each individual legend.
If you use a named size e.g. 'medium'
, then the legend text will scale with the global font.size
in rcParams
. To change font.size
use plt.rc(font.size='medium')
Subclassing is a little cumbersome for such a simple case. An alternative is to simply add the UILabel with no background set to a UIView with the background set. Set the label's x to 10 and make the outer view's size 20 pixels wider than the label.
I recommend @Jens Gustedt hexadecimal solution: use %a.
OP wants “print with maximum precision (or at least to the most significant decimal)”.
A simple example would be to print one seventh as in:
#include <float.h>
int Digs = DECIMAL_DIG;
double OneSeventh = 1.0/7.0;
printf("%.*e\n", Digs, OneSeventh);
// 1.428571428571428492127e-01
But let's dig deeper ...
Mathematically, the answer is "0.142857 142857 142857 ...", but we are using finite precision floating point numbers.
Let's assume IEEE 754 double-precision binary.
So the OneSeventh = 1.0/7.0
results in the value below. Also shown are the preceding and following representable double
floating point numbers.
OneSeventh before = 0.1428571428571428 214571170656199683435261249542236328125
OneSeventh = 0.1428571428571428 49212692681248881854116916656494140625
OneSeventh after = 0.1428571428571428 769682682968777953647077083587646484375
Printing the exact decimal representation of a double
has limited uses.
C has 2 families of macros in <float.h>
to help us.
The first set is the number of significant digits to print in a string in decimal so when scanning the string back,
we get the original floating point. There are shown with the C spec's minimum value and a sample C11 compiler.
FLT_DECIMAL_DIG 6, 9 (float) (C11)
DBL_DECIMAL_DIG 10, 17 (double) (C11)
LDBL_DECIMAL_DIG 10, 21 (long double) (C11)
DECIMAL_DIG 10, 21 (widest supported floating type) (C99)
The second set is the number of significant digits a string may be scanned into a floating point and then the FP printed, still retaining the same string presentation. There are shown with the C spec's minimum value and a sample C11 compiler. I believe available pre-C99.
FLT_DIG 6, 6 (float)
DBL_DIG 10, 15 (double)
LDBL_DIG 10, 18 (long double)
The first set of macros seems to meet OP's goal of significant digits. But that macro is not always available.
#ifdef DBL_DECIMAL_DIG
#define OP_DBL_Digs (DBL_DECIMAL_DIG)
#else
#ifdef DECIMAL_DIG
#define OP_DBL_Digs (DECIMAL_DIG)
#else
#define OP_DBL_Digs (DBL_DIG + 3)
#endif
#endif
The "+ 3" was the crux of my previous answer. Its centered on if knowing the round-trip conversion string-FP-string (set #2 macros available C89), how would one determine the digits for FP-string-FP (set #1 macros available post C89)? In general, add 3 was the result.
Now how many significant digits to print is known and driven via <float.h>
.
To print N significant decimal digits one may use various formats.
With "%e"
, the precision field is the number of digits after the lead digit and decimal point.
So - 1
is in order. Note: This -1
is not in the initial int Digs = DECIMAL_DIG;
printf("%.*e\n", OP_DBL_Digs - 1, OneSeventh);
// 1.4285714285714285e-01
With "%f"
, the precision field is the number of digits after the decimal point.
For a number like OneSeventh/1000000.0
, one would need OP_DBL_Digs + 6
to see all the significant digits.
printf("%.*f\n", OP_DBL_Digs , OneSeventh);
// 0.14285714285714285
printf("%.*f\n", OP_DBL_Digs + 6, OneSeventh/1000000.0);
// 0.00000014285714285714285
Note: Many are use to "%f"
. That displays 6 digits after the decimal point; 6 is the display default, not the precision of the number.
As posted in another answer, the wildcard library works for both glob and regex filename matching: http://code.google.com/p/wildcard/
I used the following code to match glob patterns including absolute and relative on *nix style file systems:
String filePattern = String baseDir = "./";
// If absolute path. TODO handle windows absolute path?
if (filePattern.charAt(0) == File.separatorChar) {
baseDir = File.separator;
filePattern = filePattern.substring(1);
}
Paths paths = new Paths(baseDir, filePattern);
List files = paths.getFiles();
I spent some time trying to get the FileUtils.listFiles methods in the Apache commons io library (see Vladimir's answer) to do this but had no success (I realise now/think it can only handle pattern matching one directory or file at a time).
Additionally, using regex filters (see Fabian's answer) for processing arbitrary user supplied absolute type glob patterns without searching the entire file system would require some preprocessing of the supplied glob to determine the largest non-regex/glob prefix.
Of course, Java 7 may handle the requested functionality nicely, but unfortunately I'm stuck with Java 6 for now. The library is relatively minuscule at 13.5kb in size.
Note to the reviewers: I attempted to add the above to the existing answer mentioning this library but the edit was rejected. I don't have enough rep to add this as a comment either. Isn't there a better way...
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
Warning
Do not use this as some kind of security measurement.
The encryption mechanism in this post is a One-time pad, which means that the secret key can be easily recovered by an attacker using 2 encrypted messages. XOR 2 encrypted messages and you get the key. That simple!
Pointed out by Moussa
I am using Sun's Base64Encoder/Decoder which is to be found in Sun's JRE, to avoid yet another JAR in lib. That's dangerous from point of using OpenJDK or some other's JRE. Besides that, is there another reason I should consider using Apache commons lib with Encoder/Decoder?
public class EncryptUtils {
public static final String DEFAULT_ENCODING = "UTF-8";
static BASE64Encoder enc = new BASE64Encoder();
static BASE64Decoder dec = new BASE64Decoder();
public static String base64encode(String text) {
try {
return enc.encode(text.getBytes(DEFAULT_ENCODING));
} catch (UnsupportedEncodingException e) {
return null;
}
}//base64encode
public static String base64decode(String text) {
try {
return new String(dec.decodeBuffer(text), DEFAULT_ENCODING);
} catch (IOException e) {
return null;
}
}//base64decode
public static void main(String[] args) {
String txt = "some text to be encrypted";
String key = "key phrase used for XOR-ing";
System.out.println(txt + " XOR-ed to: " + (txt = xorMessage(txt, key)));
String encoded = base64encode(txt);
System.out.println(" is encoded to: " + encoded + " and that is decoding to: " + (txt = base64decode(encoded)));
System.out.print("XOR-ing back to original: " + xorMessage(txt, key));
}
public static String xorMessage(String message, String key) {
try {
if (message == null || key == null) return null;
char[] keys = key.toCharArray();
char[] mesg = message.toCharArray();
int ml = mesg.length;
int kl = keys.length;
char[] newmsg = new char[ml];
for (int i = 0; i < ml; i++) {
newmsg[i] = (char)(mesg[i] ^ keys[i % kl]);
}//for i
return new String(newmsg);
} catch (Exception e) {
return null;
}
}//xorMessage
}//class
sudo npm install npm@latest -g
Just hook up the onclick event:
<input id="button" type="submit" name="button" value="enter" onclick="myFunction();"/>
As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx
Template
<form [formGroup]="mainForm" ng-submit="submitForm()">
Global Price: <input type="number" formControlName="globalPrice">
<button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
<table border formArrayName="orderLines">
<ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
<tr>
<td>{{orderLine.time | date}}</td>
<td>{{orderLine.quantity}}</td>
<td><input formControlName="price" type="number"></td>
</tr>
</ng-container>
</table>
</form>
Component
import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 6';
mainForm: FormGroup;
orderLines = [
{price: 10, time: new Date(), quantity: 2},
{price: 20, time: new Date(), quantity: 3},
{price: 30, time: new Date(), quantity: 3},
{price: 40, time: new Date(), quantity: 5}
]
constructor() {
this.mainForm = this.getForm();
}
getForm(): FormGroup {
return new FormGroup({
globalPrice: new FormControl(),
orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
})
}
getFormGroupForLine(orderLine: any): FormGroup {
return new FormGroup({
price: new FormControl(orderLine.price)
})
}
applyPriceToAll() {
const formLines = this.mainForm.get('orderLines') as FormArray;
const globalPrice = this.mainForm.get('globalPrice').value;
formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
// optionally recheck value and validity without emit event.
}
submitForm() {
}
}
You can think of an ArrayBuffer
as a typed Buffer
.
An ArrayBuffer
therefore always needs a type (the so-called "Array Buffer View"). Typically, the Array Buffer View has a type of Uint8Array
or Uint16Array
.
There is a good article from Renato Mangini on converting between an ArrayBuffer and a String.
I have summarized the essential parts in a code example (for Node.js). It also shows how to convert between the typed ArrayBuffer
and the untyped Buffer
.
function stringToArrayBuffer(string) {
const arrayBuffer = new ArrayBuffer(string.length);
const arrayBufferView = new Uint8Array(arrayBuffer);
for (let i = 0; i < string.length; i++) {
arrayBufferView[i] = string.charCodeAt(i);
}
return arrayBuffer;
}
function arrayBufferToString(buffer) {
return String.fromCharCode.apply(null, new Uint8Array(buffer));
}
const helloWorld = stringToArrayBuffer('Hello, World!'); // "ArrayBuffer" (Uint8Array)
const encodedString = new Buffer(helloWorld).toString('base64'); // "string"
const decodedBuffer = Buffer.from(encodedString, 'base64'); // "Buffer"
const decodedArrayBuffer = new Uint8Array(decodedBuffer).buffer; // "ArrayBuffer" (Uint8Array)
console.log(arrayBufferToString(decodedArrayBuffer)); // prints "Hello, World!"
using System.Linq;
list.Where(x=> x.Name == nameToExtract);
Edit: misread question (now all matches)
$('.launchConfirm').on('click', function (e) {
$('#confirm')
.modal({ backdrop: 'static', keyboard: false })
.one('click', '#delete', function (e) {
//delete function
});
});
For your button:
<button class='btn btn-danger btn-xs launchConfirm' type="button" name="remove_levels"><span class="fa fa-times"></span> delete</button></td>
You create a tap, pinch or swipe gesture recognizer in the same manor. Below I'll walk you through 4 steps to getting your recognizer up and running.
4 Steps
1.) Inherit from UIGestureRecognizerDelegate
by adding it to your class signature.
class ViewController: UIViewController, UIGestureRecognizerDelegate {...}
2.) Control drag from your image to your viewController to create an IBOutlet:
@IBOutlet weak var tapView: UIImageView!
3.) In your viewDidLoad add the following code:
// create an instance of UITapGestureRecognizer and tell it to run
// an action we'll call "handleTap:"
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
// we use our delegate
tap.delegate = self
// allow for user interaction
tapView.userInteractionEnabled = true
// add tap as a gestureRecognizer to tapView
tapView.addGestureRecognizer(tap)
4.) Create the function that will be called when your gesture recognizer is tapped. (You can exclude the = nil
if you choose).
func handleTap(sender: UITapGestureRecognizer? = nil) {
// just creating an alert to prove our tap worked!
let tapAlert = UIAlertController(title: "hmmm...", message: "this actually worked?", preferredStyle: UIAlertControllerStyle.Alert)
tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
self.presentViewController(tapAlert, animated: true, completion: nil)
}
Your final code should look something like this:
class ViewController: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet weak var tapView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
tap.delegate = self
tapView.userInteractionEnabled = true
tapView.addGestureRecognizer(tap)
}
func handleTap(sender: UITapGestureRecognizer? = nil) {
let tapAlert = UIAlertController(title: "hmmm...", message: "this actually worked?", preferredStyle: UIAlertControllerStyle.Alert)
tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
self.presentViewController(tapAlert, animated: true, completion: nil)
}
}
From version 2.13.0
of Dart Code, emulators can be launched directly from within Code but This feature relies on support from the Flutter tools which means it will only show emulators when using a very recent Flutter SDK. Flutter’s master channel already has this change, but it may take a little longer to filter through to the dev and beta channels.
I tested this feature and worked very well on flutter version 0.5.6-pre.61 (master channel)
The easiest solution is to simply style the element you're inserting the text into with the following CSS property:
white-space: pre-wrap;
This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a <textarea>
. That is, consecutive whitespace is not collapsed, and lines are broken at explicit newlines (but are also wrapped automatically if they exceed the width of the element).
Given that several of the answers posted here so far have been vulnerable to HTML injection (e.g. because they assign unescaped user input to innerHTML
) or otherwise buggy, let me give an example of how to do this safely and correctly, based on your original code:
document.getElementById('post-button').addEventListener('click', function () {_x000D_
var post = document.createElement('p');_x000D_
var postText = document.getElementById('post-text').value;_x000D_
post.append(postText);_x000D_
var card = document.createElement('div');_x000D_
card.append(post);_x000D_
var cardStack = document.getElementById('card-stack');_x000D_
cardStack.prepend(card);_x000D_
});
_x000D_
#card-stack p {_x000D_
background: #ddd;_x000D_
white-space: pre-wrap; /* <-- THIS PRESERVES THE LINE BREAKS */_x000D_
}_x000D_
textarea {_x000D_
width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
Note that, like your original code, the snippet above uses append()
and prepend()
. As of this writing, those functions are still considered experimental and not fully supported by all browsers. If you want to be safe and remain compatible with older browsers, you can substitute them pretty easily as follows:
element.append(otherElement)
can be replaced with element.appendChild(otherElement)
;element.prepend(otherElement)
can be replaced with element.insertBefore(otherElement, element.firstChild)
;element.append(stringOfText)
can be replaced with element.appendChild(document.createTextNode(stringOfText))
;element.prepend(stringOfText)
can be replaced with element.insertBefore(document.createTextNode(stringOfText), element.firstChild)
;element
is empty, both element.append(stringOfText)
and element.prepend(stringOfText)
can simply be replaced with element.textContent = stringOfText
.Here's the same snippet as above, but without using append()
or prepend()
:
document.getElementById('post-button').addEventListener('click', function () {_x000D_
var post = document.createElement('p');_x000D_
var postText = document.getElementById('post-text').value;_x000D_
post.textContent = postText;_x000D_
var card = document.createElement('div');_x000D_
card.appendChild(post);_x000D_
var cardStack = document.getElementById('card-stack');_x000D_
cardStack.insertBefore(card, cardStack.firstChild);_x000D_
});
_x000D_
#card-stack p {_x000D_
background: #ddd;_x000D_
white-space: pre-wrap; /* <-- THIS PRESERVES THE LINE BREAKS */_x000D_
}_x000D_
textarea {_x000D_
width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
Ps. If you really want to do this without using the CSS white-space
property, an alternative solution would be to explicitly replace any newline characters in the text with <br>
HTML tags. The tricky part is that, to avoid introducing subtle bugs and potential security holes, you have to first escape any HTML metacharacters (at a minimum, &
and <
) in the text before you do this replacement.
Probably the simplest and safest way to do that is to let the browser handle the HTML-escaping for you, like this:
var post = document.createElement('p');
post.textContent = postText;
post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');
document.getElementById('post-button').addEventListener('click', function () {_x000D_
var post = document.createElement('p');_x000D_
var postText = document.getElementById('post-text').value;_x000D_
post.textContent = postText;_x000D_
post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n'); // <-- THIS FIXES THE LINE BREAKS_x000D_
var card = document.createElement('div');_x000D_
card.appendChild(post);_x000D_
var cardStack = document.getElementById('card-stack');_x000D_
cardStack.insertBefore(card, cardStack.firstChild);_x000D_
});
_x000D_
#card-stack p {_x000D_
background: #ddd;_x000D_
}_x000D_
textarea {_x000D_
width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
Note that, while this will fix the line breaks, it won't prevent consecutive whitespace from being collapsed by the HTML renderer. It's possible to (sort of) emulate that by replacing some of the whitespace in the text with non-breaking spaces, but honestly, that's getting rather complicated for something that can be trivially solved with a single line of CSS.
What about calling the buster repeatedly as well? This'll create a race condition, but one may hope that the buster comes out on top:
(function() {
if(top !== self) {
top.location.href = self.location.href;
setTimeout(arguments.callee, 0);
}
})();
Another option is to use a multi-stage docker build to ensure that your SSH keys are not included in the final image.
As described in my post you can prepare your intermediate image with the required dependencies to git clone and then COPY
the required files into your final image.
Additionally if we LABEL
our intermediate layers, we can even delete them from the machine when finished.
# Choose and name our temporary image.
FROM alpine as intermediate
# Add metadata identifying these images as our build containers (this will be useful later!)
LABEL stage=intermediate
# Take an SSH key as a build argument.
ARG SSH_KEY
# Install dependencies required to git clone.
RUN apk update && \
apk add --update git && \
apk add --update openssh
# 1. Create the SSH directory.
# 2. Populate the private key file.
# 3. Set the required permissions.
# 4. Add github to our list of known hosts for ssh.
RUN mkdir -p /root/.ssh/ && \
echo "$SSH_KEY" > /root/.ssh/id_rsa && \
chmod -R 600 /root/.ssh/ && \
ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
# Clone a repository (my website in this case)
RUN git clone [email protected]:janakerman/janakerman.git
# Choose the base image for our final image
FROM alpine
# Copy across the files from our `intermediate` container
RUN mkdir files
COPY --from=intermediate /janakerman/README.md /files/README.md
We can then build:
MY_KEY=$(cat ~/.ssh/id_rsa)
docker build --build-arg SSH_KEY="$MY_KEY" --tag clone-example .
Prove our SSH keys are gone:
docker run -ti --rm clone-example cat /root/.ssh/id_rsa
Clean intermediate images from the build machine:
docker rmi -f $(docker images -q --filter label=stage=intermediate)
use like this :-
gridview1.DataSource = ds.Tables[0]; <-- Use index or your table name which you want to bind
gridview1.DataBind();
I hope it helps!!
If you just want to print user name on the pages, maybe you'll like this solution. It's free from object castings and works without Spring Security too:
@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public ModelAndView indexView(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("index");
String userName = "not logged in"; // Any default user name
Principal principal = request.getUserPrincipal();
if (principal != null) {
userName = principal.getName();
}
mv.addObject("username", userName);
// By adding a little code (same way) you can check if user has any
// roles you need, for example:
boolean fAdmin = request.isUserInRole("ROLE_ADMIN");
mv.addObject("isAdmin", fAdmin);
return mv;
}
Note "HttpServletRequest request" parameter added.
Works fine because Spring injects it's own objects (wrappers) for HttpServletRequest, Principal etc., so you can use standard java methods to retrieve user information.
Try restarting your computer if you just installed SQL Server and there's no choice in the SQL Server Installation Center to install SQL Server Management Studio.
This choice (see image below) only appeared for me after I installed SQL Server, then restarted my computer:
Try using the ACQUIRE_CAUSES_WAKEUP flag when you create the wake lock. The ON_AFTER_RELEASE flag just resets the activity timer to keep the screen on a bit longer.
http://developer.android.com/reference/android/os/PowerManager.html#ACQUIRE_CAUSES_WAKEUP
I just wanted to give my two cents.
This is according to @Powerlord 's answer.
Puts "null" instead of null strings.
private static Dictionary<string, string> map = new Dictionary<string, string>();
public static void put(string key, string value)
{
if (value == null) value = "null";
map[key] = value;
}
public static string get(string key, string defaultValue)
{
try
{
return map[key];
}
catch (KeyNotFoundException e)
{
return defaultValue;
}
}
public static string get(string key)
{
return get(key, "null");
}
Try out this method which would try to cover for all the possible Exceptions scenarios. It would work for almost all the Windows related Paths.
/// <summary>
/// Validate the Path. If path is relative append the path to the project directory by default.
/// </summary>
/// <param name="path">Path to validate</param>
/// <param name="RelativePath">Relative path</param>
/// <param name="Extension">If want to check for File Path</param>
/// <returns></returns>
private static bool ValidateDllPath(ref string path, string RelativePath = "", string Extension = "") {
// Check if it contains any Invalid Characters.
if (path.IndexOfAny(Path.GetInvalidPathChars()) == -1) {
try {
// If path is relative take %IGXLROOT% as the base directory
if (!Path.IsPathRooted(path)) {
if (string.IsNullOrEmpty(RelativePath)) {
// Exceptions handled by Path.GetFullPath
// ArgumentException path is a zero-length string, contains only white space, or contains one or more of the invalid characters defined in GetInvalidPathChars. -or- The system could not retrieve the absolute path.
//
// SecurityException The caller does not have the required permissions.
//
// ArgumentNullException path is null.
//
// NotSupportedException path contains a colon (":") that is not part of a volume identifier (for example, "c:\").
// PathTooLongException The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
// RelativePath is not passed so we would take the project path
path = Path.GetFullPath(RelativePath);
} else {
// Make sure the path is relative to the RelativePath and not our project directory
path = Path.Combine(RelativePath, path);
}
}
// Exceptions from FileInfo Constructor:
// System.ArgumentNullException:
// fileName is null.
//
// System.Security.SecurityException:
// The caller does not have the required permission.
//
// System.ArgumentException:
// The file name is empty, contains only white spaces, or contains invalid characters.
//
// System.IO.PathTooLongException:
// The specified path, file name, or both exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters, and file names must be less than 260 characters.
//
// System.NotSupportedException:
// fileName contains a colon (:) in the middle of the string.
FileInfo fileInfo = new FileInfo(path);
// Exceptions using FileInfo.Length:
// System.IO.IOException:
// System.IO.FileSystemInfo.Refresh() cannot update the state of the file or
// directory.
//
// System.IO.FileNotFoundException:
// The file does not exist.-or- The Length property is called for a directory.
bool throwEx = fileInfo.Length == -1;
// Exceptions using FileInfo.IsReadOnly:
// System.UnauthorizedAccessException:
// Access to fileName is denied.
// The file described by the current System.IO.FileInfo object is read-only.-or-
// This operation is not supported on the current platform.-or- The caller does
// not have the required permission.
throwEx = fileInfo.IsReadOnly;
if (!string.IsNullOrEmpty(Extension)) {
// Validate the Extension of the file.
if (Path.GetExtension(path).Equals(Extension, StringComparison.InvariantCultureIgnoreCase)) {
// Trim the Library Path
path = path.Trim();
return true;
} else {
return false;
}
} else {
return true;
}
} catch (ArgumentNullException) {
// System.ArgumentNullException:
// fileName is null.
} catch (System.Security.SecurityException) {
// System.Security.SecurityException:
// The caller does not have the required permission.
} catch (ArgumentException) {
// System.ArgumentException:
// The file name is empty, contains only white spaces, or contains invalid characters.
} catch (UnauthorizedAccessException) {
// System.UnauthorizedAccessException:
// Access to fileName is denied.
} catch (PathTooLongException) {
// System.IO.PathTooLongException:
// The specified path, file name, or both exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters, and file names must be less than 260 characters.
} catch (NotSupportedException) {
// System.NotSupportedException:
// fileName contains a colon (:) in the middle of the string.
} catch (FileNotFoundException) {
// System.FileNotFoundException
// The exception that is thrown when an attempt to access a file that does not
// exist on disk fails.
} catch (IOException) {
// System.IO.IOException:
// An I/O error occurred while opening the file.
} catch (Exception) {
// Unknown Exception. Might be due to wrong case or nulll checks.
}
} else {
// Path contains invalid characters
}
return false;
}
parseDouble() method is used to initialise a STRING (which should contains some numerical value)....the value it returns is of primitive data type, like int, float, etc.
But valueOf() creates an object of Wrapper class. You have to unwrap it in order to get the double value. It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.
Observe the following conversion.
int k = 100;
Integer it1 = new Integer(k);
The int data type k is converted into an object, it1 using Integer class. The it1 object can be used in Java programming wherever k is required an object.
The following code can be used to unwrap (getting back int from Integer object) the object it1.
int m = it1.intValue();
System.out.println(m*m); // prints 10000
//intValue() is a method of Integer class that returns an int data type.
RC's post was SUPER useful. I never thought about using the $(dir $@) function, but it did exactly what I needed it to do.
In parentDir, have a bunch of directories with source files in them: dirA, dirB, dirC. Various files depend on the object files in other directories, so I wanted to be able to make one file from within one directory, and have it make that dependency by calling the makefile associated with that dependency.
Essentially, I made one Makefile in parentDir that had (among many other things) a generic rule similar to RC's:
%.o : %.cpp @mkdir -p $(dir $@) @echo "=============" @echo "Compiling $<" @$(CC) $(CFLAGS) -c $< -o $@
Each subdirectory included this upper-level makefile in order to inherit this generic rule. In each subdirectory's Makefile, I wrote a custom rule for each file so that I could keep track of everything that each individual file depended on.
Whenever I needed to make a file, I used (essentially) this rule to recursively make any/all dependencies. Perfect!
NOTE: there's a utility called "makepp" that seems to do this very task even more intuitively, but for the sake of portability and not depending on another tool, I chose to do it this way.
Hope this helps!
While in insert mode hit CTRL-R {register}
Examples:
CTRL-R *
will insert in the contents of the clipboard CTRL-R "
(the unnamed register) inserts the last delete or yank. To find this in vim's help type :h i_ctrl-r
In my case i made a new installation of php7 using xampp, the error was in php.ini at line 699, i just did
include_path= C:\Program Files (x86)\xampp\php\PEAR
to
include_path= "C:\Program Files (x86)\xampp\php\PEAR"
and it worked for me.
I checked this by running the php.exe it gave me that error and i fixed it.
Just call fig.tight_layout()
as you normally would. (pyplot
is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)
There shouldn't be a difference between the QtAgg
backend and the default backend (or if there is, it's a bug).
E.g.
import matplotlib.pyplot as plt
#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so
#-- we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
plt.show()
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
fig.tight_layout()
plt.show()
You can use this code:
$('#country').select2("val", "Your_value").trigger('change');
Put your desired value instead of Your_value
Hope It will work :)
This happens to me when I'm using Jinja2 for templates. The problem can be solved by running the development server using the runserver_plus
command from django_extensions.
It uses the werkzeug debugger which also happens to be a lot better and has a very nice interactive debugging console. It does some ajax magic to launch a python shell at any frame (in the call stack) so you can debug.