Your DNA molecules are double-linked lists.
Are you trying to make something like this?
public List<Car> getAll() {
return new ArrayList<Car>(cars);
}
And then calling it:
List<Car> cars = c1.getAll();
for (Car item : cars) {
System.out.println(item.getMake() + " " + item.getReg());
}
While executing multiple lines of code in R, you need to first select all the lines of code and then click on "Run". This error usually comes up when we don't select our statements and click on "Run".
Please don't call any StartForgroundServices inside onCreate() method, you have to call StartForground services in onStartCommand() after make the worker thread otherwise you will get ANR always , so please don't write complex login in main thread of onStartCommand();
public class Services extends Service {
private static final String ANDROID_CHANNEL_ID = "com.xxxx.Location.Channel";
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText("SmartTracker Running")
.setAutoCancel(true);
Notification notification = builder.build();
startForeground(0, notification);
Log.e("home_button","home button");
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentTitle(getString(R.string.app_name))
.setContentText("SmartTracker is Running...")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
Notification notification = builder.build();
startForeground(0, notification);
Log.e("home_button_value","home_button_value");
}
return super.onStartCommand(intent, flags, startId);
}
}
EDIT: Caution! startForeground function can't take 0 as first argument, it will raise an exception! this example contains wrong function call, change 0 to your own const which couldnt be 0 or be greater than Max(Int32)
When the user triggers the generation of the file, you could simply assign a unique ID to that "download", and send the user to a page which refreshes (or checks with AJAX) every few seconds. Once the file is finished, save it under that same unique ID and...
Then you can skip the whole iframe/waiting/browserwindow mess, yet have a really elegant solution.
You can also set processData to true:
collection.fetch({
data: { page: 1 },
processData: true
});
Jquery will auto process data object into param string,
but in Backbone.sync function, Backbone turn the processData off because Backbone will use other method to process data in POST,UPDATE...
in Backbone source:
if (params.type !== 'GET' && !Backbone.emulateJSON) {
params.processData = false;
}
If you want to see the distinct values of a specific column in your dataframe , you would just need to write -
df.select('colname').distinct().show(100,False)
This would show the 100 distinct values (if 100 values are available) for the colname column in the df dataframe.
If you want to do something fancy on the distinct values, you can save the distinct values in a vector
a = df.select('colname').distinct()
Here, a would have all the distinct values of the column colname
This code will accept all country code with + sign
<input type="text" pattern="[0-9]{5}[-][0-9]{7}[-][0-9]{1}"/>
Some countries allow a single "0" character instead of "+" and others a double "0" character instead of the "+". Neither are standard.
React + TypeScript inline util method:
const navigateToExternalUrl = (url: string, shouldOpenNewTab: boolean = true) =>
shouldOpenNewTab ? window.open(url, "_blank") : window.location.href = url;
An alternative is to use the vroom
package. Now on CRAN.
vroom
doesn't load the entire file, it indexes where each record is located, and is read later when you use it.
Only pay for what you use.
See Introduction to vroom, Get started with vroom and the vroom benchmarks.
The basic overview is that the initial read of a huge file, will be much faster, and subsequent modifications to the data may be slightly slower. So depending on what your use is, it could be the best option.
See a simplified example from vroom benchmarks below, the key parts to see is the super fast read times, but slightly sower operations like aggregate etc..
package read print sample filter aggregate total
read.delim 1m 21.5s 1ms 315ms 764ms 1m 22.6s
readr 33.1s 90ms 2ms 202ms 825ms 34.2s
data.table 15.7s 13ms 1ms 129ms 394ms 16.3s
vroom (altrep) dplyr 1.7s 89ms 1.7s 1.3s 1.9s 6.7s
What you want to do is separate the content of the table from the header of the table.
You want only the <th>
elements to be scrolled.
You can easily define this separation in HTML with the <tbody>
and the <thead>
elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block
. This way <thead>
and <tbody>
are separated.
table tbody, table thead
{
display: block;
}
Now you can set the scroll to the body of the table:
table tbody
{
overflow: auto;
height: 100px;
}
And last, because the <thead>
doesn't share the same width as the body anymore, you should set a static width to the header of the table:
th
{
width: 72px;
}
You should also set a static width for <td>
. This solves the issue of the unaligned columns.
td
{
width: 72px;
}
<tr>
element, that includes the header row:
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
I hope this is what you meant.
Addendum
If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:
table th:nth-child(1), td:nth-child(1) { min-width: 50px; max-width: 50px; }
table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
<?php echo date("H:i", time()); ?>
<?php echo $days[date("l", time())] . date(", d.m.Y", time()); ?>
Simple, this should do the trick
Yes, make the shortcut's path
%comspec% /k <command>
where
%comspec%
is the environment variable for cmd.exe's full path, equivalent to C:\Windows\System32\cmd.exe
on most (if not all) Windows installs/k
keeps the window open after the command has run, this may be replaced with /c
if you want the window to close once the command is finished running<command>
is the command you wish to runI solved it in my site making this in functions.php
add_action("template_redirect", "start_buffer");
add_action("shutdown", "end_buffer", 999);
function filter_buffer($buffer) {
$buffer = replace_insecure_links($buffer);
return $buffer;
}
function start_buffer(){
ob_start("filter_buffer");
}
function end_buffer(){
if (ob_get_length()) ob_end_flush();
}
function replace_insecure_links($str) {
$str = str_replace ( array("http://www.yoursite.com/", "https://www.yoursite.com/") , array("/", "/"), $str);
return apply_filters("rsssl_fixer_output", $str);
}
I took part of one plugin, cut it into pieces and make this. It replaced ALL links in my site (menus, css, scripts etc.) and everything was working.
You can run build
for a specific service by running docker-compose up --build <service name>
where the service name must match how did you call it in your docker-compose file.
Example
Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application
in docker-compose file.
You can then simply run docker-compose up --build application
Extra parameters
In case you want to add extra parameters to your command such as -d
for running in the background, the parameter must be before the service name:
docker-compose up --build -d application
Another possible source of this issue is USB tethering. If you have used USB tethering, turn it off, then unplug the device from USB, plug it back in, then do
adb kill-server
adb devices
That did the trick in my case (Ubuntu 12.04, Nexus S, SDK in home dir, never needed root to get it running). Depending on your device, you may need to run adb devices
as root, though.
You should look into Java's interfaces. A quick Google search revealed this page, which looks pretty good.
I like to think of an interface
as a "promise" of sorts: Any class that implements it has certain behavior that can be expected of it, and therefore you can put an instance of an implementing class into an interface-type reference.
A simple example is the java.lang.Comparable
interface. By implementing all methods in this interface in your own class, you are claiming that your objects are "comparable" to one another, and can be partially ordered.
Implementing an interface requires two steps:
Interface java.lang.Comparable
has just one method in it, public int compareTo(Object other)
. So you need to provide that method.
Here's an example. Given this class RationalNumber
:
public class RationalNumber
{
public int numerator;
public int denominator;
public RationalNumber(int num, int den)
{
this.numerator = num;
this.denominator = den;
}
}
(Note: It's generally bad practice in Java to have public fields, but I am intending this to be a very simple plain-old-data type so I don't care about public fields!)
If I want to be able to compare two RationalNumber
instances (for sorting purposes, maybe?), I can do that by implementing the java.lang.Comparable
interface. In order to do that, two things need to be done: provide a definition for compareTo
and declare that the interface is implemented.
Here's how the fleshed-out class might look:
public class RationalNumber implements java.lang.Comparable
{
public int numerator;
public int denominator;
public RationalNumber(int num, int den)
{
this.numerator = num;
this.denominator = den;
}
public int compareTo(Object other)
{
if (other == null || !(other instanceof RationalNumber))
{
return -1; // Put this object before non-RationalNumber objects
}
RationalNumber r = (RationalNumber)other;
// Do the calculations by cross-multiplying. This isn't really important to
// the answer, but the point is we're comparing the two rational numbers.
// And no, I don't care if it's mathematically inaccurate.
int myTotal = this.numerator * other.denominator;
int theirTotal = other.numerator * this.denominator;
if (myTotal < theirTotal) return -1;
if (myTotal > theirTotal) return 1;
return 0;
}
}
You're probably thinking, what was the point of all this? The answer is when you look at methods like this: sorting algorithms that just expect "some kind of comparable object". (Note the requirement that all objects must implement java.lang.Comparable
!) That method can take lists of ANY kind of comparable objects, be they String
s or Integer
s or RationalNumber
s.
NOTE: I'm using practices from Java 1.4 in this answer. java.lang.Comparable
is now a generic interface, but I don't have time to explain generics.
Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.
// Outputs F because A is replaced with B, then B is replaced with C, and so on... // Finally E is replaced with F, because of left to right replacements. $search = array('A', 'B', 'C', 'D', 'E'); $replace = array('B', 'C', 'D', 'E', 'F'); $subject = 'A'; echo str_replace($search, $replace, $subject);
CSS3 introduced flexible boxes (aka. flex box) which can also achieve this behavior.
Simply define the width of the first div, and then give the second a flex-grow
value of 1
which will allow it to fill the remaining width of the parent.
.container{
display: flex;
}
.fixed{
width: 200px;
}
.flex-item{
flex-grow: 1;
}
<div class="container">
<div class="fixed"></div>
<div class="flex-item"></div>
</div>
Demo:
div {
color: #fff;
font-family: Tahoma, Verdana, Segoe, sans-serif;
padding: 10px;
}
.container {
background-color:#2E4272;
display:flex;
}
.fixed {
background-color:#4F628E;
width: 200px;
}
.flex-item {
background-color:#7887AB;
flex-grow: 1;
}
_x000D_
<div class="container">
<div class="fixed">Fixed width</div>
<div class="flex-item">Dynamically sized content</div>
</div>
_x000D_
Note that flex boxes are not backwards compatible with old browsers, but is a great option for targeting modern browsers (see also Caniuse and MDN). A great comprehensive guide on how to use flex boxes is available on CSS Tricks.
The accepted solution wasn't working. Chrome was printing a blank page because it wasn't loading the image in time. This approach works:
Edit: It appears the accepted solution was modified after my post. Why the downvote? This solution works as well.
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
w = window.open();
w.document.write(printContents);
w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');
w.document.close(); // necessary for IE >= 10
w.focus(); // necessary for IE >= 10
return true;
}
people using pandas package
import os
import pandas as pd
tar = os.chdir('<dir path only>') # do not mention file name here
print os.getcwd()# to print the path name in CLI
the following syntax to be used to import the file in python CLI
dataset(*just a variable) = pd.read_csv('new.csv')
Try using this:
If you specify
ON DUPLICATE KEY UPDATE
, and a row is inserted that would cause a duplicate value in aUNIQUE index or
PRIMARY KEY, MySQL performs an [
UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...The
ON DUPLICATE KEY UPDATE
clause can contain multiple column assignments, separated by commas.With
ON DUPLICATE KEY UPDATE
, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify theCLIENT_FOUND_ROWS
flag tomysql_real_connect()
when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...
you can filter the waypoints by passing the user to the form init
class waypointForm(forms.Form):
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ChoiceField(
choices=[(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
)
from your view while initiating the form pass the user
form = waypointForm(user)
in case of model form
class waypointForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ModelChoiceField(
queryset=Waypoint.objects.filter(user=user)
)
class Meta:
model = Waypoint
Prior to PHP 5.5, the the PHP docs used to say:
empty() only checks variables as anything else will result in a parse error
In PHP < 5.5 you weren't able use empty()
directly on a function's return value. Instead, you could assign the return from getError()
to a variable and run empty()
on the variable.
In PHP >= 5.5 this is no longer necessary.
You can use org.apache.commons.io.IOUtils.toString(InputStream is, Charset chs)
to do that.
e.g.
IOUtils.toString(context.getResources().openRawResource(<your_resource_id>), StandardCharsets.UTF_8)
For adding the correct library:
Add the following to your app/build.gradle file:
dependencies { compile 'org.apache.directory.studio:org.apache.commons.io:2.4' }
or for the Maven repo see -> this link
For direct jar download see-> https://commons.apache.org/proper/commons-io/download_io.cgi
To create a composite unique key on table
ALTER TABLE [TableName] ADD UNIQUE ([Column1], [Column2], [column3]);
I had a very similar issue with the same error message. "Changes not staged for commit", yet when I do a diff it shows differences. I finally figured out that a while back I had changed a directories case. ex. "PostgeSQL" to "postgresql". As I remember now sometimes git will leave a file or two behind in the old case directory. Then you will commit a new version to the new case.
Thus git doesn't know which one to rely on. So to resolve it, I had to go onto the github's website. Then you're able to view both cases. And you must delete all the files in the incorrect cased directory. Be sure that you have the correct version saved off or in the correct cased directory.
Once you have deleted all the files in the old case directory, that whole directory will disappear. Then do a commit.
At this point you should be able to do a Pull on your local computer and not see the conflicts any more. Thus being able to commit again. :)
You need to output ANSI colour codes. Note that not all terminals support this; if colour sequences are not supported, garbage will show up.
Example:
cout << "\033[1;31mbold red text\033[0m\n";
Here, \033
is the ESC character, ASCII 27. It is followed by [
, then zero or more numbers separated by ;
, and finally the letter m
. The numbers describe the colour and format to switch to from that point onwards.
The codes for foreground and background colours are:
foreground background
black 30 40
red 31 41
green 32 42
yellow 33 43
blue 34 44
magenta 35 45
cyan 36 46
white 37 47
Additionally, you can use these:
reset 0 (everything back to normal)
bold/bright 1 (often a brighter shade of the same colour)
underline 4
inverse 7 (swap foreground and background colours)
bold/bright off 21
underline off 24
inverse off 27
See the table on Wikipedia for other, less widely supported codes.
To determine whether your terminal supports colour sequences, read the value of the TERM
environment variable. It should specify the particular terminal type used (e.g. vt100
, gnome-terminal
, xterm
, screen
, ...). Then look that up in the terminfo database; check the colors
capability.
Run ps aux | grep nodejs
, find the PID of the process you're looking for, then run kill
starting with SIGTERM (kill -15 25239
). If that doesn't work then use SIGKILL instead, replacing -15
with -9
.
For Red Hat :
sudo yum install libstdc++.i686
sudo yum install libstdc++-devel.i686
#include <string>
using std::string;
void myReplace(string& str,
const string& oldStr,
const string& newStr) {
if (oldStr.empty()) {
return;
}
for (size_t pos = 0; (pos = str.find(oldStr, pos)) != string::npos;) {
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
The check for oldStr being empty is important. If for whatever reason that parameter is empty you will get stuck in an infinite loop.
But yeah use the tried and tested C++11 or Boost solution if you can.
If statement for images in jquery:
#html
<button id="chain">Chain</button>
<img src="bulb_on.jpg" alt="img" id="img"/>
#script
<script>
$(document).ready(function(){
$("#chain").click(function(){
if($("#img").attr('src')!='bulb_on.jpg'){
$("#img").attr('src', 'bulb_on.jpg');
}
else
{
$("#img").attr('src', 'bulb_onn.jpg');
}
});
});
</script>
Basic:
string[] myString = new string[]{"string1", "string2"};
or
string[] myString = new string[4];
myString[0] = "string1"; // etc.
Advanced: From a List
list<string> = new list<string>();
//... read this in from somewhere
string[] myString = list.ToArray();
From StringCollection
StringCollection sc = new StringCollection();
/// read in from file or something
string[] myString = sc.ToArray();
I manage to solve this in excel 97-2003, in a file with .xls extension this way: I went to the page where I had the linked data, with the cursor over the imported data table, go to tab Design --> External Data Table --> Unlink Unlink all tables (conections), delete all conections in Data --> Conections --> Conections save your work and done! regards, Dan
Change the REGEXP
to Like
SELECT * FROM table_name WHERE column_name like '%[^a-zA-Z0-9]%'
this one works fine
http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx
Remember that using uninitialized variables in C# is not allowed.
With
bool foo = new bool();
foo will have the default value.
Boolean default is false
import groovyx.net.http.HTTPBuilder;
public class HttpclassgetrRoles {
static void main(String[] args){
def baseUrl = new URL('http://test.city.com/api/Cirtxyz/GetUser')
HttpURLConnection connection = (HttpURLConnection) baseUrl.openConnection();
connection.addRequestProperty("Accept", "application/json")
connection.with {
doOutput = true
requestMethod = 'GET'
println content.text
}
}
}
Using the Thread.sleep(millis)
method.
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
I have created an Object.filter()
which does not only filter by a function, but also accepts an array of keys to include. The optional third parameter will allow you to invert the filter.
var foo = {
x: 1,
y: 0,
z: -1,
a: 'Hello',
b: 'World'
}
Object.filter(foo, ['z', 'a', 'b'], true);
Object.filter(foo, function (key, value) {
return Ext.isString(value);
});
Disclaimer: I chose to use Ext JS core for brevity. Did not feel it was necessary to write type checkers for object types as it was not part of the question.
// Helper function_x000D_
function print(obj) {_x000D_
document.getElementById('disp').innerHTML += JSON.stringify(obj, undefined, ' ') + '<br />';_x000D_
console.log(obj);_x000D_
}_x000D_
_x000D_
Object.filter = function (obj, ignore, invert) {_x000D_
let result = {}; // Returns a filtered copy of the original list_x000D_
if (ignore === undefined) {_x000D_
return obj; _x000D_
}_x000D_
invert = invert || false;_x000D_
let not = function(condition, yes) { return yes ? !condition : condition; };_x000D_
let isArray = Ext.isArray(ignore);_x000D_
for (var key in obj) {_x000D_
if (obj.hasOwnProperty(key) &&_x000D_
!(isArray && not(!Ext.Array.contains(ignore, key), invert)) &&_x000D_
!(!isArray && not(!ignore.call(undefined, key, obj[key]), invert))) {_x000D_
result[key] = obj[key];_x000D_
}_x000D_
}_x000D_
return result;_x000D_
};_x000D_
_x000D_
let foo = {_x000D_
x: 1,_x000D_
y: 0,_x000D_
z: -1,_x000D_
a: 'Hello',_x000D_
b: 'World'_x000D_
};_x000D_
_x000D_
print(Object.filter(foo, ['z', 'a', 'b'], true));_x000D_
print(Object.filter(foo, (key, value) => Ext.isString(value)));
_x000D_
#disp {_x000D_
white-space: pre;_x000D_
font-family: monospace_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/extjs/4.2.1/builds/ext-core.min.js"></script>_x000D_
<div id="disp"></div>
_x000D_
If you want your CSS to be copied into the output without being processed, you can use the (inline)
directive. e.g.,
@import (inline) '../timepicker/jquery.ui.timepicker.css';
Actually Java does support associative arrays they are called dictionaries!
If you don't have formatting or formulas you want to keep, you can try saving your file as a tab delimited text file, closing it, and reopening it with excel. This worked for me.
Try this:
using System.Data.Linq;
var result = from i in list
where i.age > 45
select i;
Using lambda expression please use this Statement:
var result = list.where(i => i.age > 45);
There are two different types of quotation marks in MySQL. You need to use ` for column names and ' for strings. Since you have used ' for the filename column the query parser got confused. Either remove the quotation marks around all column names, or change 'filename' to `filename`. Then it should work.
The default answer is to remove the item from whatever collection you're using as the GridView's DataSource.
If that option is undesirable then I recommend that you use the GridView's RowDataBound
event to selectively set the row's (e.Row
) Visible
property to false.
To answer your question, no. That would be possible with div though. THe only question is would cause a hazzle if the functionality were done with div rather than tables.
In the repository directory you remove the directory named .git and that's all :). On Un*x it is hidden, so you might not see it from file browser, but
cd repository-path/
rm -r .git
should do the trick.
You shouldn't create jquery objects for each cell and row. Try this:
function responseHandler(response)
{
var c = [];
$.each(response, function(i, item) {
c.push("<tr><td>" + item.rank + "</td>");
c.push("<td>" + item.content + "</td>");
c.push("<td>" + item.UID + "</td></tr>");
});
$('#records_table').html(c.join(""));
}
Observe object and array reactivity here:
First consider if you really need to iterate over rows in a DataFrame. See this answer for alternatives.
If you still need to iterate over rows, you can use methods below. Note some important caveats which are not mentioned in any of the other answers.
for index, row in df.iterrows():
print(row["c1"], row["c2"])
for row in df.itertuples(index=True, name='Pandas'):
print(row.c1, row.c2)
itertuples()
is supposed to be faster than iterrows()
But be aware, according to the docs (pandas 0.24.2 at the moment):
iterrows: dtype
might not match from row to row
Because iterrows returns a Series for each row, it does not preserve dtypes across the rows (dtypes are preserved across columns for DataFrames). To preserve dtypes while iterating over the rows, it is better to use itertuples() which returns namedtuples of the values and which is generally much faster than iterrows()
iterrows: Do not modify rows
You should never modify something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it will have no effect.
Use DataFrame.apply() instead:
new_df = df.apply(lambda x: x * 2)
itertuples:
The column names will be renamed to positional names if they are invalid Python identifiers, repeated, or start with an underscore. With a large number of columns (>255), regular tuples are returned.
See pandas docs on iteration for more details.
What is the difference between Git and GitHub?
Git is a distributed version control system. It usually runs at the command line of your local machine. It keeps track of your files and modifications to those files in a "repository" (or "repo"), but only when you tell it to do so. (In other words, you decide which files to track and when to take a "snapshot" of any modifications.)
In contrast, GitHub is a website that allows you to publish your Git repositories online, which can be useful for many reasons (see #3).
Is Git saving every repository locally (in the user's machine) and in GitHub?
Git is known as a "distributed" (rather than "centralized") version control system because you can run it locally and disconnected from the Internet, and then "push" your changes to a remote system (such as GitHub) whenever you like. Thus, repo changes only appear on GitHub when you manually tell Git to push those changes.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
Yes, you can use Git without GitHub. Git is the "workhorse" program that actually tracks your changes, whereas GitHub is simply hosting your repositories (and provides additional functionality not available in Git). Here are some of the benefits of using GitHub:
How does Git compare to a backup system such as Time Machine?
Git does backup your files, though it gives you much more granular control than a traditional backup system over what and when you backup. Specifically, you "commit" every time you want to take a snapshot of changes, and that commit includes both a description of your changes and the line-by-line details of those changes. This is optimal for source code because you can easily see the change history for any given file at a line-by-line level.
Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?
Yes, this is a manual process.
If are not collaborating and you are already using a backup system why would you use Git?
For getting started with Git, I recommend the online book Pro Git as well as GitRef as a handy reference guide. For getting started with GitHub, I like the GitHub's Bootcamp and their GitHub Guides. Finally, I created a short videos series to introduce Git and GitHub to beginners.
This is what the code would look like in a batch file(tested, works):
powershell -Command "& {set-location 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'; set-location ZoneMap\Domains; new-item SERVERNAME; set-location SERVERNAME; new-itemproperty . -Name http -Value 2 -Type DWORD;}"
Based on the information from:
http://dmitrysotnikov.wordpress.com/2008/06/27/powershell-script-in-a-bat-file/
Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class Demo {
public static final String PRIVATE_KEY="/home/user/private.der";
public static final String PUBLIC_KEY="/home/user/public.der";
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
//get the private key
File file = new File(PRIVATE_KEY);
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) file.length()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
System.out.println("Exponent :" + privKey.getPrivateExponent());
System.out.println("Modulus" + privKey.getModulus());
//get the public key
File file1 = new File(PUBLIC_KEY);
FileInputStream fis1 = new FileInputStream(file1);
DataInputStream dis1 = new DataInputStream(fis1);
byte[] keyBytes1 = new byte[(int) file1.length()];
dis1.readFully(keyBytes1);
dis1.close();
X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
KeyFactory kf1 = KeyFactory.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);
System.out.println("Exponent :" + pubKey.getPublicExponent());
System.out.println("Modulus" + pubKey.getModulus());
}
}
You can use as many colors and images as you desire.
Please note that the priority with which the background images are rendered is FILO, the first specified image is on the top layer, the last specified image is on the bottom layer (see the snippet).
#composition {_x000D_
width: 400px;_x000D_
height: 200px;_x000D_
background-image:_x000D_
linear-gradient(to right, #FF0000, #FF0000), /* gradient 1 as solid color */_x000D_
linear-gradient(to right, #00FF00, #00FF00), /* gradient 2 as solid color */_x000D_
linear-gradient(to right, #0000FF, #0000FF), /* gradient 3 as solid color */_x000D_
url('http://lorempixel.com/400/200/'); /* image */_x000D_
background-repeat: no-repeat; /* same as no-repeat, no-repeat, no-repeat */_x000D_
background-position:_x000D_
0 0, /* gradient 1 */_x000D_
20px 0, /* gradient 2 */_x000D_
40px 0, /* gradient 3 */_x000D_
0 0; /* image position */_x000D_
background-size:_x000D_
30px 30px,_x000D_
30px 30px,_x000D_
30px 30px,_x000D_
100% 100%;_x000D_
}
_x000D_
<div id="composition">_x000D_
</div>
_x000D_
<script>
var x = 2; //X is global and value is 2.
function myFunction()
{
x = 7; //x is local variable and value is 7.
}
myFunction();
alert(x); //x is gobal variable and the value is 7
</script>
Here is the complete procedure for IDEA IntelliJ 2019.3:
File > Project Structure
Under Project Settings > Modules
Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.
Apply changes.
Be aware of windows vista/windows 7 security rights - if you are running Visual Studio as administrator, you will not be able to drag files from a non-administrator explorer window into your program when you run it from within visual studio. The drag related events will not even fire! I hope this helps somebody else out there not waste hours of their life...
You can add a span to your html and css .
Here's an example from my code ...
HTML ( JSX ):
<input type="radio" name="AMPM" id="radiostyle1" value="AM" checked={this.state.AMPM==="AM"} onChange={this.handleChange}/>
<label for="radiostyle1"><span></span> am </label>
<input type="radio" name="AMPM" id="radiostyle2" value="PM" checked={this.state.AMPM==="PM"} onChange={this.handleChange}/>
<label for="radiostyle2"><span></span> pm </label>
CSS to make standard radio button vanish on screen and superimpose custom button image:
input[type="radio"] {
opacity:0;
}
input[type="radio"] + label {
font-size:1em;
text-transform: uppercase;
color: white ;
cursor: pointer;
margin:auto 15px auto auto;
}
input[type="radio"] + label span {
display:inline-block;
width:30px;
height:10px;
margin:1px 0px 0 -30px;
cursor:pointer;
border-radius: 20%;
}
input[type="radio"] + label span {
background-color: #FFFFFF
}
input[type="radio"]:checked + label span{
background-color: #660006;
}
There is a fairly simple answer with powershell.
Import-PfxCertificate -Password $secure_pw -CertStoreLocation Cert:\LocalMachine\Root -FilePath certs.pfx
The trick is making a "secure" password...
$plaintext_pw = 'PASSWORD';
$secure_pw = ConvertTo-SecureString $plaintext_pw -AsPlainText -Force;
Import-PfxCertificate -Password $secure_pw -CertStoreLocation Cert:\LocalMachine\Root -FilePath certs.pfx;
Actually I think OZ_ may be somewhat correct.
If you have the route '/users/:userId'
and navigate to '/users/'
(note the trailing /), $routeParams
in your controller should be an object containing userId: ""
in 1.1.5. So no the paramater userId
isn't completely ignored, but I think it's the best you're going to get.
You won't be able to make an ajax call to http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
from a file deployed at http://run.jsbin.com
due to the same-origin policy.
As the source (aka origin) page and the target URL are at different domains (run.jsbin.com
and www.ecb.europa.eu
), your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary GET
.
In a few words, the same-origin policy says that browsers should only allow ajax calls to services at the same domain of the HTML page.
A page at http://www.example.com/myPage.html
can only directly request services that are at http://www.example.com
, like http://www.example.com/api/myService
. If the service is hosted at another domain (say http://www.ok.com/api/myService
), the browser won't make the call directly (as you'd expect). Instead, it will try to make a CORS request.
To put it shortly, to perform a (CORS) request* across different domains, your browser:
Origin
header in the original request (with the page's domain as value) and perform it as usual; and thenAccess-Control-Allow-Origin
is one of them) allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).
* The above depicts the steps in a simple request, such as a regular GET
with no fancy headers. If the request is not simple (like a POST
with application/json
as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS
request to the target URL. Like above, it only will continue if the response to this OPTIONS
request contains the CORS headers. This OPTIONS
call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers
header.
Was it just a typo? Sometimes the JavaScript code has just a typo in the target domain. Have you checked? If the page is at www.example.com
it will only make regular calls to www.example.com
! Other URLs, such as api.example.com
or even example.com
or www.example.com:8080
are considered different domains by the browser! Yes, if the port is different, then it is a different domain!
Add the headers. The simplest way to enable CORS is by adding the necessary headers (as Access-Control-Allow-Origin
) to the server's responses. (Each server/language has a way to do that - check some solutions here.)
Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.
In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):
select myintfield + 0.0 as myfloatfield from mytable
While @Heximal's answer works, I don't personally recommend it.
This is because it uses implicit casting. Although you didn't type CAST
, either the SUM()
or the 0.0
need to be cast to be the same data-types, before the +
can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +
. But SUM(aFloatField) + 0
does not yield an INT, because the 0
is being implicitly cast to a FLOAT.
I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.
If you want to be explicit, I would use the following.
CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT requires 8.0
You can try the following to see what happens...
CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))
For those of you who still don't understand after reading @meda answer, here is my concise and complete explanation for this issue:
Let's say you have 2 Fragments, Fragment_A
and Fragment_B
which are auto-generated from the app. On the bottom part of your generated fragments, you're going to find this code:
public class Fragment_A extends Fragment {
//rest of the code is omitted
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
public class Fragment_B extends Fragment {
//rest of the code is omitted
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
To overcome the issue, you have to add onFragmentInteraction
method into your activity, which in my case is named MainActivity2
. After that, you need to implements
all fragments in the MainActivity
like this:
public class MainActivity2 extends ActionBarActivity
implements Fragment_A.OnFragmentInteractionListener,
Fragment_B.OnFragmentInteractionListener,
NavigationDrawerFragment.NavigationDrawerCallbacks {
//rest code is omitted
@Override
public void onFragmentInteraction(Uri uri){
//you can leave it empty
}
}
P.S.: In short, this method could be used for communicating between fragments. For those of you who want to know more about this method, please refer to this link.
function routeToRoom(userId, passw, cb) {
var roomId = 0;
var nStore = require('nstore/lib/nstore').extend(require('nstore/lib/nstore/query')());
var users = nStore.new('data/users.db', function() {
users.find({
user: userId,
pass: passw
}, function(err, results) {
if (err) {
roomId = -1;
} else {
roomId = results.creationix.room;
}
cb(roomId);
});
});
}
routeToRoom("alex", "123", function(id) {
console.log(id);
});
You need to use callbacks. That's how asynchronous IO works. Btw sys.puts
is deprecated
The steps in order to make a full check are:
Prepare the captor :
ArgumentCaptor<SomeArgumentClass> someArgumentCaptor = ArgumentCaptor.forClass(SomeArgumentClass.class);
verify the call to dependent on component (collaborator of subject under test). times(1) is the default value, so ne need to add it.
verify(dependentOnComponent, times(1)).send(someArgumentCaptor.capture());
Get the argument passed to collaborator
SomeArgumentClass someArgument = messageCaptor.getValue();
someArgument can be used for assertions
This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.
typedef void (*functiontype)();
Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:
void dosomething() { }
functiontype func = &dosomething;
func();
For a function that returns an int and takes a char you would do
typedef int (*functiontype2)(char);
and to use it
int dosomethingwithchar(char a) { return 1; }
functiontype2 func2 = &dosomethingwithchar
int result = func2('a');
There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!
boost::function<int (char a)> functiontype2;
is so much nicer than the above.
If the POM missing warning is of project's self module, the reason is that you are trying to mistakenly build from a sub-module directory. You need to run the build and install command from root directory of the project.
There is no way.
This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.
If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern
attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.
For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}">
could be adequate. It is of course implementation-dependent how it will be handled.
You want this - enter N and then take N number of elements.I am considering your input case is just like this
5
2 3 6 6 5
have this in this way in python 3.x (for python 2.x use raw_input()
instead if input()
)
n = int(input())
arr = input() # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])
n = int(raw_input())
arr = raw_input() # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])
I started hacking away a bit on Yar's script and the result is on github, including man pages and install script:
https://github.com/najamelan/git-backup
Installation:
git clone "https://github.com/najamelan/git-backup.git"
cd git-backup
sudo ./install.sh
Welcoming all suggestions and pull request on github.
#!/usr/bin/env ruby
#
# For documentation please sea man git-backup(1)
#
# TODO:
# - make it a class rather than a function
# - check the standard format of git warnings to be conform
# - do better checking for git repo than calling git status
# - if multiple entries found in config file, specify which file
# - make it work with submodules
# - propose to make backup directory if it does not exists
# - depth feature in git config (eg. only keep 3 backups for a repo - like rotate...)
# - TESTING
# allow calling from other scripts
def git_backup
# constants:
git_dir_name = '.git' # just to avoid magic "strings"
filename_suffix = ".git.bundle" # will be added to the filename of the created backup
# Test if we are inside a git repo
`git status 2>&1`
if $?.exitstatus != 0
puts 'fatal: Not a git repository: .git or at least cannot get zero exit status from "git status"'
exit 2
else # git status success
until File::directory?( Dir.pwd + '/' + git_dir_name ) \
or File::directory?( Dir.pwd ) == '/'
Dir.chdir( '..' )
end
unless File::directory?( Dir.pwd + '/.git' )
raise( 'fatal: Directory still not a git repo: ' + Dir.pwd )
end
end
# git-config --get of version 1.7.10 does:
#
# if the key does not exist git config exits with 1
# if the key exists twice in the same file with 2
# if the key exists exactly once with 0
#
# if the key does not exist , an empty string is send to stdin
# if the key exists multiple times, the last value is send to stdin
# if exaclty one key is found once, it's value is send to stdin
#
# get the setting for the backup directory
# ----------------------------------------
directory = `git config --get backup.directory`
# git config adds a newline, so remove it
directory.chomp!
# check exit status of git config
case $?.exitstatus
when 1 : directory = Dir.pwd[ /(.+)\/[^\/]+/, 1]
puts 'Warning: Could not find backup.directory in your git config file. Please set it. See "man git config" for more details on git configuration files. Defaulting to the same directroy your git repo is in: ' + directory
when 2 : puts 'Warning: Multiple entries of backup.directory found in your git config file. Will use the last one: ' + directory
else unless $?.exitstatus == 0 then raise( 'fatal: unknown exit status from git-config: ' + $?.exitstatus ) end
end
# verify directory exists
unless File::directory?( directory )
raise( 'fatal: backup directory does not exists: ' + directory )
end
# The date and time prefix
# ------------------------
prefix = ''
prefix_date = Time.now.strftime( '%F' ) + ' - ' # %F = YYYY-MM-DD
prefix_time = Time.now.strftime( '%H:%M:%S' ) + ' - '
add_date_default = true
add_time_default = false
prefix += prefix_date if git_config_bool( 'backup.prefix-date', add_date_default )
prefix += prefix_time if git_config_bool( 'backup.prefix-time', add_time_default )
# default bundle name is the name of the repo
bundle_name = Dir.pwd.split('/').last
# set the name of the file to the first command line argument if given
bundle_name = ARGV[0] if( ARGV[0] )
bundle_name = File::join( directory, prefix + bundle_name + filename_suffix )
puts "Backing up to bundle #{bundle_name.inspect}"
# git bundle will print it's own error messages if it fails
`git bundle create #{bundle_name.inspect} --all --remotes`
end # def git_backup
# helper function to call git config to retrieve a boolean setting
def git_config_bool( option, default_value )
# get the setting for the prefix-time from git config
config_value = `git config --get #{option.inspect}`
# check exit status of git config
case $?.exitstatus
# when not set take default
when 1 : return default_value
when 0 : return true unless config_value =~ /(false|no|0)/i
when 2 : puts 'Warning: Multiple entries of #{option.inspect} found in your git config file. Will use the last one: ' + config_value
return true unless config_value =~ /(false|no|0)/i
else raise( 'fatal: unknown exit status from git-config: ' + $?.exitstatus )
end
end
# function needs to be called if we are not included in another script
git_backup if __FILE__ == $0
Step 1
My computer > properties > Advance system settings
Step 2
environment variables > click New button under user variables > Enter variable name as 'PATH'
Copy the location of java bin (e.g:C:\Program Files\Java\jdk1.8.0_121\bin)
and paste it in Variable value and click OK Now open the eclipse.
If you code on Laravel just use Illuminate\Support\Str
here is example
Str::words($category->publication->title, env('WORDS_COUNT_HOME'), '...')
Hope this was helpful.
Not sure if I understand your question, but max(id) won't give you the number of lines at all. For example if you have only one line with id = 13 (let's say you deleted the previous lines), you'll have max(id) = 13 but the number of rows is 1. The correct (and fastest) solution is to use count(). BTW if you wonder why there's a star, it's because you can count lines based on a criteria.
I find it easy to make an image of a line, and then insert it into the code as a "rule", setting the width and/or height as needed. These have all been horizontal-rule images, but there's nothing stopping me (or you) from using a "vertical-rule" image.
This is cool for many reasons; you can use different lines, colors, or patterns easily as "rules", and since they would have no text, even if you had done it the "normal" way using hr in HTML, it shouldn't impact SEO or other stuff like that. And the image file would/should be very tiny (1 or 2KB at most).
On Angular to update a component including its template, there is a straight forward solution to this, having an @Input
property on your ChildComponent and add to your @Component
decorator changeDetection: ChangeDetectionStrategy.OnPush
as follows:
import { ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'master',
templateUrl: templateUrl,
styleUrls:[styleUrl1],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent{
@Input() data: MyData;
}
This will do all the work of check if Input data have changed and re-render the component
This is correct formula to find integers from i
to j
where i <= R <= j
FLOOR(min+RAND()*(max-min))
The following are the major differences between procedure and function,
Make a backup!
Then you need to set the default char sets on the database. This does not convert existing tables, it only sets the default for newly created tables.
ALTER DATABASE dbname CHARACTER SET utf8 COLLATE utf8_general_ci;
Then, you will need to convert the char set on all existing tables and their columns. This assumes that your current data is actually in the current char set. If your columns are set to one char set but your data is really stored in another then you will need to check the MySQL manual on how to handle this.
ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
just scale your output from your first function
0) you have a number in range 1-5
1) subtract 1 to make it in range 0-4
2) multiply by (7-1)/(5-1) to make it in range 0-6
3) add 1 to increment the range: Now your result is in between 1-7
You can use the drop_duplicates
method to get the unique rows in a DataFrame:
In [29]: df = pd.DataFrame({'a':[1,2,1,2], 'b':[3,4,3,5]})
In [30]: df
Out[30]:
a b
0 1 3
1 2 4
2 1 3
3 2 5
In [32]: df.drop_duplicates()
Out[32]:
a b
0 1 3
1 2 4
3 2 5
You can also provide the subset
keyword argument if you only want to use certain columns to determine uniqueness. See the docstring.
Modify your CSS like this:
.vertical_banner {_x000D_
border: 1px solid #E9E3DD;_x000D_
float: left;_x000D_
height: 210px;_x000D_
margin: 2px;_x000D_
padding: 4px 2px 10px 10px;_x000D_
text-align: left;_x000D_
width: 117px;_x000D_
position:relative;_x000D_
}_x000D_
_x000D_
#bottom_link{_x000D_
position:absolute; /* added */_x000D_
bottom:0; /* added */_x000D_
left:0; /* added */_x000D_
}
_x000D_
<div class="vertical_banner">_x000D_
<div id="bottom_link">_x000D_
<input type="submit" value="Continue">_x000D_
</div>_x000D_
</div>
_x000D_
Have a look at the AlertDialog docs. As it states, to add a custom view to your alert dialog you need to find the frameLayout and add your view to that like so:
FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom);
fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));
Most likely you are going to want to create a layout xml file for your view, and inflate it:
LayoutInflater inflater = getLayoutInflater();
View twoEdits = inflater.inflate(R.layout.my_layout, f1, false);
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
1. Can not instantiate abstract class: Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract.
Example below :
abstract class AbstractClass
{
abstract protected function getValue();
abstract protected function prefixValue($prefix);
public function printOut() {
echo "Hello how are you?";
}
}
$obj=new AbstractClass();
$obj->printOut();
//Fatal error: Cannot instantiate abstract class AbstractClass
2. Any class that contains at least one abstract method must also be abstract: Abstract class can have abstract and non-abstract methods, but it must contain at least one abstract method. If a class has at least one abstract method, then the class must be declared abstract.
Note: Traits support the use of abstract methods in order to impose requirements upon the exhibiting class.
Example below :
class Non_Abstract_Class
{
abstract protected function getValue();
public function printOut() {
echo "Hello how are you?";
}
}
$obj=new Non_Abstract_Class();
$obj->printOut();
//Fatal error: Class Non_Abstract_Class contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Non_Abstract_Class::getValue)
3. An abstract method can not contain body: Methods defined as abstract simply declare the method's signature - they cannot define the implementation. But a non-abstract method can define the implementation.
abstract class AbstractClass
{
abstract protected function getValue(){
return "Hello how are you?";
}
public function printOut() {
echo $this->getValue() . "\n";
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";
//Fatal error: Abstract function AbstractClass::getValue() cannot contain body
4. When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child :If you inherit an abstract class you have to provide implementations to all the abstract methods in it.
abstract class AbstractClass
{
// Force Extending class to define this method
abstract protected function getValue();
// Common method
public function printOut() {
print $this->getValue() . "<br/>";
}
}
class ConcreteClass1 extends AbstractClass
{
public function printOut() {
echo "dhairya";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
//Fatal error: Class ConcreteClass1 contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (AbstractClass::getValue)
5. Same (or a less restricted) visibility:When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.
Note that abstract method should not be private.
abstract class AbstractClass
{
abstract public function getValue();
abstract protected function prefixValue($prefix);
public function printOut() {
print $this->getValue();
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."<br/>";
//Fatal error: Access level to ConcreteClass1::getValue() must be public (as in class AbstractClass)
6. Signatures of the abstract methods must match:When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child;the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. For example, if the child class defines an optional argument, where the abstract method's signature does not, there is no conflict in the signature.
abstract class AbstractClass
{
abstract protected function prefixName($name);
}
class ConcreteClass extends AbstractClass
{
public function prefixName($name, $separator = ".") {
if ($name == "Pacman") {
$prefix = "Mr";
} elseif ($name == "Pacwoman") {
$prefix = "Mrs";
} else {
$prefix = "";
}
return "{$prefix}{$separator} {$name}";
}
}
$class = new ConcreteClass;
echo $class->prefixName("Pacman"), "<br/>";
echo $class->prefixName("Pacwoman"), "<br/>";
//output: Mr. Pacman
// Mrs. Pacwoman
7. Abstract class doesn't support multiple inheritance:Abstract class can extends another abstract class,Abstract class can provide the implementation of interface.But it doesn't support multiple inheritance.
interface MyInterface{
public function foo();
public function bar();
}
abstract class MyAbstract1{
abstract public function baz();
}
abstract class MyAbstract2 extends MyAbstract1 implements MyInterface{
public function foo(){ echo "foo"; }
public function bar(){ echo "bar"; }
public function baz(){ echo "baz"; }
}
class MyClass extends MyAbstract2{
}
$obj=new MyClass;
$obj->foo();
$obj->bar();
$obj->baz();
//output: foobarbaz
Note: Please note order or positioning of the classes in your code can affect the interpreter and can cause a Fatal error. So, when using multiple levels of abstraction, be careful of the positioning of the classes within the source code.
below example will cause Fatal error: Class 'horse' not found
class cart extends horse {
public function get_breed() { return "Wood"; }
}
abstract class horse extends animal {
public function get_breed() { return "Jersey"; }
}
abstract class animal {
public abstract function get_breed();
}
$cart = new cart();
print($cart->get_breed());
You also can try out this
final WebView webView = new WebView(this);
webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);
What version of WPF are you using? I tried in both 3.5 and 4.0, and Fill="#FF000000" should work fine in a in the XAML. There is another syntax, however, if it doesn't. Here's a 3.5 XAML that I tested with two different ways. Better yet would be to use a resource.
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Rectangle Height="100" HorizontalAlignment="Left" Margin="100,12,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="200" Fill="#FF00AE00" />
<Rectangle Height="100" HorizontalAlignment="Left" Margin="100,132,0,0" Name="rectangle2" Stroke="Black" VerticalAlignment="Top" Width="200" >
<Rectangle.Fill>
<SolidColorBrush Color="#FF00AE00" />
</Rectangle.Fill>
</Rectangle>
</Grid>
The easiest solution I found is to just rename the php folder version as such:
That way only two of them will be read by MAMP. Done!
From ?read.table
: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.
So, perhaps your data file isn't clean. Being more specific will help the data import:
d = read.table("foobar.txt",
sep="\t",
col.names=c("id", "name"),
fill=FALSE,
strip.white=TRUE)
will specify exact columns and fill=FALSE
will force a two column data frame.
Try this;
function X (id,parameter1,parameter2,...) {
$.ajax({
url: '@Url.Action("Actionre", "controller")',+ id,
type: "Get",
data: { parameter1: parameter1, parameter2: parameter2,...}
}).done(function(result) {
your code...
});
}
So controller method would looks like :
public ActionResult ActionName(id,parameter1, parameter2,...)
{
Your Code .......
}
select T.TABLE_NAME, T.TABLESPACE_NAME, t.avg_row_len*t.num_rows from dba_tables t
order by T.TABLE_NAME asc
See e.g. http://www.dba-oracle.com/t_script_oracle_table_size.htm for more options
By the Spring guys, used for Grails reloading but works with Java too:
You could serialize the image into a Data URI. There's a tutorial in this blog post. That will produce a string you can store in local storage. Then on the next page, use the data uri as the source of the image.
This works for me:
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
cout << M_PI << endl;
return 0;
}
Compiles and prints pi
like is should: cl /O2 main.cpp /link /out:test.exe
.
There must be a mismatch in the code you have posted and the one you're trying to compile.
Be sure there are no precompiled headers being pulled in before your #define
.
Things you can add to declarations: [] in modules
Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.
A really easy way to do this is to add a UNIQUE
index on the 3 columns. When you write the ALTER
statement, include the IGNORE
keyword. Like so:
ALTER IGNORE TABLE jobs
ADD UNIQUE INDEX idx_name (site_id, title, company);
This will drop all the duplicate rows. As an added benefit, future INSERTs
that are duplicates will error out. As always, you may want to take a backup before running something like this...
I think you can get it using subc1.text
.
>>> html = """
<p>
<strong class="offender">YOB:</strong> 1987<br />
<strong class="offender">RACE:</strong> WHITE<br />
<strong class="offender">GENDER:</strong> FEMALE<br />
<strong class="offender">HEIGHT:</strong> 5'05''<br />
<strong class="offender">WEIGHT:</strong> 118<br />
<strong class="offender">EYE COLOR:</strong> GREEN<br />
<strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
"""
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> print soup.text
YOB: 1987
RACE: WHITE
GENDER: FEMALE
HEIGHT: 5'05''
WEIGHT: 118
EYE COLOR: GREEN
HAIR COLOR: BROWN
Or if you want to explore it, you can use .contents
:
>>> p = soup.find('p')
>>> from pprint import pprint
>>> pprint(p.contents)
[u'\n',
<strong class="offender">YOB:</strong>,
u' 1987',
<br/>,
u'\n',
<strong class="offender">RACE:</strong>,
u' WHITE',
<br/>,
u'\n',
<strong class="offender">GENDER:</strong>,
u' FEMALE',
<br/>,
u'\n',
<strong class="offender">HEIGHT:</strong>,
u" 5'05''",
<br/>,
u'\n',
<strong class="offender">WEIGHT:</strong>,
u' 118',
<br/>,
u'\n',
<strong class="offender">EYE COLOR:</strong>,
u' GREEN',
<br/>,
u'\n',
<strong class="offender">HAIR COLOR:</strong>,
u' BROWN',
<br/>,
u'\n']
and filter out the necessary items from the list:
>>> data = dict(zip([x.text for x in p.contents[1::4]], [x.strip() for x in p.contents[2::4]]))
>>> pprint(data)
{u'EYE COLOR:': u'GREEN',
u'GENDER:': u'FEMALE',
u'HAIR COLOR:': u'BROWN',
u'HEIGHT:': u"5'05''",
u'RACE:': u'WHITE',
u'WEIGHT:': u'118',
u'YOB:': u'1987'}
Starting Mongo 4.2
, db.collection.update()
can accept an aggregation pipeline, which allows using aggregation operators such as $addFields
, which outputs all existing fields from the input documents and newly added fields:
var new_info = { param2: "val2_new", param3: "val3_new" }
// { some_key: { param1: "val1", param2: "val2", param3: "val3" } }
// { some_key: { param1: "val1", param2: "val2" } }
db.collection.update({}, [{ $addFields: { some_key: new_info } }], { multi: true })
// { some_key: { param1: "val1", param2: "val2_new", param3: "val3_new" } }
// { some_key: { param1: "val1", param2: "val2_new", param3: "val3_new" } }
The first part {}
is the match query, filtering which documents to update (in this case all documents).
The second part [{ $addFields: { some_key: new_info } }]
is the update aggregation pipeline:
$addFields
.$addFields
performs exactly what you need: updating the object so that the new object will overlay / merge with the existing one:{ param2: "val2_new", param3: "val3_new" }
will be merged into the existing some_key
by keeping param1
untouched and either add or replace both param2
and param3
.Don't forget { multi: true }
, otherwise only the first matching document will be updated.
FileZilla Works well. I Use FileZilla FTP Client "Manual Transfer" which supports Passive mode.
Example: Open FileZilla and Select "Transfer" >> "Manual Transfer" then within the Manual Transfer Window, perform the following:
Insert "checkbox". Every time you check or uncheck the box the sheet recalculates. If you put the text size for the checkbox at 2, the color at almost black and the cell shade to black, it becomes a button that recalculates.
Another but much more elegant solution for this is as follows:
/**
* Convert number secs to display time
*
* 65 input becomes 01:05.
*
* @param Number inputSeconds Seconds input.
*/
export const toMMSS = inputSeconds => {
const secs = parseInt( inputSeconds, 10 );
let minutes = Math.floor( secs / 60 );
let seconds = secs - minutes * 60;
if ( 10 > minutes ) {
minutes = '0' + minutes;
}
if ( 10 > seconds ) {
seconds = '0' + seconds;
}
// Return display.
return minutes + ':' + seconds;
};
Following are the differences/advantages:
Constraint Layout has dual power of both Relative Layout as well as Linear layout: Set relative positions of views ( like Relative layout ) and also set weights for dynamic UI (which was only possible in Linear Layout).
A very powerful use is grouping of elements by forming a chain. This way we can form a group of views which as a whole can be placed in a desired way without adding another layer of hierarchy just to form another group of views.
In addition to weights, we can apply horizontal and vertical bias which is nothing but the percentage of displacement from the centre. ( bias of 0.5 means centrally aligned. Any value less or more means corresponding movement in the respective direction ) .
Another very important feature is that it respects and provides the functionality to handle the GONE views so that layouts do not break if some view is set to GONE through java code. More can be found here: https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html#VisibilityBehavior
Provides power of automatic constraint applying by the use of Blue print and Visual Editor tool which makes it easy to design a page.
All these features lead to flattening of the view hierarchy which improves performance and also helps in making responsive and dynamic UI which can more easily adapt to different screen size and density.
Here is the best place to learn quickly: https://codelabs.developers.google.com/codelabs/constraint-layout/#0
The simples way is to use 'to' property:
<Link to="chart" target="_blank" to="http://link2external.page.com" >Test</Link>
I have created a static method for setting part of text Bold for TextView and EditText
public static void boldPartOfText(View mView, String contentData, int startIndex, int endIndex){
if(!contentData.isEmpty() && contentData.length() > endIndex) {
final SpannableStringBuilder sb = new SpannableStringBuilder(contentData);
final StyleSpan bss = new StyleSpan(Typeface.BOLD); // Span to make text bold
final StyleSpan iss = new StyleSpan(Typeface.NORMAL); //Span to make text normal
sb.setSpan(iss, 0, startIndex, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
sb.setSpan(bss, startIndex, endIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
sb.setSpan(iss,endIndex, contentData.length()-1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
if(mView instanceof TextView)
((TextView) mView).setText(sb);
else if(mView instanceof EditText)
((EditText) mView).setText(sb);
}
}
Another more customized code
/*typeFaceStyle can be passed as
Typeface.NORMAL = 0;
Typeface.BOLD = 1;
Typeface.ITALIC = 2;
Typeface.BOLD_ITALIC = 3;*/
public static void boldPartOfText(View mView, String contentData, int startIndex, int endIndex,int typeFaceStyle){
if(!contentData.isEmpty() && contentData.length() > endIndex) {
final SpannableStringBuilder sb = new SpannableStringBuilder(contentData);
final StyleSpan bss = new StyleSpan(typeFaceStyle); // Span to make text bold
final StyleSpan iss = new StyleSpan(Typeface.NORMAL); //Span to make text italic
sb.setSpan(iss, 0, startIndex, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
sb.setSpan(bss, startIndex, endIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
sb.setSpan(iss,endIndex,contentData.length()-1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
if(mView instanceof TextView)
((TextView) mView).setText(sb);
else if(mView instanceof EditText)
((EditText) mView).setText(sb);
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.your_external_website.com");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
is best for http url, But how to open https url help me
Convert everything to everything (bool,string,enum,etc):
public class EverythingConverterValue
{
public object ConditionValue { get; set; }
public object ResultValue { get; set; }
}
public class EverythingConverterList : List<EverythingConverterValue>
{
}
public class EverythingConverter : IValueConverter
{
public EverythingConverterList Conditions { get; set; } = new EverythingConverterList();
public object NullResultValue { get; set; }
public object NullBackValue { get; set; }
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return Conditions.Where(x => x.ConditionValue.Equals(value)).Select(x => x.ResultValue).FirstOrDefault() ?? NullResultValue;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return Conditions.Where(x => x.ResultValue.Equals(value)).Select(x => x.ConditionValue).FirstOrDefault() ?? NullBackValue;
}
}
XAML Examples:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:conv="clr-namespace:MvvmGo.Converters;assembly=MvvmGo.WindowsWPF"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<conv:EverythingConverter x:Key="BooleanToVisibilityConverter">
<conv:EverythingConverter.Conditions>
<conv:EverythingConverterValue ResultValue="{x:Static Visibility.Visible}">
<conv:EverythingConverterValue.ConditionValue>
<sys:Boolean>True</sys:Boolean>
</conv:EverythingConverterValue.ConditionValue>
</conv:EverythingConverterValue>
<conv:EverythingConverterValue ResultValue="{x:Static Visibility.Collapsed}">
<conv:EverythingConverterValue.ConditionValue>
<sys:Boolean>False</sys:Boolean>
</conv:EverythingConverterValue.ConditionValue>
</conv:EverythingConverterValue>
</conv:EverythingConverter.Conditions>
</conv:EverythingConverter>
<conv:EverythingConverter x:Key="InvertBooleanToVisibilityConverter">
<conv:EverythingConverter.Conditions>
<conv:EverythingConverterValue ResultValue="{x:Static Visibility.Visible}">
<conv:EverythingConverterValue.ConditionValue>
<sys:Boolean>False</sys:Boolean>
</conv:EverythingConverterValue.ConditionValue>
</conv:EverythingConverterValue>
<conv:EverythingConverterValue ResultValue="{x:Static Visibility.Collapsed}">
<conv:EverythingConverterValue.ConditionValue>
<sys:Boolean>True</sys:Boolean>
</conv:EverythingConverterValue.ConditionValue>
</conv:EverythingConverterValue>
</conv:EverythingConverter.Conditions>
</conv:EverythingConverter>
<conv:EverythingConverter x:Key="MarriedConverter" NullResultValue="Single">
<conv:EverythingConverter.Conditions>
<conv:EverythingConverterValue ResultValue="Married">
<conv:EverythingConverterValue.ConditionValue>
<sys:Boolean>True</sys:Boolean>
</conv:EverythingConverterValue.ConditionValue>
</conv:EverythingConverterValue>
<conv:EverythingConverterValue ResultValue="Single">
<conv:EverythingConverterValue.ConditionValue>
<sys:Boolean>False</sys:Boolean>
</conv:EverythingConverterValue.ConditionValue>
</conv:EverythingConverterValue>
</conv:EverythingConverter.Conditions>
<conv:EverythingConverter.NullBackValue>
<sys:Boolean>False</sys:Boolean>
</conv:EverythingConverter.NullBackValue>
</conv:EverythingConverter>
In my case the same error happen because I was trying to use mysql by just typing "mysql" instead of "mysql -u root -p"
Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS
// Example using HTTP POST operation
var page = require('webpage').create(),
server = 'http://posttestserver.com/post.php?dump',
data = 'universe=expanding&answer=42';
page.open(server, 'post', data, function (status) {
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log(page.content);
}
phantom.exit();
});
ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).
In a comment you said
"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"
Well, your code does this:
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?
ORA-06510: PL/SQL: unhandled user-defined exception
If so, all you need to do is add an exception block to handle the error. Perhaps:
PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
vSOME_EX EXCEPTION;
BEGIN
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
ELSE
EXECUTE IMMEDIATE 'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
END IF;
exception
when vsome_ex then
raise_application_error(-20000
, 'This is not a valid table: M'||pNum||'GR');
END PX;
The documentation covers handling PL/SQL exceptions in depth.
2 ways:-
1st one Custom Query
@Modifying
@Query("delete from User where firstName = :firstName")
void deleteUsersByFirstName(@Param("firstName") String firstName);
2nd one JPA Query by method
List<User> deleteByLastname(String lastname);
When you go with query by method (2nd way) it will first do a get call
select * from user where last_name = :firstName
Then it will load it in a List Then it will call delete id one by one
delete from user where id = 18
delete from user where id = 19
First fetch list of object, then for loop to delete id one by one
But, the 1st option (custom query),
It's just a single query It will delete wherever the value exists.
Go through this link too https://www.baeldung.com/spring-data-jpa-deleteby
Here is regex free version:
function indexes(source, find) {
if (!source) {
return [];
}
// if find is empty string return all indexes.
if (!find) {
// or shorter arrow function:
// return source.split('').map((_,i) => i);
return source.split('').map(function(_, i) { return i; });
}
var result = [];
for (i = 0; i < source.length; ++i) {
// If you want to search case insensitive use
// if (source.substring(i, i + find.length).toLowerCase() == find) {
if (source.substring(i, i + find.length) == find) {
result.push(i);
}
}
return result;
}
indexes("I learned to play the Ukulele in Lebanon.", "le")
EDIT: and if you want to match strings like 'aaaa' and 'aa' to find [0, 2] use this version:
function indexes(source, find) {
if (!source) {
return [];
}
if (!find) {
return source.split('').map(function(_, i) { return i; });
}
var result = [];
var i = 0;
while(i < source.length) {
if (source.substring(i, i + find.length) == find) {
result.push(i);
i += find.length;
} else {
i++;
}
}
return result;
}
const args = process.argv;
console.log(args);
This returns:
$ node server.js one two=three four
['node', '/home/server.js', 'one', 'two=three', 'four']
Minimist: For minimal argument parsing.
Commander.js: Most adopted module for argument parsing.
Meow: Lighter alternative to Commander.js
Yargs: More sophisticated argument parsing (heavy).
Vorpal.js: Mature / interactive command-line applications with argument parsing.
Here are a couple of things to check:
For console.Write/WriteLine
, your app must be a console application. (right-click the project in Solution Explorer, choose Properties, and look at the "Output Type" combo in the Application Tab -- should be "Console Application" (note, if you really need a windows application or a class library, don't change this to Console App just to get the Console.WriteLine
).
You could use System.Diagnostics.Debug.WriteLine
to write to the output window (to show the output window in VS, got to View | Output) Note that these writes will only occur in a build where the DEBUG conditional is defined (by default, debug builds define this, and release builds do not)
You could use System.Diagnostics.Trace.Writeline
if you want to be able to write to configurable "listeners" in non-debug builds. (by default, this writes to the Output Window in Visual Studio, just like Debug.Writeline
)
If you want to inspect html, css or maybe you need js console in your mobile browser . You can use excelent tool eruda Using it you have the same Developer Tools on your mobile browser like in your desctop device. Dont forget to upvote :) Here is a link https://github.com/liriliri/eruda
It sounds like you're doing property checking on an object! If you want to check a property exists (but can be values such as null or 0 in addition to truthy values), the in operator can make for some nice syntax.
var foo = { bar: 1234, baz: null };
console.log("bar in foo:", "bar" in foo); // true
console.log("baz in foo:", "baz" in foo); // true
console.log("otherProp in foo:", "otherProp" in foo) // false
console.log("__proto__ in foo:", "__proto__" in foo) // true
As you can see, the __proto__ property is going to be thrown here. This is true for all inherited properties. For further reading, I'd recommend the MDN page:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
Use this class to set divider in your RecyclerView
.
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
I wrote a fuller description on 365git.
The use of the imperative, present tense is one that takes a little getting used to. When I started mentioning it, it was met with resistance. Usually along the lines of “The commit message records what I have done”. But, Git is a distributed version control system where there are potentially many places to get changes from. Rather than writing messages that say what you’ve done; consider these messages as the instructions for what applying the commit will do. Rather than having a commit with the title:
Renamed the iVars and removed the common prefix.
Have one like this:
Rename the iVars to remove the common prefix
Which tells someone what applying the commit will do, rather than what you did. Also, if you look at your repository history you will see that the Git generated messages are written in this tense as well - “Merge” not “Merged”, “Rebase” not “Rebased” so writing in the same tense keeps things consistent. It feels strange at first but it does make sense (testimonials available upon application) and eventually becomes natural.
Having said all that - it’s your code, your repository: so set up your own guidelines and stick to them.
If, however, you do decide to go this way then
git rebase -i
with the reword option would be a good thing to look into.
You may try;
$('#save_value').click(function(){
var final = '';
$('.ads_Checkbox:checked').each(function(){
var values = $(this).val();
final += values;
});
alert(final);
});
This will return all checkbox values in a single instance.
Here is a working Live Demo.
You can use ${!a}
:
var1="this is the real value"
a="var1"
echo "${!a}" # outputs 'this is the real value'
This is an example of indirect parameter expansion:
The basic form of parameter expansion is
${parameter}
. The value ofparameter
is substituted.If the first character of
parameter
is an exclamation point (!), it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest ofparameter
as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value ofparameter
itself.
Works and is simpler than every other solution I see here :
Pump().getPumps()
This is great if you don't need to reuse a class instance. Tested on Python 3.7.3.
If you are trying to loop over a NodeList
like this:
const allParagraphs = document.querySelectorAll("p");
I highly recommend loop it this way:
Array.prototype.forEach.call(allParagraphs , function(el) {
// Write your code here
})
Personally, I've tried several ways but most of them didn't work as I wanted to loop over a NodeList
, but this one works like a charm, give it a try!
The NodeList
isn't an Array, but we treat it as an Array, using Array.
So, you need to know that it is not supported in older browsers!
Need more information about NodeList
? Please read its documentation on MDN.
If you want to load the partial view directly inside the main view you could use the Html.Action
helper:
@Html.Action("Load", "Home")
or if you don't want to go through the Load action use the HtmlPartialAsync helper:
@await Html.PartialAsync("_LoadView")
If you want to use Ajax.ActionLink
, replace your Html.ActionLink
with:
@Ajax.ActionLink(
"load partial view",
"Load",
"Home",
new AjaxOptions { UpdateTargetId = "result" }
)
and of course you need to include a holder in your page where the partial will be displayed:
<div id="result"></div>
Also don't forget to include:
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
in your main view in order to enable Ajax.*
helpers. And make sure that unobtrusive javascript is enabled in your web.config (it should be by default):
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
I found the nice resource Standard C++ Containers. Probably this is what you all looking for.
VECTOR
Constructors
vector<T> v; Make an empty vector. O(1)
vector<T> v(n); Make a vector with N elements. O(n)
vector<T> v(n, value); Make a vector with N elements, initialized to value. O(n)
vector<T> v(begin, end); Make a vector and copy the elements from begin to end. O(n)
Accessors
v[i] Return (or set) the I'th element. O(1)
v.at(i) Return (or set) the I'th element, with bounds checking. O(1)
v.size() Return current number of elements. O(1)
v.empty() Return true if vector is empty. O(1)
v.begin() Return random access iterator to start. O(1)
v.end() Return random access iterator to end. O(1)
v.front() Return the first element. O(1)
v.back() Return the last element. O(1)
v.capacity() Return maximum number of elements. O(1)
Modifiers
v.push_back(value) Add value to end. O(1) (amortized)
v.insert(iterator, value) Insert value at the position indexed by iterator. O(n)
v.pop_back() Remove value from end. O(1)
v.assign(begin, end) Clear the container and copy in the elements from begin to end. O(n)
v.erase(iterator) Erase value indexed by iterator. O(n)
v.erase(begin, end) Erase the elements from begin to end. O(n)
For other containers, refer to the page.
The following code is Linux (maybe Unix) only, but it works in a real project.
private double getAverageValueByLinux() throws InterruptedException {
try {
long delay = 50;
List<Double> listValues = new ArrayList<Double>();
for (int i = 0; i < 100; i++) {
long cput1 = getCpuT();
Thread.sleep(delay);
long cput2 = getCpuT();
double cpuproc = (1000d * (cput2 - cput1)) / (double) delay;
listValues.add(cpuproc);
}
listValues.remove(0);
listValues.remove(listValues.size() - 1);
double sum = 0.0;
for (Double double1 : listValues) {
sum += double1;
}
return sum / listValues.size();
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
private long getCpuT throws FileNotFoundException, IOException {
BufferedReader reader = new BufferedReader(new FileReader("/proc/stat"));
String line = reader.readLine();
Pattern pattern = Pattern.compile("\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)")
Matcher m = pattern.matcher(line);
long cpuUser = 0;
long cpuSystem = 0;
if (m.find()) {
cpuUser = Long.parseLong(m.group(1));
cpuSystem = Long.parseLong(m.group(3));
}
return cpuUser + cpuSystem;
}
Manually creating a folder named 'npm' in the displayed path fixed the problem.
More information can be found on Troubleshooting page
I know the topic is old, but you can declare the Ajax as a variable, then use a function to call the variable on the desired content. Keep in mind you are calling what you have in the Ajax if you want a different elements from the Ajax you need to specify it.
Example:
Var infogen = $.ajax({'your query')};
$("#refresh").click(function(){
infogen;
console.log("to verify");
});
Hope helps
if not try:
$("#refresh").click(function(){
loca.tion.reload();
console.log("to verify");
});
No there isn't and it's probably not there, because there are very few valid uses for it. I would think twice before using it. Also, it is indeed easy to create yourself.
Please refer to this discussion about why it's even in .NET.
I guess UnsupportedOperationException
comes close, although it doesn't say the operation is just not implemented, but unsupported even. That could imply no valid implementation is possible. Why would the operation be unsupported? Should it even be there?
Interface segregation or Liskov substitution issues maybe?
If it's work in progress I'd go for ToBeImplementedException
, but I've never caught myself defining a concrete method and then leave it for so long it makes it into production and there would be a need for such an exception.
You can do it with using a FileOutputStream
and the writeTo
method.
ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
byteArrayOutputStream.writeTo(outputStream);
}
Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions
Intent service is child of Service
IntentService: If you want to download a bunch of images at the start of opening your app. It's a one-time process and can clean itself up once everything is downloaded.
Service: A Service which will constantly be used to communicate between your app and back-end with web API calls. Even if it is finished with its current task, you still want it to be around a few minutes later, for more communication
<EditText
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="DD/MM/YYYY"
android:inputType="date"
android:focusable="false"/>
<EditText
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="00:00"
android:inputType="time"
android:focusable="false"/>
JAVA FILE
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText selectDate,selectTime;
private int mYear, mMonth, mDay, mHour, mMinute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectDate=(EditText)findViewById(R.id.date);
selectTime=(EditText)findViewById(R.id.time);
selectDate.setOnClickListener(this);
selectTime.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view == selectDate) {
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
selectDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
if (view == selectTime) {
// Get Current Time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
selectTime.setText(hourOfDay + ":" + minute);
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
}
}
Short answer: When I send files between devices with OBEX I am almost never prompted to pair, so it is certainly possible.
1) An application and the device itself can each be set to need/not-need authentication modes, so often there was no requirement for pairing. For instance most OBEX (OPP) servers don't need any authentication at all so there is not need for pairing/bonding.
Presumably "Wireless Designs"'s answer was covering that case.
2) Then if pairing was required by the device/app:
2.1) Prior to v2.1 for pairing then the two devices needed to have matching passphrase/PINs. So this either needed user involvement (to enter the PINs) or knowledge in the softwareto know the PIN: either defined in the app if pin callback send pin="1234"
, or smarts in the OS like BlueZ and Win7 (see Slide 20 at my Bluetooth in Windows 7 doc) which has logic like: if(remotedevice=headset) then expectedPin ="0000"
. Don't know what Android does
2.2) In v2.1 Secure Simple Pairing (SSP) was added. Which changes pairing to:
if (either is pre-v2.1) then Legacy else if (Out-Of-Band channel) then OutOfBand else if (neither have "Man-in-the-Middle Protection Required") then (i.e. both have "Man-in-the-Middle Protection _Not_ Required") Just-Works else Depending on the two devices' "IO Capabilities", either NumericComparison or Passkey. Passkey is used when one device has KeyboardOnly -- and the peer device _isn't_ NoInputNoOutput. endif
From 32feet.NET's BluetoothWin32Authentication user guide, see also the SSP sections in [1]
So to have pairing be unprompted needs either "JustWorks" or "Out-of-Band" eg your NFC suggestion.
Hope that helps...
Got the same question from a friend. My suggestion which does not require !Important
looks like this: I add a custom class "no-border
" which can be added to the bootstrap table.
.table.no-border tr td, .table.no-border tr th {
border-width: 0;
}
You can see my go at a solution here
Here's an answer covering the more general question of calling another PS script from a PS script, as you may do if you were composing your scripts of many little, narrow-purpose scripts.
I found it was simply a case of using dot-sourcing. That is, you just do:
# This is Script-A.ps1
. ./Script-B.ps1 -SomeObject $variableFromScriptA -SomeOtherParam 1234;
I found all the Q/A very confusing and complicated and eventually landed upon the simple method above, which is really just like calling another script as if it was a function in the original script, which I seem to find more intuitive.
Dot-sourcing can "import" the other script in its entirety, using:
. ./Script-B.ps1
It's now as if the two files are merged.
Ultimately, what I was really missing is the notion that I should be building a module of reusable functions.
You have prevent the default action of the event and return false
from the function.
function onTestClick(e) {
e.preventDefault();
return false;
}
In the context of Drupal, the difference will depend whether clean URLs are on or not.
With them off, $_SERVER['REQUEST_URI']
will have the full path of the page as called w/ /index.php
, while $_GET["q"]
will just have what is assigned to q
.
With them on, they will be nearly identical w/o other arguments, but $_GET["q"]
will be missing the leading /
. Take a look towards the end of the default .htaccess to see what is going on. They will also differ if additional arguments are passed into the page, eg when a pager is active.
You can squash (join) commits with an Interactive Rebase. There is a pretty nice YouTube video which shows how to do this on the command line or with SmartGit:
If you are already a SmartGit user then you can select all your outgoing commits (by holding down the Ctrl key) and open the context menu (right click) to squash your commits.
It's very comfortable:
There is also a very nice tutorial from Atlassian which shows how it works:
Given that most recommended error mode for PDO is ERRMODE_EXCEPTION
, no direct execute()
result verification will ever work. As the code execution won't even reach the condition offered in other answers.
So, there are three possible scenarios to handle the query execution result in PDO:
try..catch
operator.For a regular PHP user it sounds a bit alien - how's that, not to verify the direct result of the operation? - but this is exactly how exceptions work - you check the error somewhere else. Once for all. Extremely convenient.
So, in a nutshell: in a regular code you don't need any error handling at all. Just keep your code as is:
$stmt->bindParam(':field1', $field1, PDO::PARAM_STR);
$stmt->bindParam(':field2', $field2, PDO::PARAM_STR);
$stmt->execute();
echo "Success!"; // whatever
On success it will tell you so, on error it will show you the regular error page that your application is showing for such an occasion.
Only in case you have a handling scenario other than just reporting the error, put your insert statement in a try..catch
operator, check whether it was the error you expected and handle it; or - if the error was any different - re-throw the exception, to make it possible to be handled by the site-wide error handler usual way. Below is the example code from my article on error handling with PDO:
try {
$pdo->prepare("INSERT INTO users VALUES (NULL,?,?,?,?)")->execute($data);
} catch (PDOException $e) {
if ($e->getCode() == 1062) {
// Take some action if there is a key constraint violation, i.e. duplicate name
} else {
throw $e;
}
}
echo "Success!";
In the code above we are checking for the particular error to take some action and re-throwing the exception for the any other error (no such table for example) which will be reported to a programmer.
While again - just to tell a user something like "Your insert was successful" no condition is ever needed.
This is the most common technique I've seen:
function getUserIP() {
if( array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',')>0) {
$addr = explode(",",$_SERVER['HTTP_X_FORWARDED_FOR']);
return trim($addr[0]);
} else {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
}
}
else {
return $_SERVER['REMOTE_ADDR'];
}
}
Note that it does not guarantee it you will get always the correct user IP because there are many ways to hide it.
I get the same error in Cygwin. I had to install the openssh package in Cygwin Setup.
(The strange thing was that all ssh-*
commands were valid, (bash could execute as program) but the openssh package wasn't installed.)
If you are using React Router, use this:
<Link to="/files/myfile.pdf" target="_blank" download>Download</Link>
Where /files/myfile.pdf
is inside your public
folder.
Another common solution is adding "Other.." option to the drop down and when selected show text box that is otherwise hidden. Then when submitting the form, assign hidden field value with either the drop down or textbox value and in the server side code check the hidden value.
Example: http://jsfiddle.net/c258Q/
HTML code:
Please select: <form onsubmit="FormSubmit(this);">
<input type="hidden" name="fruit" />
<select name="fruit_ddl" onchange="DropDownChanged(this);">
<option value="apple">Apple</option>
<option value="orange">Apricot </option>
<option value="melon">Peach</option>
<option value="">Other..</option>
</select> <input type="text" name="fruit_txt" style="display: none;" />
<button type="submit">Submit</button>
</form>
JavaScript:
function DropDownChanged(oDDL) {
var oTextbox = oDDL.form.elements["fruit_txt"];
if (oTextbox) {
oTextbox.style.display = (oDDL.value == "") ? "" : "none";
if (oDDL.value == "")
oTextbox.focus();
}
}
function FormSubmit(oForm) {
var oHidden = oForm.elements["fruit"];
var oDDL = oForm.elements["fruit_ddl"];
var oTextbox = oForm.elements["fruit_txt"];
if (oHidden && oDDL && oTextbox)
oHidden.value = (oDDL.value == "") ? oTextbox.value : oDDL.value;
}
And in the server side, read the value of "fruit" from the Request.
You might want to look into the DirectoryInfo
.Parent
property.
This depends. If you are concerned that your variable could end up as something that resolves to TRUE. Then hard checking is a must. Otherwise it is up to you. However, I doubt that the syntax whatever == TRUE
would ever confuse anyone who knew what they were doing.
In Ubuntu In the conf file: /etc/apache2/sites-enabled/your-file.conf
change
AddHandler application/x-httpd-php .js .xml .htc .css
to:
AddHandler application/x-httpd-php .js .xml .htc
To facilitate potentially solving your problem given the information you've provided, I'm going to assume you're seeking dynamic CSS. If this is the case, you can use a server-side scripting language to do so. For example (and I absolutely love doing things like this):
styles.css.php:
body
{
margin: 0px;
font-family: Verdana;
background-color: #cccccc;
background-image: url('<?php
echo 'images/flag_bg/' . $user_country . '.png';
?>');
}
This would set the background image to whatever was stored in the $user_country variable. This is only one example of dynamic CSS; there are virtually limitless possibilities when combining CSS and server-side code. Another case would be doing something like allowing the user to create a custom theme, storing it in a database, and then using PHP to set various properties, like so:
user_theme.css.php:
body
{
background-color: <?php echo $user_theme['BG_COLOR']; ?>;
color: <?php echo $user_theme['COLOR']; ?>;
font-family: <?php echo $user_theme['FONT']; ?>;
}
#panel
{
font-size: <?php echo $user_theme['FONT_SIZE']; ?>;
background-image: <?php echo $user_theme['PANEL_BG']; ?>;
}
Once again, though, this is merely an off-the-top-of-the-head example; harnessing the power of dynamic CSS via server-side scripting can lead to some pretty incredible stuff.
To use the IntelliJ Java decompiler from the command line for a jar package follow the instructions provided here: https://github.com/JetBrains/intellij-community/tree/master/plugins/java-decompiler/engine
Since your content must be dynamic you can set the css properties of the modal dynamically on show
event of the modal which will re-size the modal overriding its default specs. Reason being bootstrap applies a max-height to the modal body with the css rule as below:
.modal-body {
position: relative;
overflow-y: auto;
max-height: 400px;
padding: 15px;
}
So you can add inline styles dynamically using jquery css
method:
For newer versions of bootstrap use show.bs.modal
$('#modal').on('show.bs.modal', function () {
$(this).find('.modal-body').css({
width:'auto', //probably not needed
height:'auto', //probably not needed
'max-height':'100%'
});
});
For older versions of bootstrap use show
$('#modal').on('show', function () {
$(this).find('.modal-body').css({
width:'auto', //probably not needed
height:'auto', //probably not needed
'max-height':'100%'
});
});
or use a css rule to override:
.autoModal.modal .modal-body{
max-height: 100%;
}
and add this class autoModal
to your target modals.
Change the content dynamically in the fiddle, you will see the modal getting resized accordingly. Demo
Newer version of bootstrap see the available event names
.
Older version of bootstrap modal events supported.
All of the following examples use
var str = "Hello, playground"
startIndex
and endIndex
startIndex
is the index of the first characterendIndex
is the index after the last character.Example
// character
str[str.startIndex] // H
str[str.endIndex] // error: after last character
// range
let range = str.startIndex..<str.endIndex
str[range] // "Hello, playground"
With Swift 4's one-sided ranges, the range can be simplified to one of the following forms.
let range = str.startIndex...
let range = ..<str.endIndex
I will use the full form in the follow examples for the sake of clarity, but for the sake of readability, you will probably want to use the one-sided ranges in your code.
after
As in: index(after: String.Index)
after
refers to the index of the character directly after the given index.Examples
// character
let index = str.index(after: str.startIndex)
str[index] // "e"
// range
let range = str.index(after: str.startIndex)..<str.endIndex
str[range] // "ello, playground"
before
As in: index(before: String.Index)
before
refers to the index of the character directly before the given index.Examples
// character
let index = str.index(before: str.endIndex)
str[index] // d
// range
let range = str.startIndex..<str.index(before: str.endIndex)
str[range] // Hello, playgroun
offsetBy
As in: index(String.Index, offsetBy: String.IndexDistance)
offsetBy
value can be positive or negative and starts from the given index. Although it is of the type String.IndexDistance
, you can give it an Int
.Examples
// character
let index = str.index(str.startIndex, offsetBy: 7)
str[index] // p
// range
let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end
str[range] // play
limitedBy
As in: index(String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index)
limitedBy
is useful for making sure that the offset does not cause the index to go out of bounds. It is a bounding index. Since it is possible for the offset to exceed the limit, this method returns an Optional. It returns nil
if the index is out of bounds.Example
// character
if let index = str.index(str.startIndex, offsetBy: 7, limitedBy: str.endIndex) {
str[index] // p
}
If the offset had been 77
instead of 7
, then the if
statement would have been skipped.
It would be much easier to use an Int
index for Strings. The reason that you have to create a new String.Index
for every String is that Characters in Swift are not all the same length under the hood. A single Swift Character might be composed of one, two, or even more Unicode code points. Thus each unique String must calculate the indexes of its Characters.
It is possibly to hide this complexity behind an Int index extension, but I am reluctant to do so. It is good to be reminded of what is actually happening.
You can format them as table !!
form {_x000D_
display: table;_x000D_
}_x000D_
label {_x000D_
display: table-row;_x000D_
}_x000D_
input {_x000D_
display: table-cell;_x000D_
}_x000D_
p1 {_x000D_
display: table-cell;_x000D_
}
_x000D_
<div id="header_order_form" align="center">_x000D_
<form id="order_header" method="post">_x000D_
<label>_x000D_
<p1>order_no:_x000D_
<input type="text">_x000D_
</p1>_x000D_
<p1>order_type:_x000D_
<input type="text">_x000D_
</p1>_x000D_
</label>_x000D_
</br>_x000D_
</br>_x000D_
<label>_x000D_
<p1>_x000D_
creation_date:_x000D_
<input type="text">_x000D_
</p1>_x000D_
<p1>delivery_date:_x000D_
<input type="text">_x000D_
</p1>_x000D_
<p1>billing_date:_x000D_
<input type="text">_x000D_
</p1>_x000D_
</label>_x000D_
</br>_x000D_
</br>_x000D_
_x000D_
<label>_x000D_
<p1>sold_to_party:_x000D_
<input type="text">_x000D_
</p1>_x000D_
<p1>sop_address:_x000D_
<input type="text">_x000D_
</p1>_x000D_
</label>_x000D_
</form>_x000D_
</div>
_x000D_
Your html is completely wrong for starters, there should not be a div within your head section, nor after your body section. I suggest you look into correct html first before starting to work with favicons etc.
Anacoda3-4.2.0 Uses python 3.5 You can find the same in the link given below : https://repo.continuum.io/archive/Anaconda3-4.2.0-Windows-x86_64.exe
I faced the same problem and found the correct version by checking the available Anaconda 4.2.0 distributions in installer archive here
from app import SQLAlchemyDB as db
Chance.query.filter(Chance.repo_id==repo_id,
Chance.status=="1",
db.func.date(Chance.apply_time)<=end,
db.func.date(Chance.apply_time)>=start).count()
it is equal to:
select
count(id)
from
Chance
where
repo_id=:repo_id
and status='1'
and date(apple_time) <= end
and date(apple_time) >= start
wish can help you.
You just need to set background and give previous.xml file in background of button in your layout file.
<Button
android:id="@+id/button1"
android:background="@drawable/previous"
android:layout_width="200dp"
android:layout_height="126dp"
android:text="Hello" />
and done.Edit Following is previous.xml file in drawable directory
<?xml version="1.0" encoding="utf-8"?>
<item android:drawable="@drawable/onclick" android:state_selected="true"></item>
<item android:drawable="@drawable/onclick" android:state_pressed="true"></item>
<item android:drawable="@drawable/normal"></item>
The string is basically bounded from the place where it is pointed to (char *ptrChar;
), to the null character (\0
).
The char *ptrChar;
actually points to the beginning of the string (char array), and thus that is the pointer to that string,
so when you do like ptrChar[x]
for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).
Below is just for reference of numeric unique random id...
it may help you...
$query=mysql_query("select * from collectors_repair");
$row=mysql_num_rows($query);
$ind=0;
if($row>0)
{
while($rowids=mysql_fetch_array($query))
{
$already_exists[$ind]=$rowids['collector_repair_reportid'];
}
}
else
{
$already_exists[0]="nothing";
}
$break='false';
while($break=='false'){
$rand=mt_rand(10000,999999);
if(array_search($rand,$alredy_exists)===false){
$break='stop';
}else{
}
}
echo "random number is : ".$echo;
and you can add char with the code like -> $rand=mt_rand(10000,999999) .$randomchar; // assume $radomchar contains char;
If you are happy to have a dependency upon the System.Web.Helpers
assembly, then you can use the Json
class:
dynamic data = Json.Decode(json);
It is included with the MVC framework as an additional download to the .NET 4 framework. Be sure to give Vlad an upvote if that's helpful! However if you cannot assume the client environment includes this DLL, then read on.
An alternative deserialisation approach is suggested here. I modified the code slightly to fix a bug and suit my coding style. All you need is this code and a reference to System.Web.Extensions
from your project:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
public sealed class DynamicJsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { typeof(object) })); }
}
#region Nested type: DynamicJsonObject
private sealed class DynamicJsonObject : DynamicObject
{
private readonly IDictionary<string, object> _dictionary;
public DynamicJsonObject(IDictionary<string, object> dictionary)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
_dictionary = dictionary;
}
public override string ToString()
{
var sb = new StringBuilder("{");
ToString(sb);
return sb.ToString();
}
private void ToString(StringBuilder sb)
{
var firstInDictionary = true;
foreach (var pair in _dictionary)
{
if (!firstInDictionary)
sb.Append(",");
firstInDictionary = false;
var value = pair.Value;
var name = pair.Key;
if (value is string)
{
sb.AppendFormat("{0}:\"{1}\"", name, value);
}
else if (value is IDictionary<string, object>)
{
new DynamicJsonObject((IDictionary<string, object>)value).ToString(sb);
}
else if (value is ArrayList)
{
sb.Append(name + ":[");
var firstInArray = true;
foreach (var arrayValue in (ArrayList)value)
{
if (!firstInArray)
sb.Append(",");
firstInArray = false;
if (arrayValue is IDictionary<string, object>)
new DynamicJsonObject((IDictionary<string, object>)arrayValue).ToString(sb);
else if (arrayValue is string)
sb.AppendFormat("\"{0}\"", arrayValue);
else
sb.AppendFormat("{0}", arrayValue);
}
sb.Append("]");
}
else
{
sb.AppendFormat("{0}:{1}", name, value);
}
}
sb.Append("}");
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (!_dictionary.TryGetValue(binder.Name, out result))
{
// return null to avoid exception. caller can check for null this way...
result = null;
return true;
}
result = WrapResultObject(result);
return true;
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
if (indexes.Length == 1 && indexes[0] != null)
{
if (!_dictionary.TryGetValue(indexes[0].ToString(), out result))
{
// return null to avoid exception. caller can check for null this way...
result = null;
return true;
}
result = WrapResultObject(result);
return true;
}
return base.TryGetIndex(binder, indexes, out result);
}
private static object WrapResultObject(object result)
{
var dictionary = result as IDictionary<string, object>;
if (dictionary != null)
return new DynamicJsonObject(dictionary);
var arrayList = result as ArrayList;
if (arrayList != null && arrayList.Count > 0)
{
return arrayList[0] is IDictionary<string, object>
? new List<object>(arrayList.Cast<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x)))
: new List<object>(arrayList.Cast<object>());
}
return result;
}
}
#endregion
}
You can use it like this:
string json = ...;
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
dynamic obj = serializer.Deserialize(json, typeof(object));
So, given a JSON string:
{
"Items":[
{ "Name":"Apple", "Price":12.3 },
{ "Name":"Grape", "Price":3.21 }
],
"Date":"21/11/2010"
}
The following code will work at runtime:
dynamic data = serializer.Deserialize(json, typeof(object));
data.Date; // "21/11/2010"
data.Items.Count; // 2
data.Items[0].Name; // "Apple"
data.Items[0].Price; // 12.3 (as a decimal)
data.Items[1].Name; // "Grape"
data.Items[1].Price; // 3.21 (as a decimal)
The reason why you're getting that error is because you've declared your struct
as:
struct {
char name[32];
int size;
int start;
int popularity;
} stasher_file;
This is not declaring a stasher_file
type. This is declaring an anonymous struct
type and is creating a global instance named stasher_file
.
What you intended was:
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
But note that while Brian R. Bondy's response wasn't correct about your error message, he's right that you're trying to write into the struct
without having allocated space for it. If you want an array of pointers to struct stasher_file
structures, you'll need to call malloc
to allocate space for each one:
struct stasher_file *newFile = malloc(sizeof *newFile);
if (newFile == NULL) {
/* Failure handling goes here. */
}
strncpy(newFile->name, name, 32);
newFile->size = size;
...
(BTW, be careful when using strncpy
; it's not guaranteed to NUL-terminate.)
In the $routeProvider URI patters, you can specify variable parameters, like so: $routeProvider.when('/page/:pageNumber' ...
, and access it in your controller via $routeParams.
There is a good example at the end of the $route page: http://docs.angularjs.org/api/ng.$route
EDIT (for the edited question):
The routing system is unfortunately very limited - there is a lot of discussion on this topic, and some solutions have been proposed, namely via creating multiple named views, etc.. But right now, the ngView directive serves only ONE view per route, on a one-to-one basis. You can go about this in multiple ways - the simpler one would be to use the view's template as a loader, with a <ng-include src="myTemplateUrl"></ng-include>
tag in it ($scope.myTemplateUrl would be created in the controller).
I use a more complex (but cleaner, for larger and more complicated problems) solution, basically skipping the $route service altogether, that is detailed here:
Click the "activity monitor" icon in the toolbar.
In SQL Server Management Studio, right click on Server, choose "Activity Monitor" from context menu -or- use keyboard shortcut Ctrl + Alt + A.
Reference: Microsoft Docs - Open Activity Monitor in SQL Server Management Studio (SSMS)
The syntax for an implicit pipe from a shell command into a bash variable is
var=$(command)
or
var=`command`
In your examples, you are piping data to an assignment statement, which does not expect any input.
It looks like the github.com
host which jenkins tries to connect to is not listed under the Jenkins user's $HOME/.ssh/known_hosts
. Jenkins runs on most distros as the user jenkins
and hence has its own .ssh
directory to store the list of public keys and known_hosts
.
The easiest solution I can think of to fix this problem is:
# Login as the jenkins user and specify shell explicity,
# since the default shell is /bin/false for most
# jenkins installations.
sudo su jenkins -s /bin/bash
cd SOME_TMP_DIR
# git clone YOUR_GITHUB_URL
# Allow adding the SSH host key to your known_hosts
# Exit from su
exit
Dynamically changing styles is not supported (yet). You have to set the style before the view gets created, via XML.
I don't understand, why you don't want to set the $HOME
environment variable since that solves exactly what you're asking for.
cd ~
doesn't mean change to the root directory, but change to the user's home directory, which is set by the $HOME
environment variable.
Edit C:\Program Files (x86)\Git\etc\profile
and set $HOME
variable to whatever you want (add it if it's not there). A good place could be for example right after a condition commented by # Set up USER's home directory
. It must be in the MinGW format, for example:
HOME=/c/my/custom/home
Save it, open Git Bash and execute cd ~
. You should be in a directory /c/my/custom/home
now.
Everything that accesses the user's profile should go into this directory instead of your Windows' profile on a network drive.
Note: C:\Program Files (x86)\Git\etc\profile
is shared by all users, so if the machine is used by multiple users, it's a good idea to set the $HOME
dynamically:
HOME=/c/Users/$USERNAME
Set the environment variable HOME
in Windows to whatever directory you want. In this case, you have to set it in Windows path format (with backslashes, e.g. c:\my\custom\home
), Git Bash will load it and convert it to its format.
If you want to change the home directory for all users on your machine, set it as a system environment variable, where you can use for example %USERNAME%
variable so every user will have his own home directory, for example:
HOME=c:\custom\home\%USERNAME%
If you want to change the home directory just for yourself, set it as a user environment variable, so other users won't be affected. In this case, you can simply hard-code the whole path:
HOME=c:\my\custom\home
load your url helper when you create a function eg,
visibility function_name () {
$this->load->helper('url');
}
the it will show you errors or a view you loaded.
Martin Joiner's problem is caused by a misunderstanding of the <caption>
tag.
The <caption>
tag defines a table caption.
The <caption>
tag must be the first child of the <table>
tag.
You can specify only one caption per table.
Also, note that the scope
attribute should be placed on a <th>
element and not on a <tr>
element.
The proper way to write a multi-header multi-tbody table would be something like this :
<table id="dinner_table">_x000D_
<caption>This is the only correct place to put a caption.</caption>_x000D_
<tbody>_x000D_
<tr class="header">_x000D_
<th colspan="2" scope="col">First Half of Table (British Dinner)</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">1</th>_x000D_
<td>Fish</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">2</th>_x000D_
<td>Chips</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">3</th>_x000D_
<td>Peas</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">4</th>_x000D_
<td>Gravy</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
<tbody>_x000D_
<tr class="header">_x000D_
<th colspan="2" scope="col">Second Half of Table (Italian Dinner)</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">5</th>_x000D_
<td>Pizza</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">6</th>_x000D_
<td>Salad</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">7</th>_x000D_
<td>Oil</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th scope="row">8</th>_x000D_
<td>Bread</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
We used DBVisualizer for that.
Description: The references graph is a great feature as it automatically renders all primary/foreign key mappings (also called referential integrity constraints) in a graph style. The table nodes and relations are layed out automatically, with a number of layout modes available. The resulting graph is unique as it displays all information in an optimal and readable layout. from its site
I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.
This question is old but here is another answer because it is useful fo others:
thread.sleep is not a good method for waiting, because usually it freezes the software until finishing its time, this function is better:
Imports VB = Microsoft.VisualBasic
Public Sub wait(ByVal seconds As Single)
Static start As Single
start = VB.Timer()
Do While VB.Timer() < start + seconds
System.Windows.Forms.Application.DoEvents()
Loop
End Sub
The above function waits for a specific time without freezing the software, however increases the CPU usage.
This function not only doesn't freeze the software, but also doesn't increase the CPU usage:
Private Sub wait(ByVal seconds As Integer)
For i As Integer = 0 To seconds * 100
System.Threading.Thread.Sleep(10)
Application.DoEvents()
Next
End Sub
First of all as the name suggests a view is immutable. thats because a view is nothing other than a virtual table created from a stored query in the DB. Because of this you have some characteristics of views:
so there are a gazillion of use cases for which views are better fitted than tables, just think about only displaying active users on a website. a view would be better because you operate only on a subset of the data which actually is in your DB (active and inactive users)
check out this article
hope this helped..
On Ubuntu system, I purged the PostgreSQL and re-installed it. All the databases are restored. This solved the problem for me.
Advice - Take the backup of the databases to be on the safer side.
My guess is that you are using MySQL where the +
operator does addition, along with silent conversion of the values to numbers. If a value does not start with a digit, then the converted value is 0
.
So try this:
select concat(column1, column2)
Two ways to add a space:
select concat(column1, ' ', column2)
select concat_ws(' ', column1, column2)
Although we might have different contexts, the below worked for me.
I wrapped every part of my variable in brackets and then added an exclamation mark outside the right closing bracket.
For example, print(documentData["mileage"])
is changed to:
print((documentData["mileage"])!)
like @nd says but using the built-in function of int to convert to a different base
>>> [ int(i,16) for i in '0123456789ABCDEF' ]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>> [int(i,2) for i in "100 010 110 111".split()]
[4, 2, 6, 7]
I don't know what is the final objective but take a look also inside the decimal module of python for doing stuff like
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
Just style the input to offset for the extra padding. In the following example the padding on the input would be 10px on the left and right for a total padding offset of 20px:
input[type=text]{
width: calc(100% - 20px);
}
You should be able to cite at least one from the JDK itself. Look in the java.util.collections
package. There are several abstract classes. You should fully understand interface, abstract, and concrete for Map
and why Joshua Bloch wrote it that way.
Try doing this :
recipients="[email protected],[email protected],[email protected]"
And another approach, using shell here-doc :
/usr/sbin/sendmail "$recipients" <<EOF
subject:$subject
from:$from
Example Message
EOF
Be sure to separate the headers from the body with a blank line as per RFC 822.
Going to answer this myself (correct me if I'm wrong):
It is not possible to iterate over a group of rows (like an array) in Excel without VBA installed / macros enabled.
The main question - end of line
$ goes to the end of line, remains in command mode
A goes to the end of line, switches to insert mode
Conversely - start of line (technically the first non-whitespace character)
^ goes to the start of line, remains in command mode
I (uppercase i) goes to the start of line, switches to insert mode
Further - start of line (technically the first column irrespective of whitespace)
0 (zero) goes to the start of line, remains in command mode
0i (zero followed by lowercase i) goes the start of line, switches to insert mode
For those starting to learn vi, here is a good introduction to vi by listing side by side vi commands to typical Windows GUI Editor cursor movement and shortcut keys.
Typescript will always complain when it is unable to find a symbol. The compiler comes together with a set of default definitions for window
, document
and such specified in a file called lib.d.ts
. If I do a grep for require
in this file I can find no definition of a function require
. Hence, we have to tell the compiler ourselves that this function will exist at runtime using the declare
syntax:
declare function require(name:string);
var sampleModule = require('modulename');
On my system, this compiles just fine.
Here's a variation of Oscar's first version that doesn't use a for-each loop.
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == 'q') {
// do something
break;
}
}
You could have a boolean variable that gets set to false before the loop, then make "do something" set the variable to true, which you could test for after the loop. The loop could also be wrapped in a function call then just use 'return true' instead of the break, and add a 'return false' statement after the for loop.
If I have one thing that I love to share with respect to CSS, it's MY FAVE WAY OF CENTERING THINGS ALONG BOTH AXES!!!
Advantages of this method:
I always do this by using 2 classes: One to specify the parent element, whose content will be centered (.centered-wrapper
), and the 2nd one to specify which child of the parent is centered (.centered-content
). This 2nd class is useful in the case where the parent has multiple children, but only 1 needs to be centered).
In this case, body
will be the .centered-wrapper
, and an inner div
will be .centered-content
.
<html>
<head>...</head>
<body class="centered-wrapper">
<div class="centered-content">...</div>
</body>
</html>
The idea for centering will now be to make .centered-content
an inline-block
. This will easily facilitate horizontal centering, through text-align: center;
, and also allows for vertical centering as you shall see.
.centered-wrapper {
position: relative;
text-align: center;
}
.centered-wrapper:before {
content: "";
position: relative;
display: inline-block;
width: 0; height: 100%;
vertical-align: middle;
}
.centered-content {
display: inline-block;
vertical-align: middle;
}
This gives you 2 really reusable classes for centering any child inside of any parent! Just add the .centered-wrapper
and .centered-content
classes.
So, what's up with that :before
element? It facilitates vertical-align: middle;
and is necessary because vertical alignment isn't relative to the height of the parent - vertical alignment is relative to the height of the tallest sibling!!!. Therefore, by ensuring that there is a sibling whose height is the parent's height (100% height, 0 width to make it invisible), we know that vertical alignment will be with respect to the parent's height.
One last thing: You need to ensure that your html
and body
tags are the size of the window so that centering to them is the same as centering to the browser!
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
Choose Database | Set Datasource Location... Select the database node (yellow-ish cylinder) of the current connection, then select the database node of the desired connection (you may need to authenticate), then click Update.
You will need to do this for the 'Subreports' nodes as well.
FYI, you can also do individual tables by selecting each individually, then choosing Update.
Use
git apply patchfile
if possible.
patch -p1 < patchfile
has potential side-effect.
git apply
also handles file adds, deletes, and renames if they're described in the git diff
format, which patch
won't do. Finally, git apply
is an "apply all or abort all" model where either everything is applied or nothing is, whereas patch can partially apply patch files, leaving your working directory in a weird state.
var str = "Hello, this is Mike (example)";
alert(str.replace(/\s*\(.*?\)\s*/g, ''));
That'll also replace excess whitespace before and after the parentheses.
Swift 3.0 code
self.timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector:#selector(fetchAutocompletePlaces(timer:)), userInfo:[textView.text], repeats: true)
func fetchAutocompletePlaces(timer : Timer) {
let keyword = timer.userInfo
}
You can send value in 'userinfo' and use that as parameter in the function.
you can use android:textColor= "
whatever text color u want to give" in xml file where your text view is declared.
Here's the solution I came up with:
select FIELD from TABLE where FIELD > LASTVAL order by FIELD fetch first N rows only;
By initializing LASTVAL to 0 (or '' for a text field), then setting it to the last value in the most recent set of records, this will step through the table in chunks of N records.
This is how I ended up taking care of this issue. Note that debug code is still in there for testing. This code is within the OnStartup in the App.xaml.cs file. (WPF)
// Process already running ?
if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
{
// Show your error message
MessageBox.Show("xxx is already running. \r\n\r\nIf the original process is hung up you may need to restart your computer, or kill the current xxx process using the task manager.", "xxx is already running!", MessageBoxButton.OK, MessageBoxImage.Exclamation);
// This process
Process currentProcess = Process.GetCurrentProcess();
// Get all processes running on the local computer.
Process[] localAll = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
// ID of this process...
int temp = currentProcess.Id;
MessageBox.Show("This Process ID: " + temp.ToString());
for (int i = 0; i < localAll.Length; i++)
{
// Find the other process
if (localAll[i].Id != currentProcess.Id)
{
MessageBox.Show("Original Process ID (Switching to): " + localAll[i].Id.ToString());
// Switch to it...
SetForegroundWindow(localAll[i].MainWindowHandle);
}
}
Application.Current.Shutdown();
}
This may have issues that I have not caught yet. If I run into any I'll update my answer.
This answer is a follow up to DaRKoN_'s answer that utilized the object filter:
[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }
I was having a problem figuring out how to send multiple parameters to an action method and have one of them be the json object and the other be a plain string. I'm new to MVC and I had just forgotten that I already solved this problem with non-ajaxed views.
What I would do if I needed, say, two different objects on a view. I would create a ViewModel class. So say I needed the person object and the address object, I would do the following:
public class SomeViewModel()
{
public Person Person { get; set; }
public Address Address { get; set; }
}
Then I would bind the view to SomeViewModel. You can do the same thing with JSON.
[ObjectFilter(Param = "jsonViewModel", RootType = typeof(JsonViewModel))] // Don't forget to add the object filter class in DaRKoN_'s answer.
public JsonResult doJsonStuff(JsonViewModel jsonViewModel)
{
Person p = jsonViewModel.Person;
Address a = jsonViewModel.Address;
// Do stuff
jsonViewModel.Person = p;
jsonViewModel.Address = a;
return Json(jsonViewModel);
}
Then in the view you can use a simple call with JQuery like this:
var json = {
Person: { Name: "John Doe", Sex: "Male", Age: 23 },
Address: { Street: "123 fk st.", City: "Redmond", State: "Washington" }
};
$.ajax({
url: 'home/doJsonStuff',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(json), //You'll need to reference json2.js
success: function (response)
{
var person = response.Person;
var address = response.Address;
}
});
In Vuetify 2.x, v-layout and v-flex are replaced by v-row and v-col respectively. To center the content both vertically and horizontally, we have to instruct the v-row component to do it:
<v-container fill-height>
<v-row justify="center" align="center">
<v-col cols="12" sm="4">
Centered both vertically and horizontally
</v-col>
</v-row>
</v-container>
Edward,
You can modify the code in your example like this:
var playerShip:PlayerShip!
var deltaPoint = CGPointZero
init(size: CGSize)
{
super.init(size: size)
playerLayerNode.addChild(playerShip)
}
This is using an implicitly unwrapped optional.
In documentation we can read:
"As with optionals, if you don’t provide an initial value when you declare an implicitly unwrapped optional variable or property, it’s value automatically defaults to nil."
If you are using Java 8, a shorter version for Jersey2 than the answer provided by Aleksandr.
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
// Create a new X509TrustManager
sslContext.init(null, getTrustManager(), null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw e;
}
final Client client = ClientBuilder.newBuilder().hostnameVerifier((s, session) -> true)
.sslContext(sslContext).build();
return client;
private TrustManager[] getTrustManager() {
return new TrustManager[] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
}
};
}
if all the above didn't work for you then add an .htaccess
file to the directory where your script is located and put this inside
<IfModule mod_php5.c>
php_value post_max_size 200M
php_value upload_max_filesize 200M
php_value memory_limit 300M
php_value max_execution_time 259200
php_value max_input_time 259200
php_value session.gc_maxlifetime 1200
</IfModule>
this was the way I solved my problem , neither ini_set('max_execution_time', 86400);
nor set_time_limit(86400)
solved my problem , but the .htaccess method did.
If you need to insert into a specific position in the array, you can do this:
case ADD_ITEM :
return {
...state,
arr: [
...state.arr.slice(0, action.pos),
action.newItem,
...state.arr.slice(action.pos),
],
}
If you put log4j.properties inside src, you don't need to use the statement -
PropertyConfigurator.configure("log4j.properties");
It will be taken automatically as the properties file is in the classpath.
This is the best way
LinearLayout lp = new LinearLayout(this);
lp.addView(new Button(this));
lp.addView(new ImageButton(this));
// Now remove them
lp.removeViewAt(0); // and so on
If you have xml layout then no need to add dynamically.just call
lp.removeViewAt(0);
In my case, this problem was solved by clicking 'Kernel' (shown on the top of notebooks) and then 'Reconnect'.
Note Added: In some versions of Jupyter, there is not 'Reconnect'.
You need to use font-url
in your @font-face block, not url
@font-face {
font-family: 'Inconsolata';
src:font-url('Inconsolata-Regular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
as well as this line in application.rb, as you mentioned (for fonts in app/assets/fonts
config.assets.paths << Rails.root.join("app", "assets", "fonts")
Also try directly startup:
sqlplus /nolog
conn / as sysdba
startup
In response to the OP, there are two problems with your code: you need to set jsonp='callback', and adding in a callback function in a variable like you did does not seem to work.
Update: when I wrote this the Twitter API was just open, but they changed it and it now requires authentication. I changed the second example to a working (2014Q1) example, but now using github.
This does not work any more - as an exercise, see if you can replace it with the Github API:
$('document').ready(function() {
var pm_url = 'http://twitter.com/status';
pm_url += '/user_timeline/stephenfry.json';
pm_url += '?count=10&callback=photos';
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
jsonp: 'callback',
});
});
function photos (data) {
alert(data);
console.log(data);
};
although alert()ing an array like that does not really work well... The "Net" tab in Firebug will show you the JSON properly. Another handy trick is doing
alert(JSON.stringify(data));
You can also use the jQuery.getJSON method. Here's a complete html example that gets a list of "gists" from github. This way it creates a randomly named callback function for you, that's the final "callback=?" in the url.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JQuery (cross-domain) JSONP Twitter example</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('https://api.github.com/gists?callback=?', function(response){
$.each(response.data, function(i, gist){
$('#gists').append('<li>' + gist.user.login + " (<a href='" + gist.html_url + "'>" +
(gist.description == "" ? "undescribed" : gist.description) + '</a>)</li>');
});
});
});
</script>
</head>
<body>
<ul id="gists"></ul>
</body>
</html>