public class MainActivity extends Activity {
private WebView webView1;
Button google;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
google = (Button) findViewById(R.id.google);
google.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
webView1 = (WebView) findViewById(R.id.webView);
webView1.getSettings().setJavaScriptEnabled(true);
webView1.loadUrl("http://www.google.co.in/");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I'll jump in with the notorious "Do you really want to do that" answer.
It seems like your focus is on playing with Java and seeing what it can do. However, if you want to actually develop a web app, you should be aware that, although Java is used in web applications (and in serious ones), there are other technology options which might be more adequate.
Personally, I like (and use) Java for powerful, portable backend services on a server. I've never tried building websites with it, because it never seemed the most obvious ting to do. After growing tired of PHP (which I have been using for years), I lately fell in love with Django, a Python-based web framework.
The Ruby on Rails people have a number of very funny videos on youtube comparing different web technologies to RoR. Of course, these are obviously exaggerated and maybe slightly biased, but I'd say there's more than one grain of truth in each of them. The one about Java is here. ;-)
This is basically the same answer provided by Evert, but extended to show-off
some cool options of fill_between
from matplotlib import pyplot as pl
import numpy as np
pl.clf()
pl.hold(1)
x = np.linspace(0, 30, 100)
y = np.sin(x) * 0.5
pl.plot(x, y, '-k')
x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape) +.1
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#CC4F1B')
pl.fill_between(x, y-error, y+error,
alpha=0.5, edgecolor='#CC4F1B', facecolor='#FF9848')
y = np.cos(x/6*np.pi)
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#1B2ACC')
pl.fill_between(x, y-error, y+error,
alpha=0.2, edgecolor='#1B2ACC', facecolor='#089FFF',
linewidth=4, linestyle='dashdot', antialiased=True)
y = np.cos(x/6*np.pi) + np.sin(x/3*np.pi)
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#3F7F4C')
pl.fill_between(x, y-error, y+error,
alpha=1, edgecolor='#3F7F4C', facecolor='#7EFF99',
linewidth=0)
pl.show()
If you are using gerrit, this could be caused by an inappropriate Change-id in the commit. Try deleting the Change-Id and see what happens.
const extend = function*(ls,xs){
yield* ls;
yield* xs;
}
console.log( [...extend([1,2,3],[4,5,6])] );
to check input and get confirm by check box ,use this script...
$(document).on("change", ".inputClass", function () {
if($(this).is(':checked')){
confirm_message = $(this).data('confirm');
var confirm_status = confirm(confirm_message);
if (confirm_status == true) {
//doing somethings...
}
}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> check action </lable>
<input class="inputClass" type="checkbox" data-confirm="are u sure to do ...?" >
_x000D_
I had the same problem solved using instead of pip install :
sudo apt-get install python-openpyxl
sudo apt-get install python3-openpyxl
The sudo command also works better for other packages.
Unless you're talking about base 16 numbers (for which there's a method to parse as Hex), you need to explicitly separate out the part that you are interested in, and then convert it. After all, what would be the semantics of something like 23e44e11d in base 10?
Regular expressions could do the trick if you know for sure that you only have one number. Java has a built in regular expression parser.
If, on the other hands, your goal is to concatenate all the digits and dump the alphas, then that is fairly straightforward to do by iterating character by character to build a string with StringBuilder, and then parsing that one.
You should probably clarify which logger are you using.
org.apache.commons.logging.Log
interface has method void error(Object message, Throwable t)
(and method void info(Object message, Throwable t)
), which logs the stack trace together with your custom message. Log4J implementation has this method too.
So, probably you need to write:
logger.error("BOOM!", e);
If you need to log it with INFO level (though, it might be a strange use case), then:
logger.info("Just a stack trace, nothing to worry about", e);
Hope it helps.
Is this what you are trying?
Option Explicit
Public Sub SaveWorksheetsAsCsv()
Dim WS As Worksheet
Dim SaveToDirectory As String, newName As String
SaveToDirectory = "H:\test\"
For Each WS In ThisWorkbook.Worksheets
newName = GetBookName(ThisWorkbook.Name) & "_" & WS.Name
WS.Copy
ActiveWorkbook.SaveAs SaveToDirectory & newName, xlCSV
ActiveWorkbook.Close Savechanges:=False
Next
End Sub
Function GetBookName(strwb As String) As String
GetBookName = Left(strwb, (InStrRev(strwb, ".", -1, vbTextCompare) - 1))
End Function
This is late to the game, but I found the most awesome-est command line command for this problem. Done using bash. Enjoy.
svn status | grep -v excluding | sed 's/^A */"/g; s/$/"/g' | tr '\n' ' ' | xargs svn commit -m "My Message"
Ok, so here's an explanation of the command. Some things will need to be changed based on your use case.
svn status
I get a list of all the files. They'll all start with those status characters (?, !, A, etc). Each is on its own lines
grep -v excluding
I use grep to filter the list. It can either be used normally (to include) or with the -v flag (to exclude). In this case, it's being used to exclude, with a phrase "excluding" being what will be excluded.
sed 's/^. */"/g; s/$/"/g'
Now I remove the status character and whitespace at the beginning of each line, and then quote each line, using sed. Some of my filenames have spaces in them, hence the quoting.
tr '\n' ' '
Using tr, I replace all newlines with spaces. Now my entire list of files to commit is on one line.
xargs svn commit -m "My Message"
Lastly, I use xargs to execute my commit command with the message. It does the commit, and drops my quoted file list as the last argument.
The result is that everything ultimately works the way that I want it to. I still kind of hate svn for forcing me to jump through these goddamn hoops, but I can live with this. I guess.
To avoid adding extra div
s when clicking on the link multiple times, and avoid problems when using the script to display forms, you could try a variation of @jek's code.
$('a.ajax').live('click', function() {
var url = this.href;
var dialog = $("#dialog");
if ($("#dialog").length == 0) {
dialog = $('<div id="dialog" style="display:hidden"></div>').appendTo('body');
}
// load remote content
dialog.load(
url,
{},
function(responseText, textStatus, XMLHttpRequest) {
dialog.dialog();
}
);
//prevent the browser to follow the link
return false;
});`
This is not defined.
A payload within a DELETE request message has no defined semantics; sending a payload body on a DELETE request might cause some existing implementations to reject the request.
https://tools.ietf.org/html/rfc7231#page-29
StringExtension class is the way forward, I've combined a couple of the posts above to give a complete code example:
public static class StringExtensions
{
/// <summary>
/// Allows case insensitive checks
/// </summary>
public static bool Contains(this string source, string toCheck, StringComparison comp)
{
return source.IndexOf(toCheck, comp) >= 0;
}
}
There is a convenient third party tool named FileMenu Tools, that gives several right-click tools as a windows explorer extension.
One of them is Split file / Join Parts, that does and undoes exactly what you are looking for.
Check it at http://www.lopesoft.com/en/filemenutools. Of course, it is windows only, as Unixes environments already have lots of tools for that.
Using the std::bitset answers and convenience templates:
#include <iostream>
#include <bitset>
#include <climits>
template<typename T>
struct BinaryForm {
BinaryForm(const T& v) : _bs(v) {}
const std::bitset<sizeof(T)*CHAR_BIT> _bs;
};
template<typename T>
inline std::ostream& operator<<(std::ostream& os, const BinaryForm<T> bf) {
return os << bf._bs;
}
Using it like this:
auto c = 'A';
std::cout << "c: " << c << " binary: " << BinaryForm{c} << std::endl;
unsigned x = 1234;
std::cout << "x: " << x << " binary: " << BinaryForm{x} << std::endl;
int64_t z { -1024 };
std::cout << "z: " << << " binary: " << BinaryForm{z} << std::endl;
Generates output:
c: A binary: 01000001
x: 1234 binary: 00000000000000000000010011010010
z: -1024 binary: 1111111111111111111111111111111111111111111111111111110000000000
You can use str.split
by whitespace (default separator) and parameter expand=True
for DataFrame
with assign to new columns:
df = pd.DataFrame({'row': ['00000 UNITED STATES', '01000 ALABAMA',
'01001 Autauga County, AL', '01003 Baldwin County, AL',
'01005 Barbour County, AL']})
print (df)
row
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
df[['a','b']] = df['row'].str.split(n=1, expand=True)
print (df)
row a b
0 00000 UNITED STATES 00000 UNITED STATES
1 01000 ALABAMA 01000 ALABAMA
2 01001 Autauga County, AL 01001 Autauga County, AL
3 01003 Baldwin County, AL 01003 Baldwin County, AL
4 01005 Barbour County, AL 01005 Barbour County, AL
Modification if need remove original column with DataFrame.pop
df[['a','b']] = df.pop('row').str.split(n=1, expand=True)
print (df)
a b
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
What is same like:
df[['a','b']] = df['row'].str.split(n=1, expand=True)
df = df.drop('row', axis=1)
print (df)
a b
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
If get error:
#remove n=1 for split by all whitespaces
df[['a','b']] = df['row'].str.split(expand=True)
ValueError: Columns must be same length as key
You can check and it return 4 column DataFrame
, not only 2:
print (df['row'].str.split(expand=True))
0 1 2 3
0 00000 UNITED STATES None
1 01000 ALABAMA None None
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
Then solution is append new DataFrame
by join
:
df = pd.DataFrame({'row': ['00000 UNITED STATES', '01000 ALABAMA',
'01001 Autauga County, AL', '01003 Baldwin County, AL',
'01005 Barbour County, AL'],
'a':range(5)})
print (df)
a row
0 0 00000 UNITED STATES
1 1 01000 ALABAMA
2 2 01001 Autauga County, AL
3 3 01003 Baldwin County, AL
4 4 01005 Barbour County, AL
df = df.join(df['row'].str.split(expand=True))
print (df)
a row 0 1 2 3
0 0 00000 UNITED STATES 00000 UNITED STATES None
1 1 01000 ALABAMA 01000 ALABAMA None None
2 2 01001 Autauga County, AL 01001 Autauga County, AL
3 3 01003 Baldwin County, AL 01003 Baldwin County, AL
4 4 01005 Barbour County, AL 01005 Barbour County, AL
With remove original column (if there are also another columns):
df = df.join(df.pop('row').str.split(expand=True))
print (df)
a 0 1 2 3
0 0 00000 UNITED STATES None
1 1 01000 ALABAMA None None
2 2 01001 Autauga County, AL
3 3 01003 Baldwin County, AL
4 4 01005 Barbour County, AL
If you are using Windows, open up a command prompt and type 'netstat -an'.
If your server is running, you should be able to see the port 1883.
If you cannot go to Task Manager > Services and start/restart the Mosquitto server from there. If you cannot find it here too, your installation of Mosquitto has not been successful.
A more detailed tutorial for setting up Mosquitto with Windows / is linked here.
This will work
$ext = pathinfo($filename, PATHINFO_EXTENSION);
POSIX 2008 added the +
marker to find
which means it now automatically groups as many files as are reasonable into a single command execution, very much like xargs
does, but with a number of advantages:
The file name issue is a problem with xargs
without the -0
option, and the 'run even with zero file names' issue is a problem with or without the -0
option — but GNU xargs
has the -r
or --no-run-if-empty
option to prevent that happening. Also, this notation cuts down on the number of processes, not that you're likely to measure the difference in performance. Hence, you could sensibly write:
find . -exec grep something {} +
find . -print | xargs grep something
If you're on Linux or have the GNU find
and xargs
commands, then use -print0
with find
and -0
with xargs
to handle file names containing spaces and other odd-ball characters.
find . -print0 | xargs -0 grep something
grep
If you don't want the file names (just the text) then add an appropriate option to grep
(usually -h
to suppressing 'headings'). To absolutely guarantee the file name is printed by grep
(even if only one file is found, or the last invocation of grep
is only given 1 file name), then add /dev/null
to the xargs
command line, so that there will always be at least two file names.
The two valid mains are int main()
and int main(int, char*[])
. Any thing else may or may not compile. If main
doesn't explicitly return a value, 0 is implicitly returned.
To expand on user2915097's response:
The idea of isolation is to be able to restrict what an application/process/container (whatever your angle at this is) can do to the host system very clearly. Hence, being able to copy and execute a file would really break the whole concept.
Yes. But it's sometimes necessary.
No. That's not the case, or Docker is not the right thing to use. What you should do is declare a clear interface for what you want to do (e.g. updating a host config), and write a minimal client/server to do exactly that and nothing more. Generally, however, this doesn't seem to be very desirable. In many cases, you should simply rethink your approach and eradicate that need. Docker came into an existence when basically everything was a service that was reachable using some protocol. I can't think of any proper usecase of a Docker container getting the rights to execute arbitrary stuff on the host.
You can return FileResult with this methods:
1: Return FileStreamResult
[HttpGet("get-file-stream/{id}"]
public async Task<FileStreamResult> DownloadAsync(string id)
{
var fileName="myfileName.txt";
var mimeType="application/....";
var stream = await GetFileStreamById(id);
return new FileStreamResult(stream, mimeType)
{
FileDownloadName = fileName
};
}
2: Return FileContentResult
[HttpGet("get-file-content/{id}"]
public async Task<FileContentResult> DownloadAsync(string id)
{
var fileName="myfileName.txt";
var mimeType="application/....";
var fileBytes = await GetFileBytesById(id);
return new FileContentResult(fileBytes, mimeType)
{
FileDownloadName = fileName
};
}
readlines() reads the entire input file into a list and is not a good performer. Just iterate through the lines in the file. I used 'with' on output.txt so that it is automatically closed when done. That's not needed on 'list1.txt' because it will be closed when the for loop ends.
#!/usr/bin/env python
with open('output.txt', 'a') as f1:
for line in open('list1.txt'):
if 'tests/file/myword' in line:
f1.write(line)
Do you mean like:
import groovy.json.*
class Me {
String name
}
def o = new Me( name: 'tim' )
println new JsonBuilder( o ).toPrettyString()
You can use WhenAll
which will return an awaitable Task
or WaitAll
which has no return type and will block further code execution simular to Thread.Sleep
until all tasks are completed, canceled or faulted.
Example
var tasks = new Task[] {
TaskOperationOne(),
TaskOperationTwo()
};
Task.WaitAll(tasks);
// or
await Task.WhenAll(tasks);
If you want to run the tasks in a praticular order you can get inspiration form this anwser.
$(function () {_x000D_
$('input[type="file"]').change(function () {_x000D_
if ($(this).val() != "") {_x000D_
$(this).css('color', '#333');_x000D_
}else{_x000D_
$(this).css('color', 'transparent');_x000D_
}_x000D_
});_x000D_
})
_x000D_
input[type="file"]{_x000D_
color: transparent;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="file" name="app_cvupload" class="fullwidth input rqd">
_x000D_
Below code will help you:
public class DeckListAdapter extends BaseAdapter{
private LayoutInflater mInflater;
ArrayList<String> teams=new ArrayList<String>();
ArrayList<Integer> teamcolor=new ArrayList<Integer>();
public DeckListAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
teams.add("Upload");
teams.add("Download");
teams.add("Device Browser");
teams.add("FTP Browser");
teams.add("Options");
teamcolor.add(Color.WHITE);
teamcolor.add(Color.LTGRAY);
teamcolor.add(Color.WHITE);
teamcolor.add(Color.LTGRAY);
teamcolor.add(Color.WHITE);
}
public int getCount() {
return teams.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.decklist, null);
holder = new ViewHolder();
holder.icon = (ImageView) convertView.findViewById(R.id.deckarrow);
holder.text = (TextView) convertView.findViewById(R.id.textname);
.......here you can use holder.text.setonclicklistner(new View.onclick.
for each textview
System.out.println(holder.text.getText().toString());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(teams.get(position));
if(position<teamcolor.size())
holder.text.setBackgroundColor(teamcolor.get(position));
holder.icon.setImageResource(R.drawable.arraocha);
return convertView;
}
class ViewHolder {
ImageView icon;
TextView text;
}
}
Hope this helps.
Note: This is not a duplicate, because the OP is aware that the image from cv2.imread
is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)
To illustrate, I've opened up this same color JPEG image:
once using the conversion
img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
and another by loading it in gray scale mode
img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom
I've summed up the diff too to see
import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image
I tried all cv2.imread()
modes
Among all the IMREAD_
modes for cv2.imread()
, only IMREAD_COLOR
and IMREAD_ANYCOLOR
can be converted using COLOR_BGR2GRAY
, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE
The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)
Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.
In brief, let's not mix the versions and types in the processing pipeline.
So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)
I had the same Problem. I had start my Oracle TNS Listener, then it works normally again.
There's no easy way to do this, but something like this will work:
SELECT ET.TrainingID,
ET.CompletedDate,
ET.Notes
FROM
HR_EmployeeTrainings ET
inner join
(
select TrainingID, Max(CompletedDate) as CompletedDate
FROM HR_EmployeeTrainings
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
GROUP BY AvantiRecID, TrainingID
) ET2
on ET.TrainingID = ET2.TrainingID
and ET.CompletedDate = ET2.CompletedDate
Use localStorage to store the fact that you opened the page :
$(document).ready(function() {
var yetVisited = localStorage['visited'];
if (!yetVisited) {
// open popup
localStorage['visited'] = "yes";
}
});
You just have to post the data. and Using jquery ajax function set parameters. Here is an example.
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'your_complete url',
data: $('form').serialize(),
success: function (response) {
//$('form')[0].reset();
// $("#feedback").text(response);
if(response=="True") {
$('form')[0].reset();
$("#feedback").text("Your information has been stored.");
}
else
$("#feedback").text(" Some Error has occured Errror !!! ID duplicate");
}
});
});
});
</script>
It is located in the AppData
hidden folder
C:\Users\[user]\AppData\Local\Android\sdk\platform-tools
From l33t's comment below you may use the following shortcut:
%LOCALAPPDATA%\Android\sdk\platform-tools
Most of these answers are invalid after the 6/1/2016 Instagram API changes. The best solution now is here. Go to your feed on instagram.com, copy the link address for any of your pictures, and paste it into the textbox on that page. Worked like a charm.
Using useEffect hook:
useEffect(() => {
const ourRequest = Axios.CancelToken.source() // <-- 1st step
const fetchPost = async () => {
try {
const response = await Axios.get(`endpointURL`, {
cancelToken: ourRequest.token, // <-- 2nd step
})
console.log(response.data)
setPost(response.data)
setIsLoading(false)
} catch (err) {
console.log('There was a problem or request was cancelled.')
}
}
fetchPost()
return () => {
ourRequest.cancel() // <-- 3rd step
}
}, [])
Note: For POST request, pass cancelToken as 3rd argument
Axios.post(`endpointURL`, {data}, {
cancelToken: ourRequest.token, // 2nd step
})
I found this helpful
<?php if (strpos($_SERVER['HTTP_USER_AGENT'], 'Trident/7.0; rv:11.0') !== false) { ?>
<script>
$(function(){
$('html').addClass('ie11');
});
</script>
<?php } ?>
Add this under your <head>
document
SELECT * FROM [server].[database].[schema].[table]
This works for me. SSMS intellisense may still underline this as a syntax error, but it should work if your linked server is configured and your query is otherwise correct.
For a vector m
, m[round(m) != m]
will return the indices of values in the vector that are not integers.
you must put object in your JSX, It`s easy way to do this just see my simple code here:
const link = [
{
name: "Cold Drink",
link: "/coldDrink"
},
{
name: "Hot Drink",
link: "/HotDrink"
},
{ name: "chease Cake", link: "/CheaseCake" } ]; and you must map this array in your code with simple object see this code :
const links = (this.props.link);
{links.map((item, i) => (
<li key={i}>
<Link to={item.link}>{item.name}</Link>
</li>
))}
I hope this answer will be helpful for you ...:)
For substracting in moment.js:
moment().subtract(1, 'months').format('MMM YYYY');
Documentation:
http://momentjs.com/docs/#/manipulating/subtract/
Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).
moment().subtract('seconds', 1); // Deprecated in 2.8.0
moment().subtract(1, 'seconds');
As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.
moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8
For Swift 3, many Foundation
types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString
.
This code is perfect for me:
this.context.beginPath();
this.context.moveTo(data[0].x, data[0].y);
for (let i = 1; i < data.length; i++) {
this.context.bezierCurveTo(
data[i - 1].x + (data[i].x - data[i - 1].x) / 2,
data[i - 1].y,
data[i - 1].x + (data[i].x - data[i - 1].x) / 2,
data[i].y,
data[i].x,
data[i].y);
}
you have correct smooth line and correct endPoints NOTICE! (y = "canvas height" - y);
In layman terms it's strongly structured vs unstructured, which implies that you have different degrees of adaptability for your DB. Differences arise in indexation particularly as you need to ensure that a certain reference index can link to a another item -> this a relation. The more strict structure of relational DB comes from this requirement.
To note that NosDB apaprently provides both relational and non relational DBs and a way to query both http://www.alachisoft.com/nosdb/sql-cheat-sheet.html
You need to make the members in the for the form class either public or, if the service class is in the same assembly, internal. Windows controls' visibility can be controlled through their Modifiers properties.
Note that it's generally considered a bad practice to explicitly tie a service class to a UI class. Rather you should create good interfaces between the service class and the form class. That said, for learning or just generally messing around, the earth won't spin off its axis if you expose form members for service classes.
rp
Another similar option that I think Nick briefly alluded to in the comments is to create multiple wrapper jars. I haven't tried it, but I think they could be completely empty other than the manifest file, which should specify the main class to load as well as the inclusion of the MyJar.jar to the classpath.
MyJar1.jar\META-INF\MANIFEST.MF
Manifest-Version: 1.0
Main-Class: com.mycomp.myproj.dir1.MainClass1
Class-Path: MyJar.jar
MyJar2.jar\META-INF\MANIFEST.MF
Manifest-Version: 1.0
Main-Class: com.mycomp.myproj.dir2.MainClass2
Class-Path: MyJar.jar
etc.
Then just run it with java -jar MyJar2.jar
your panel class don't have a constructor that accepts a string
try change
RLS_strid_panel p = new RLS_strid_panel(namn1);
to
RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);
If by "hex data" you mean a string of the form
s = "6a48f82d8e828ce82b82"
you can use
i = int(s, 16)
to convert it to an integer and
str(i)
to convert it to a decimal string.
I have used many codes from the above mentioned sections for removing index.php form the base url. But it was not working from my end. So, you can use this code which I have used and its working properly.
If you really need to remove index.php from the base URL then just put this code in your htaccess.
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]
If you want to know the number of tables that belong to a certain schema/user, you can also use SQL similar to this one:
SELECT Count(*) FROM DBA_TABLES where OWNER like 'PART_OF_NAME%';
With the step attribute specified to the precision of the decimals you want, and the lang attribute [which is set to a locale that formats decimals with period], your html5 numeric input will accept decimals. eg. to take values like 10.56; i mean 2 decimal place numbers, do this:
<input type="number" step="0.01" min="0" lang="en" value="1.99">
You can further specify the max attribute for the maximum allowable value.
Edit Add a lang attribute to the input element with a locale value that formats decimals with point instead of comma
If you want to use Linq then you can use the following snippet:
var listNumber = dicNumber.Keys.ToList();
You mention Haxe/NME but you seem to instinctively dislike it. However, my experience with it has been very positive. Sure, the API is a reimplementation of the Flash API, but you're not limited to targeting Flash, you can also compile to HTML5 or native Windows, Mac, iOS and Android apps. Haxe is a pleasant, modern language similar to Java or C#.
If you're interested, I've written a bit about my experience using Haxe/NME: link
In your onHandleSubmit
function, set your state to {city: ''}
again like this :
this.setState({ city: '' });
Here's your bulletproof solution:
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="33%" align="center" valign="top" style="font-family:Arial, Helvetica, sans-serif; font-size:2px; color:#ffffff;">.</td>
<td width="35%" align="center" valign="top">
CONTENT GOES HERE
</td>
<td width="33%" align="center" valign="top" style="font-family:Arial, Helvetica, sans-serif; font-size:2px; color:#ffffff;">.</td>
</tr>
</table>
Just Try it out, Looks a bit messy, but It works Even with the new Firefox Update for Yahoo mail. (doesn't center the email because replace the main table by a div)
Like 5 years late, I know, thanks for all the proposals, I used to do this the following way:
$ echo /home/parent/child1/child2/filename | rev | cut -d '/' -f1 | rev
filename
Glad to notice there are better manners
If you set the AllowsTransparency
property on the Window
(even without setting any transparency values) the border disappears and you can only resize via the grip.
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="640" Height="480"
WindowStyle="None"
AllowsTransparency="True"
ResizeMode="CanResizeWithGrip">
<!-- Content -->
</Window>
Result looks like:
A HashSet
has an internal structure (hash), where items can be searched and identified quickly. The downside is that iterating through a HashSet
(or getting an item by index) is rather slow.
So why would someone want be able to know if an entry already exists in a set?
One situation where a HashSet
is useful is in getting distinct values from a list where duplicates may exist. Once an item is added to the HashSet
it is quick to determine if the item exists (Contains
operator).
Other advantages of the HashSet
are the Set operations: IntersectWith
, IsSubsetOf
, IsSupersetOf
, Overlaps
, SymmetricExceptWith
, UnionWith
.
If you are familiar with the object constraint language then you will identify these set operations. You will also see that it is one step closer to an implementation of executable UML.
If you want to look at parameters and methods, as others have pointed out you may well use pprint
or dir()
If you want to see the actual value of the contents, you can do
object.__dict__
For global purposes.
Instead of converting, codifying, decodifying each text I prefer to let them as they are and instead change the server php settings. So,
Let the diamonds
From the browser, on the view menu select "text encoding" and find the one which let's you see your text correctly.
Edit your php.ini and add:
default_charset = "ISO-8859-1"
or instead of ISO-8859 the one which fits your text encoding.
I know this says command line, but just a tidbit of something quick to try that might work, if you've got MySQL workbench and the csv isn't too large, you can simply
I say hope for the best because this is MySQL Workbench. You never know when it's going to explode
If you want to do this on a remote server, you would do
mysql -h<server|ip> -u<username> -p --local-infile bark -e "LOAD DATA LOCAL INFILE '<filename.csv>' INTO TABLE <table> FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'"
Note, I didn't put a password after -p
as putting one on the command line is considered bad practice
I experienced a similar problem and doing width:100%;
solved it for me. I came to this solution after trying an answer in this question and realizing that the very nature of an <iframe>
will make these javascript measurement tools inaccurate without using some complex function. Doing 100% is a simple way to take care of it in an iframe. I don't know about your issue since I'm not sure of what HTML elements you are manipulating.
You haven't reserved enough space in your vector object to hold the contents of your set.
std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());
The another solution is service volume, You can define a service volume and mount host's PostgreSQL Data directory in that volume. Check out the given compose file for details.
version: '2'
services:
db:
image: postgres:9.6.1
volumes:
- "/var/lib/postgresql/data:/var/lib/postgresql/data"
ports:
- "5432:5432"
By doing this, another PostgreSQL service will run under container but uses same data directory which host PostgreSQL service is using.
POST is valid to use instead of GET if you have specific reasons for doing so and process it properly. I understand it's not specifically RESTy, but if you have a bunch of spaces and ampersands and slashes and so on in your data [eg a product model like Amazon] then trying to encode and decode this can be more trouble than it's worth instead of just pre-jsonifying it. Make sure though that you return the proper response codes and heavily comment what you're doing because it's not a typical use case of POST.
I think there's an even easier way now. This enables basic caching for all $http requests (which $resource inherits):
var app = angular.module('myApp',[])
.config(['$httpProvider', function ($httpProvider) {
// enable http caching
$httpProvider.defaults.cache = true;
}])
The max length of a varchar in MySQL 5.6.12 is 4294967295.
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
# Python Program - Convert Hexadecimal to Binary
hexdec = input("Enter Hexadecimal string: ")
print(hexdec," in Binary = ", end="") # end is by default "\n" which prints a new line
for _hex in hexdec:
dec = int(_hex, 16) # 16 means base-16 wich is hexadecimal
print(bin(dec)[2:].rjust(4,"0"), end="") # the [2:] skips 0b, and the
There's actually a pretty good implementation of a class decorator here:
https://github.com/agiliq/Django-parsley/blob/master/parsley/decorators.py
I actually think this is a pretty interesting implementation. Because it subclasses the class it decorates, it will behave exactly like this class in things like isinstance
checks.
It has an added benefit: it's not uncommon for the __init__
statement in a custom django Form to make modifications or additions to self.fields
so it's better for changes to self.fields
to happen after all of __init__
has run for the class in question.
Very clever.
However, in your class you actually want the decoration to alter the constructor, which I don't think is a good use case for a class decorator.
In my case the problem was that I had putted the following code to keep the gridview tableheader after partial postback:
protected override void OnPreRenderComplete(EventArgs e)
{
if (grv.Rows.Count > 0)
{
grv.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
Removing this code stopped the issue.
If you are using "MVC 5" you may not see the file, and you should follow these steps: http://www.techjunkieblog.com/2015/05/aspnet-mvc-empty-project-adding.html
If you are using "ASP.NET 5" it has stopped using "bundling and minification" instead was replaced by gulp, bower, and npm. More information see https://jeffreyfritz.com/2015/05/where-did-my-asp-net-bundles-go-in-asp-net-5/
Your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary POST
.
That is: Modern browsers will only allow Ajax calls to services in the same domain as the HTML page.
Example: A page in http://www.example.com/myPage.html
can only directly request services that are in http://www.example.com
, like http://www.example.com/testservice/etc
. If the service is in other domain, the browser won't make the direct call (as you'd expect). Instead, it will try to make a CORS request.
To put it shortly, to perform a CORS request, your browser:
OPTION
request to the target URLOPTION
contains the adequate headers (Access-Control-Allow-Origin
is one of them) to allow the CORS request, the browse will perform the call (almost exactly the way it would if the HTML page was at the same domain).
How to solve it? The simplest way is to enable CORS (enable the necessary headers) on the server.
If you don't have server-side access to it, you can mirror the web service from somewhere else, and then enable CORS there.
Just the thread.
I hope what you are trying to achieve is like this. For this please use Box layout.
package com.kcing.kailas.sample.client;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
public class Testing extends JFrame {
private JPanel jContentPane = null;
public Testing() {
super();
initialize();
}
private void initialize() {
this.setSize(300, 200);
this.setContentPane(getJContentPane());
this.setTitle("JFrame");
}
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(61, 11, 81, 140);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
jContentPane.add(panel);
JCheckBox c1 = new JCheckBox("Check1");
panel.add(c1);
c1 = new JCheckBox("Check2");
panel.add(c1);
c1 = new JCheckBox("Check3");
panel.add(c1);
c1 = new JCheckBox("Check4");
panel.add(c1);
}
return jContentPane;
}
public static void main(String[] args) throws Exception {
Testing frame = new Testing();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
}
I know this is an old post, but I really hate that there is only one answer here that suggests not mixing html and php. Instead of mixing content one should use template systems, or create a basic template system themselves.
In the php
<?php
$var1 = 'Alice'; $var2 = 'apples'; $var3 = 'lunch'; $var4 = 'Bob';
if ($var1 == 'Alice') {
$html = file_get_contents('/path/to/file.html'); //get the html template
$template_placeholders = array('##variable1##', '##variable2##', '##variable3##', '##variable4##'); // variable placeholders inside the template
$template_replace_variables = array($var1, $var2, $var3, $var4); // the variables to pass to the template
$html_output = str_replace($template_placeholders, $template_replace_variables, $html); // replace the placeholders with the actual variable values.
}
echo $html_output;
?>
In the html (/path/to/file.html)
<p>##variable1## ate ##variable2## for ##variable3## with ##variable4##.</p>
The output of this would be:
Alice ate apples for lunch with Bob.
FWIW, git rebase interactive now has a "reword" option, which makes this much less painful!
:set runtimepath?
This lists the path of all plugins loaded when a file is opened with Vim.
You can track by $index
if your data source has duplicate identifiers
e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]
You can't iterate this collection while using 'id' as identifier (duplicate id:1).
WON'T WORK:
<element ng-repeat="item.id as item.name for item in dataSource">
// something with item ...
</element>
but you can, if using track by $index
:
<element ng-repeat="item in dataSource track by $index">
// something with item ...
</element>
This is working for me, as described in this thread:
declare let something: string;
something = 'foo';
Click these links to see these more flexible and robust solutions. They're answers to a similar question:
window.location.search = jQuery.query.set('single', true);
parse
and stringify
on window.location.search
These allow you to programmatically set the parameter, and, unlike the other hacks suggested for this question, won't break for URLs that already have a parameter, or if something else isn't quite what you thought might happen.
In my case I checked event logs and found error was Cannot read configuration file ' trying to read configuration data from file '\\?\', line number '0'. The data field contains the error code.
The error code was 2307.
I deleted all files in C:\inetpub\temp\appPools and restarted the iis. It fixed the issue.
UPDATE 2
@Override
protected void onResume() {
super.onResume();
mUserNameEdit.requestFocus();
mUserNameEdit.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
InputMethodManager keyboard = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(mUserNameEdit, 0);
}
},200); //use 300 to make it run when coming back from lock screen
}
I tried very hard and found out a solution ... whenever a new activity starts then keyboard cant open but we can use Runnable in onResume and it is working fine so please try this code and check...
UPDATE 1
add this line in your AppLogin.java
mUserNameEdit.requestFocus();
and this line in your AppList.java
listview.requestFocus()'
after this check your application if it is not working then add this line in your AndroidManifest.xml
file
<activity android:name=".AppLogin" android:configChanges="keyboardHidden|orientation"></activity>
<activity android:name=".AppList" android:configChanges="keyboard|orientation"></activity>
ORIGINAL ANSWER
InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
for hide keyboard
imm.hideSoftInputFromWindow(ed.getWindowToken(), 0);
for show keyboard
imm.showSoftInput(ed, 0);
for focus on EditText
ed.requestFocus();
where ed is EditText
If you want to give your user all read permissions, you could use:
EXEC sp_addrolemember N'db_datareader', N'your-user-name'
That adds the default db_datareader
role (read permission on all tables) to that user.
There's also a db_datawriter
role - which gives your user all WRITE permissions (INSERT, UPDATE, DELETE) on all tables:
EXEC sp_addrolemember N'db_datawriter', N'your-user-name'
If you need to be more granular, you can use the GRANT
command:
GRANT SELECT, INSERT, UPDATE ON dbo.YourTable TO YourUserName
GRANT SELECT, INSERT ON dbo.YourTable2 TO YourUserName
GRANT SELECT, DELETE ON dbo.YourTable3 TO YourUserName
and so forth - you can granularly give SELECT, INSERT, UPDATE, DELETE permission on specific tables.
This is all very well documented in the MSDN Books Online for SQL Server.
And yes, you can also do it graphically - in SSMS, go to your database, then Security > Users
, right-click on that user you want to give permissions to, then Properties
adn at the bottom you see "Database role memberships" where you can add the user to db roles.
Beware of ORDER BY RAND() because of performance and results. Check this article out: http://jan.kneschke.de/projects/mysql/order-by-rand/
xxhdpi was not specified before but now new devices S4, HTC one are surely comes inside xxhdpi .These device dpi are around 440. I do not know exact limit for xxhdpi See how to develop android application for xxhdpi device Samsung S4 I know this is late answer but as thing had change since the question asked
Note Google Nexus 10 need to add a 144*144px icon in the drawable-xxhdpi or drawable-480dpi folder.
If you use code analysis tools (e.g. FxCop), it will recommend that you mark a method static
if that method don't access instance data. The rationale is that there is a performance gain. MSDN: CA1822 - Mark members as static.
It is more of a guideline than a rule, really...
System.nanoTime()
isn't supported in older JVMs. If that is a concern, stick with currentTimeMillis
Regarding accuracy, you are almost correct. On SOME Windows machines, currentTimeMillis()
has a resolution of about 10ms (not 50ms). I'm not sure why, but some Windows machines are just as accurate as Linux machines.
I have used GAGETimer in the past with moderate success.
ADO Recordset has .State
property, you can check if its value is adStateClosed
or adStateOpen
If Not (rs Is Nothing) Then
If (rs.State And adStateOpen) = adStateOpen Then rs.Close
Set rs = Nothing
End If
Edit;
The reason not to check .State
against 1 or 0 is because even if it works 99.99% of the time, it is still possible to have other flags set which will cause the If statement fail the adStateOpen
check.
Edit2:
For Late binding without the ActiveX Data Objects referenced, you have few options. Use the value of adStateOpen constant from ObjectStateEnum
If Not (rs Is Nothing) Then
If (rs.State And 1) = 1 Then rs.Close
Set rs = Nothing
End If
Or you can define the constant yourself to make your code more readable (defining them all for a good example.)
Const adStateClosed As Long = 0 'Indicates that the object is closed.
Const adStateOpen As Long = 1 'Indicates that the object is open.
Const adStateConnecting As Long = 2 'Indicates that the object is connecting.
Const adStateExecuting As Long = 4 'Indicates that the object is executing a command.
Const adStateFetching As Long = 8 'Indicates that the rows of the object are being retrieved.
[...]
If Not (rs Is Nothing) Then
' ex. If (0001 And 0001) = 0001 (only open flag) -> true
' ex. If (1001 And 0001) = 0001 (open and retrieve) -> true
' This second example means it is open, but its value is not 1
' and If rs.State = 1 -> false, even though it is open
If (rs.State And adStateOpen) = adStateOpen Then
rs.Close
End If
Set rs = Nothing
End If
You can either Drop the columns you do not need OR Select the ones you need
# Using DataFrame.drop
df.drop(df.columns[[1, 2]], axis=1, inplace=True)
# drop by Name
df1 = df1.drop(['B', 'C'], axis=1)
# Select the ones you want
df1 = df[['a','d']]
The parser is having trouble concatenating your string. Try this:
write-host 'value is : '$i' '$($ds.Tables[1].Rows[$i][0])
Edit: Using double quotes might also be clearer since you can include the expressions within the quoted string:
write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
Necromancing.
Also, the method by bzlm can be used to remove characters that are not in an arbitrary charset, not just ASCII:
// https://en.wikipedia.org/wiki/Code_page#EBCDIC-based_code_pages
// https://en.wikipedia.org/wiki/Windows_code_page#East_Asian_multi-byte_code_pages
// https://en.wikipedia.org/wiki/Chinese_character_encoding
System.Text.Encoding encRemoveAllBut = System.Text.Encoding.ASCII;
encRemoveAllBut = System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.InstalledUICulture.TextInfo.ANSICodePage); // System-encoding
encRemoveAllBut = System.Text.Encoding.GetEncoding(1252); // Western European (iso-8859-1)
encRemoveAllBut = System.Text.Encoding.GetEncoding(1251); // Windows-1251/KOI8-R
encRemoveAllBut = System.Text.Encoding.GetEncoding("ISO-8859-5"); // used by less than 0.1% of websites
encRemoveAllBut = System.Text.Encoding.GetEncoding(37); // IBM EBCDIC US-Canada
encRemoveAllBut = System.Text.Encoding.GetEncoding(500); // IBM EBCDIC Latin 1
encRemoveAllBut = System.Text.Encoding.GetEncoding(936); // Chinese Simplified
encRemoveAllBut = System.Text.Encoding.GetEncoding(950); // Chinese Traditional
encRemoveAllBut = System.Text.Encoding.ASCII; // putting ASCII again, as to answer the question
// https://stackoverflow.com/questions/123336/how-can-you-strip-non-ascii-characters-from-a-string-in-c
string inputString = "Räksmör??????, ???gås";
string asAscii = encRemoveAllBut.GetString(
System.Text.Encoding.Convert(
System.Text.Encoding.UTF8,
System.Text.Encoding.GetEncoding(
encRemoveAllBut.CodePage,
new System.Text.EncoderReplacementFallback(string.Empty),
new System.Text.DecoderExceptionFallback()
),
System.Text.Encoding.UTF8.GetBytes(inputString)
)
);
System.Console.WriteLine(asAscii);
AND for those that just want to remote the accents:
(caution, because Normalize != Latinize != Romanize)
// string str = Latinize("(æøå âôû?aè");
public static string Latinize(string stIn)
{
// Special treatment for German Umlauts
stIn = stIn.Replace("ä", "ae");
stIn = stIn.Replace("ö", "oe");
stIn = stIn.Replace("ü", "ue");
stIn = stIn.Replace("Ä", "Ae");
stIn = stIn.Replace("Ö", "Oe");
stIn = stIn.Replace("Ü", "Ue");
// End special treatment for German Umlauts
string stFormD = stIn.Normalize(System.Text.NormalizationForm.FormD);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int ich = 0; ich < stFormD.Length; ich++)
{
System.Globalization.UnicodeCategory uc = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)
{
sb.Append(stFormD[ich]);
} // End if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)
} // Next ich
//return (sb.ToString().Normalize(System.Text.NormalizationForm.FormC));
return (sb.ToString().Normalize(System.Text.NormalizationForm.FormKC));
} // End Function Latinize
See:
/**
* Convert number of seconds into hours, minutes and seconds
* and return an array containing those values
*
* @param integer $inputSeconds Number of seconds to parse
* @return array
*/
function secondsToTime($inputSeconds) {
$secondsInAMinute = 60;
$secondsInAnHour = 60 * $secondsInAMinute;
$secondsInADay = 24 * $secondsInAnHour;
// extract days
$days = floor($inputSeconds / $secondsInADay);
// extract hours
$hourSeconds = $inputSeconds % $secondsInADay;
$hours = floor($hourSeconds / $secondsInAnHour);
// extract minutes
$minuteSeconds = $hourSeconds % $secondsInAnHour;
$minutes = floor($minuteSeconds / $secondsInAMinute);
// extract the remaining seconds
$remainingSeconds = $minuteSeconds % $secondsInAMinute;
$seconds = ceil($remainingSeconds);
// return the final array
$obj = array(
'd' => (int) $days,
'h' => (int) $hours,
'm' => (int) $minutes,
's' => (int) $seconds,
);
return $obj;
}
I have the following in my .bash_profile:
function mark {
export $1=`pwd`;
}
so anytime I want to remember a directory, I can just type, e.g. mark there .
Then when I want to go back to that location, I just type cd $there
EDIT: added a new example for ggplot2 at the end
See ?plotmath for the different mathematical operations in R
You should be able to use expression without paste. If you use the tilda (~) symbol within the expression function it will assume there is a space between the characters, or you could use the * symbol and it won't put a space between the arguments
Sometimes you will need to change the margins in you're putting superscripts on the y-axis.
par(mar=c(5, 4.3, 4, 2) + 0.1)
plot(1:10, xlab = expression(xLab ~ x^2 ~ m^-2),
ylab = expression(yLab ~ y^2 ~ m^-2),
main="Plot 1")
plot(1:10, xlab = expression(xLab * x^2 * m^-2),
ylab = expression(yLab * y^2 * m^-2),
main="Plot 2")
plot(1:10, xlab = expression(xLab ~ x^2 * m^-2),
ylab = expression(yLab ~ y^2 * m^-2),
main="Plot 3")
Hopefully you can see the differences between plots 1, 2 and 3 with the different uses of the ~ and * symbols. An extra note, you can use other symbols such as plotting the degree symbol for temperatures for or mu, phi. If you want to add a subscript use the square brackets.
plot(1:10, xlab = expression('Your x label' ~ mu[3] * phi),
ylab = expression("Temperature (" * degree * C *")"))
Here is a ggplot example using expression with a nonsense example
require(ggplot2)
Or if you have the pacman library installed you can use p_load to automatically download and load and attach add-on packages
# require(pacman)
# p_load(ggplot2)
data = data.frame(x = 1:10, y = 1:10)
ggplot(data, aes(x,y)) + geom_point() +
xlab(expression(bar(yourUnits) ~ g ~ m^-2 ~ OR ~ integral(f(x)*dx, a,b))) +
ylab(expression("Biomass (g per" ~ m^3 *")")) + theme_bw()
I, too, have need for this! My situation involves comparing actuals with budget for cost centers, where expenses may have been mis-applied and therefore need to be re-allocated to the correct cost center so as to match how they were budgeted. It is very time consuming to try and scan row-by-row to see if each expense item has been correctly allocated. I decided that I should apply conditional formatting to highlight any cells where the actuals did not match the budget. I set up the conditional formatting to change the background color if the actual amount under the cost center did not match the budgeted amount.
Here's what I did:
Start in cell A1 (or the first cell you want to have the formatting). Open the Conditional Formatting dialogue box and select Apply formatting based on a formula. Then, I wrote a formula to compare one cell to another to see if they match:
=A1=A50
If the contents of cells A1 and A50 are equal, the conditional formatting will be applied. NOTICE: no $$, so the cell references are RELATIVE! Therefore, you can copy the formula from cell A1 and PasteSpecial (format). If you only click on the cells that you reference as you write your conditional formatting formula, the cells are by default locked, so then you wouldn't be able to apply them anywhere else (you would have to write out a new rule for each line- YUK!)
What is really cool about this is that if you insert rows under the conditionally formatted cell, the conditional formatting will be applied to the inserted rows as well!
Something else you could also do with this: Use ISBLANK if the amounts are not going to be exact matches, but you want to see if there are expenses showing up in columns where there are no budgeted amounts (i.e., BLANK) .
This has been a real time-saver for me. Give it a try and enjoy!
The problem is that multiprocessing must pickle things to sling them among processes, and bound methods are not picklable. The workaround (whether you consider it "easy" or not;-) is to add the infrastructure to your program to allow such methods to be pickled, registering it with the copy_reg standard library method.
For example, Steven Bethard's contribution to this thread (towards the end of the thread) shows one perfectly workable approach to allow method pickling/unpickling via copy_reg
.
Try out this step: https://www.eclipse.org/forums/index.php/t/636348/
Go to
Project -> Properties -> C/C++ General -> Preprocessor Include Paths, Macros, etc. -> Providers
1) Update Devise so that it can handle Rails 4.0 by adding this line to your application's Gemfile:
gem 'devise', '3.0.0.rc'
Then execute:
$ bundle
2) Add the old functionality of attr_accessible
again to rails 4.0
Try to use attr_accessible
and don't comment this out.
Add this line to your application's Gemfile:
gem 'protected_attributes'
Then execute:
$ bundle
The parent div (I assume the outermost div) is display: block
and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block
is probably what you are going for:
The problem is you defined myList
from main.py
, but subfile.py
needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file settings.py
. This file is responsible for defining globals and initializing them:
# settings.py
def init():
global myList
myList = []
Next, your subfile
can import globals:
# subfile.py
import settings
def stuff():
settings.myList.append('hey')
Note that subfile
does not call init()
— that task belongs to main.py
:
# main.py
import settings
import subfile
settings.init() # Call only once
subfile.stuff() # Do stuff with global var
print settings.myList[0] # Check the result
This way, you achieve your objective while avoid initializing global variables more than once.
must please see guys that the error is in the cv2.imread() .Give the right path of the image. and firstly, see if your system loads the image or not. this can be checked first by simple load of image using cv2.imread(). after that ,see this code for the face detection
import numpy as np
import cv2
cascPath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site- packages/cv2/data/haarcascade_frontalface_default.xml"
eyePath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site-packages/cv2/data/haarcascade_eye.xml"
smilePath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site-packages/cv2/data/haarcascade_smile.xml"
face_cascade = cv2.CascadeClassifier(cascPath)
eye_cascade = cv2.CascadeClassifier(eyePath)
smile_cascade = cv2.CascadeClassifier(smilePath)
img = cv2.imread('WhatsApp Image 2020-04-04 at 8.43.18 PM.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Here, cascPath ,eyePath ,smilePath should have the right actual path that's picked up from lib/python3.7/site-packages/cv2/data here this path should be to picked up the haarcascade files
Apparently you can use this trick.
<title> My title</title>
That icon-alike is actually a text.
I'm using this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myUrl);
System.Diagnostics.Stopwatch timer = new Stopwatch();
timer.Start();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
statusCode = response.StatusCode.ToString();
response.Close();
timer.Stop();
Use: "%.2f"
or variations on that.
See the POSIX spec for an authoritative specification of the printf()
format strings. Note that it separates POSIX extras from the core C99 specification. There are some C++ sites which show up in a Google search, but some at least have a dubious reputation, judging from comments seen elsewhere on SO.
Since you're coding in C++, you should probably be avoiding printf()
and its relatives.
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
vehicle[] car = new vehicle[N];
I had a file named mysql.py in the folder. That's why it gave an error because it tried to call it in the import process.
import mysql.connector
I solved the problem by changing the file name.
Most minimal way to achieve this (that I know of):
.text-monospace
to all texts in in the card.Add .text-truncate
in the card's title and or other texts. This forces texts to a single line. Making the cards have same height.
I just wanted to share some of my results...
I have text files, which apparently came from a Linux system, so I only have a vbLF
/Chr(10)
at the end of each line and not vbCR
/Chr(13)
.
Note 1:
- This meant that the
Line Input
method would read in the entire file, instead of just one line at a time.
From my research testing small (152KB) & large (2778LB) files, both on and off the network I found the following:
Open FileName For Input: Line Input
was the slowest (See Note 1 above)
Open FileName For Binary Access Read: Input
was the fastest for reading the whole file
FSO.OpenTextFile: ReadLine
was fast, but a bit slower then Binary Input
Note 2:
If I just needed to check the file header (first 1-2 lines) to check if I had the proper file/format, then
FSO.OpenTextFile
was the fastest, followed very closely byBinary Input
.The drawback with the
Binary Input
is that you have to know how many characters you want to read.- On normal files,
Line Input
would also be a good option as well, but I couldn't test due to Note 1.
Note 3:
- Obviously, the files on the network showed the largest difference in read speed. They also showed the greatest benefit from reading the file a second time (although there are certainly memory buffers that come into play here).
You can't compare object data like this:s1.getParent() == s2
- this will compare the object references. You should override equals function
for Foo class and then compare them like this s1.getParent().equals(s2)
Java has mainly three sub categories :
where core java is the first and basic step of all to start or learn java from beginning.
Just remove the comma like this:
<article class="column wrapper">
ECB should not be used if encrypting more than one block of data with the same key.
CBC, OFB and CFB are similar, however OFB/CFB is better because you only need encryption and not decryption, which can save code space.
CTR is used if you want good parallelization (ie. speed), instead of CBC/OFB/CFB.
XTS mode is the most common if you are encoding a random accessible data (like a hard disk or RAM).
OCB is by far the best mode, as it allows encryption and authentication in a single pass. However there are patents on it in USA.
The only thing you really have to know is that ECB is not to be used unless you are only encrypting 1 block. XTS should be used if you are encrypting randomly accessed data and not a stream.
Right click on the project in which you want to put jar file. A window will open like this
Click on the AddExternal Jars there you can give the path to that jar file
.list-inline class in bootstrap is a Inline Unordered List.
If you want to create a horizontal menu using ordered or unordered list you need to place all list items in a single line i.e. side by side. You can do this by simply applying the class
<div class="list-inline">
<a href="#" class="list-inline-item">First item</a>
<a href="#" class="list-inline-item">Secound item</a>
<a href="#" class="list-inline-item">Third item</a>
</div>
Because you are passing three arguments to a four arguments method. Also, you are not using the passed closure.
If you want to specify the operations to be made on top of the source
contents, then use a closure. It would be something like this:
def copyAndReplaceText(source, dest, closure){
dest.write(closure( source.text ))
}
// And you can keep your usage as:
copyAndReplaceText(source, dest){
it.replaceAll('Visa', 'Passport!!!!')
}
If you will always swap strings, pass both, as your method signature already states:
def copyAndReplaceText(source, dest, targetText, replaceText){
dest.write(source.text.replaceAll(targetText, replaceText))
}
copyAndReplaceText(source, dest, 'Visa', 'Passport!!!!')
Not only can you, but you have to make a special effort not to if you don't want to. :-)
When the browser encounters a classic script
tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write
calls to output markup that the parser should handle).
That's the default behavior, but you have a few options for delaying script execution:
Use JavaScript modules. A type="module"
script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:
<script type="module" src="./my-code.js"></script>
<!-- Or -->
<script type="module">
// Your code here
</script>
The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)
This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.
Use the defer
attribute on a classic script tag:
<script defer src="./my-code.js"></script>
As with the module, the code in my-code.js
will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer
doesn't work with inline script content, only with external files referenced via src
.
I don't think it's what you want, but you can use the async
attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module"
tag, or use it instead of defer
on a classic script
tag.
Put the script
tag at the end of the document, just prior to the closing </body>
tag:
<!doctype html>
<html>
<!-- ... -->
<body>
<!-- The document's HTML goes here -->
<script type="module" src="./my-code.js"></script><!-- Or inline script -->
</body>
</html>
That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.
It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script
tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer
are better options.
The spec has a useful diagram showing a raw script
tag, defer
, async
, type="module"
, and type="module" async
and the timing of when the JavaScript code is fetched and run:
Here's an example of the default behavior, a raw script
tag:
.found {_x000D_
color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script>_x000D_
if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
}_x000D_
document.querySelectorAll("p").forEach(p => {_x000D_
p.classList.add("found");_x000D_
});_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
(See my answer here for details around that NodeList
code.)
When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.
In contrast, here's a type="module"
script:
.found {_x000D_
color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
document.querySelectorAll("p").forEach(p => {_x000D_
p.classList.add("found");_x000D_
});_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer
script
with external content (but not inline content).
(There was no need for the NodeList
check there because any modern browser supporting modules already has forEach
on NodeList
.)
In this modern world, there's no real value to the DOMContentLoaded
event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer
. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script
was in the head
instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body
, again back in the day.
public class EMView extends Activity {
ImageView img,img1;
int column_index;
Intent intent=null;
// Declare our Views, so we can access them later
String logo,imagePath,Logo;
Cursor cursor;
//YOU CAN EDIT THIS TO WHATEVER YOU WANT
private static final int SELECT_PICTURE = 1;
String selectedImagePath;
//ADDED
String filemanagerstring;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img= (ImageView)findViewById(R.id.gimg1);
((Button) findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}
//UPDATED
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
//OI FILE Manager
filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
img.setImageURI(selectedImageUri);
imagePath.getBytes();
TextView txt = (TextView)findViewById(R.id.title);
txt.setText(imagePath.toString());
Bitmap bm = BitmapFactory.decodeFile(imagePath);
// img1.setImageBitmap(bm);
}
}
}
//UPDATED!
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
return cursor.getString(column_index);
}
}
Though @Wayne G. Dunn has given in code. Here is the place when you don't want to code. And uncheck to disable the background refresh.
One thing json
cannot do is dict
indexed with numerals. The following snippet
import json
dictionary = dict({0:0, 1:5, 2:10})
serialized = json.dumps(dictionary)
unpacked = json.loads(serialized)
print(unpacked[0])
will throw
KeyError: 0
Because keys are converted to strings. cPickle
preserves the numeric type and the unpacked dict
can be used right away.
Your webapp has servletcontainer specific libraries like servlet-api.jar file in its /WEB-INF/lib. This is not right.
Remove them all.
The /WEB-INF/lib should contain only the libraries specific to the webapp, not to the servletcontainer. The servletcontainer (like Tomcat) is the one who should already provide the servletcontainer specific libraries.
If you supply libraries from an arbitrary servletcontainer of a different make/version, you'll run into this kind of problems because your webapp wouldn't be able to run on a servletcontainer of a different make/version than where those libraries are originated from.
How to solve: In Eclipse Right click on the project in eclipse Properties -> Java Build Path -> Add library -> Server Runtime Library -> Apache Tomcat
Im Maven Project:-
add follwing line in pom.xml file
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${default.javax.servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${default.javax.servlet.jsp.version}</version>
<scope>provided</scope>
</dependency>
Well if you're happy printing it in decimal, you could just make it positive by masking:
int positive = bytes[i] & 0xff;
If you're printing out a hash though, it would be more conventional to use hex. There are plenty of other questions on Stack Overflow addressing converting binary data to a hex string in Java.
I am not saying that you have to abandon PHP, but you need different technologies here.
Let's start off simple (without Akamai :-)) and think about the implications here. Video, chat, etc. - it's all client-side in the beginning. The user has a webcam, you want to grab the signal somehow and send it to the server. There is no PHP so far.
I know that Flash supports this though (check this tutorial on webcams and flash) so you could use Flash to transport the content to the server. I think if you'll stay with Flash, then Flex (flex and webcam tutorial) is probably a good idea to look into.
So those are just the basics, maybe it gives you an idea of where you need to research because obviously this won't give you a full video chat inside your app yet. For starters, you will need some sort of way to record the streams and re-publish them so others see other people from the chat, etc..
I'm also not sure how much traffic and bandwidth this is gonna consume though and generally, you will need way more than a Stackoverflow question to solve this issue. Best would be to do a full spec of your app and then hire some people to help you build it.
HTH!
Avast Antivirus is sensing emulator-arm.exe as a thread and blocking from some reasons. When you add it exclusions in Virus Chest page with right-click -> "restore and add to exclusions" it's not solved in future runnings. To solve this permanently in Avast 2015 :
Settings ->
Active Protection ->
File System Shield ->
Customize ->
Exclusions then add thread as a exclusion . And then press ok.
Refer to the ASP.NET page lifecycle to help find the right event to override. It really depends what you want to do. But yes, there is an unload event.
protected override void OnUnload(EventArgs e)
{
base.OnUnload(e);
// your code
}
But just remember (from the above link): During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.
Abstration which hide internal detail to outside world for example you create a class(like calculator one of the class) but for end use you provide object of class ,With the help of object they will play and perform operation ,He does't aware what type of mechanism use internally .Object of class in abstract form .
Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.For example class calculator which contain private methods getAdd,getMultiply .
Mybe above answer will help you to understand the concept .
I've been verifying calls in the same manner - I believe it is the right way to do it.
mockSomething.Verify(ms => ms.Method(
It.IsAny<int>(),
It.Is<MyObject>(mo => mo.Id == 5 && mo.description == "test")
), Times.Once());
If your lambda expression becomes unwieldy, you could create a function that takes MyObject
as input and outputs true
/false
...
mockSomething.Verify(ms => ms.Method(
It.IsAny<int>(),
It.Is<MyObject>(mo => MyObjectFunc(mo))
), Times.Once());
private bool MyObjectFunc(MyObject myObject)
{
return myObject.Id == 5 && myObject.description == "test";
}
Also, be aware of a bug with Mock where the error message states that the method was called multiple times when it wasn't called at all. They might have fixed it by now - but if you see that message you might consider verifying that the method was actually called.
EDIT: Here is an example of calling verify multiple times for those scenarios where you want to verify that you call a function for each object in a list (for example).
foreach (var item in myList)
mockRepository.Verify(mr => mr.Update(
It.Is<MyObject>(i => i.Id == item.Id && i.LastUpdated == item.LastUpdated),
Times.Once());
Same approach for setup...
foreach (var item in myList) {
var stuff = ... // some result specific to the item
this.mockRepository
.Setup(mr => mr.GetStuff(item.itemId))
.Returns(stuff);
}
So each time GetStuff is called for that itemId, it will return stuff specific to that item. Alternatively, you could use a function that takes itemId as input and returns stuff.
this.mockRepository
.Setup(mr => mr.GetStuff(It.IsAny<int>()))
.Returns((int id) => SomeFunctionThatReturnsStuff(id));
One other method I saw on a blog some time back (Phil Haack perhaps?) had setup returning from some kind of dequeue object - each time the function was called it would pull an item from a queue.
I think if you think it from the point of CALayer
, everything is more clear.
Frame is not really a distinct property of the view or layer at all, it is a virtual property, computed from the bounds, position(UIView
's center), and transform.
So basically how the layer/view layouts is really decided by these three property(and anchorPoint), and either of these three property won't change any other property, like changing transform doesn't change bounds.
I got this issue for a console Application.
In my case i just changed the Platform Target to "Any CPU" which you can see when you right click your solution and click on properties , you will find a Tab "Build" click on it, you will see "Platform target:" change it to "Any CPU", which will solve your issue
NestedCaveats solution worked for me.
Imported my .dll files before importing torch and gpytorch, and all went smoothly.
So I just want to add that its not just importing pytorch but I can confirm that torch and gpytorch have this issue as well. I'd assume it covers any other torch-related libraries.
As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:
xlrd has explicitly removed support for anything other than xls files.
In your case, the solution is to:
openpyxl
: https://openpyxl.readthedocs.io/en/stable/df1 = pd.read_excel(
os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
engine='openpyxl',
)
let the_string = "Swift"
let resultString = "\(the_string) is a new Programming Language"
Yes, the syntax is accurate and it should be fine.
Here is the SQL Fiddle Demo I created for your particular case
create table sample2
(
id int primary key,
created_date date,
data varchar(10)
)
insert into sample2 values (1,'2012-01-01','testing');
And here is how to select the data
SELECT Created_Date
FROM sample2
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())
First you have to sort
the dataframe
by the count
column max
to min
if it's not sorted that way already. In your post, it is in the right order already but I will sort
it anyways:
dataframe.sort_index(by='count', ascending=[False])
col count
0 apple 5
1 sausage 2
2 banana 2
3 cheese 1
Then you can output the col
column to a list:
dataframe['col'].tolist()
['apple', 'sausage', 'banana', 'cheese']
For .NET Core 2.0, things have changed a little bit. The startup constructor takes a Configuration object as a parameter, So using the ConfigurationBuilder
is not required. Here is mine:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<StorageOptions>(Configuration.GetSection("AzureStorageConfig"));
}
My POCO is the StorageOptions
object mentioned at the top:
namespace FictionalWebApp.Models
{
public class StorageOptions
{
public String StorageConnectionString { get; set; }
public String AccountName { get; set; }
public String AccountKey { get; set; }
public String DefaultEndpointsProtocol { get; set; }
public String EndpointSuffix { get; set; }
public StorageOptions() { }
}
}
And the configuration is actually a subsection of my appsettings.json
file, named AzureStorageConfig
:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=fictionalwebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"AzureStorageConfig": {
"AccountName": "fictionalwebapp",
"AccountKey": "Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==",
"DefaultEndpointsProtocol": "https",
"EndpointSuffix": "core.windows.net",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=fictionalwebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
}
}
The only thing I'll add is that, since the constructor has changed, I haven't tested whether something extra needs to be done for it to load appsettings.<environmentname>.json
as opposed to appsettings.json
.
Do not use primitives in your Entity classes, use instead their respective wrappers. That will fix this problem.
Out of your Entity classes you can use the != null validation for the rest of your code flow.
unittest comes with the standard library, but I would recomend you nosetests.
"nose extends unittest to make testing easier."
I would also recomend you pylint
"analyzes Python source code looking for bugs and signs of poor quality."
The simplest way is to create a VBA macro that wraps that function, like so:
Function UserNameWindows() As String
UserName = Environ("USERNAME")
End Function
Then call it from the cell:
=UserNameWindows()
See this article for more details, and other ways.
Assuming a simple table:
CREATE TABLE dbo.foo(ID INT IDENTITY(1,1), name SYSNAME);
We can capture IDENTITY
values in a table variable for further consumption.
DECLARE @IDs TABLE(ID INT);
-- minor change to INSERT statement; add an OUTPUT clause:
INSERT dbo.foo(name)
OUTPUT inserted.ID INTO @IDs(ID)
SELECT N'Fred'
UNION ALL
SELECT N'Bob';
SELECT ID FROM @IDs;
The nice thing about this method is (a) it handles multi-row inserts (SCOPE_IDENTITY()
only returns the last value) and (b) it avoids this parallelism bug, which can lead to wrong results, but so far is only fixed in SQL Server 2008 R2 SP1 CU5.
For those, like me, who did not have the possibility to use angular directive and were "stuck" outside of the angular scope, here is something that might help you.
After hours searching on the web and on the angular doc, I have created a class that compiles HTML, place it inside a targets, and binds it to a scope ($rootScope
if there is no $scope
for that element)
/**
* AngularHelper : Contains methods that help using angular without being in the scope of an angular controller or directive
*/
var AngularHelper = (function () {
var AngularHelper = function () { };
/**
* ApplicationName : Default application name for the helper
*/
var defaultApplicationName = "myApplicationName";
/**
* Compile : Compile html with the rootScope of an application
* and replace the content of a target element with the compiled html
* @$targetDom : The dom in which the compiled html should be placed
* @htmlToCompile : The html to compile using angular
* @applicationName : (Optionnal) The name of the application (use the default one if empty)
*/
AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);
$injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
//Get the scope of the target, use the rootScope if it does not exists
var $scope = $targetDom.html(htmlToCompile).scope();
$compile($targetDom)($scope || $rootScope);
$rootScope.$digest();
}]);
}
return AngularHelper;
})();
It covered all of my cases, but if you find something that I should add to it, feel free to comment or edit.
Hope it will help.
In 2017 do so
_.chain(data)
.groupBy("color")
.toPairs()
.map(item => _.zipObject(["color", "users"], item))
.value();
Use on :
$('#registered_participants').on('click', '.new_participant_form', function() {
So that the click is delegated to any element in #registered_participants
having the class new_participant_form
, even if it's added after you bound the event handler.
None of these were working for me, couldn't delete or disconnect current users. Also couldn't see any active connections to the DB. Restarting SQL Server (Right click and select Restart) allowed me to do it.
You can also use Windows PowerShell with the following command:
if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
[System.Diagnostics.EventLog]::CreateEventSource($source, "Application")
}
Make sure to check that the source does not exist before calling CreateEventSource, otherwise it will throw an exception.
For more info:
You could use a @HostListener decorator. Works with Angular 4 and up.
import { HostListener } from '@angular/core';
@HostListener("window:scroll", []) onWindowScroll() {
// do some stuff here when the window is scrolled
const verticalOffset = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop || 0;
}
This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.
Summary compiled from the above document:
* = contains the feature SQLEXPR SQLEXPRWT SQLEXPRADV ---------------------------------------------------------------------------- > SQL Server Core * * * > SQL Server Management Studio - * * > Distributed Replay – Admin Tool - * * > LocalDB - * * > SQL Server Data Tools (SSDT) - - * > Full-text and semantic search - - * > Specification of language in query - - * > some of Reporting services features - - *
The Go blog: Go maps in action has an excellent explanation.
When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. Since Go 1 the runtime randomizes map iteration order, as programmers relied on the stable iteration order of the previous implementation. If you require a stable iteration order you must maintain a separate data structure that specifies that order.
Here's my modified version of example code: http://play.golang.org/p/dvqcGPYy3-
package main
import (
"fmt"
"sort"
)
func main() {
// To create a map as input
m := make(map[int]string)
m[1] = "a"
m[2] = "c"
m[0] = "b"
// To store the keys in slice in sorted order
keys := make([]int, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
sort.Ints(keys)
// To perform the opertion you want
for _, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}
}
Output:
Key: 0 Value: b
Key: 1 Value: a
Key: 2 Value: c
Here is a Github link to a lightweight and very easy to integrate library that enables you to play with borders as you want for any widget you want, simply based on a FrameLayout widget.
Here is a quick sample code for you to see how easy it is, but you will find more information on the link.
<com.khandelwal.library.view.BorderFrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:leftBorderColor="#00F0F0"
app:leftBorderWidth="10dp"
app:topBorderColor="#F0F000"
app:topBorderWidth="15dp"
app:rightBorderColor="#F000F0"
app:rightBorderWidth="20dp"
app:bottomBorderColor="#000000"
app:bottomBorderWidth="25dp" >
</com.khandelwal.library.view.BorderFrameLayout>
So, if you don't want borders on bottom, delete the two lines about bottom in this custom widget, and that's done.
And no, I'm neither the author of this library nor one of his friend ;-)
Mostly the image is not displayed because you URL contains spaces. In your case you almost did everything correct. Except one thing - you have not added single quotes like you do if you specify background-image in css I.e.
.bg-img { \/ \/
background-image: url('http://...');
}
To do so escape quot character in HTML via \'
\/ \/
<div [ngStyle]="{'background-image': 'url(\''+ item.color.catalogImageLink + '\')'}"></div>
If you are using MacOS use:
sudo cp /usr/local/etc/openssl/cert.pem /etc/ssl/certs
after this Trust anchor not found error disappears
The problem is that .form-control
class renders like a DIV
element which according to the normal-flow-of-the-page
renders on a new line.
One way of fixing issues like this is to use display:inline
property. So, create a custom CSS
class with display:inline
and attach it to your component with a .form-control
class. You have to have a width
for your component as well.
There are other ways of handling this issue (like arranging your form-control
components inside any of the .col
classes), but the easiest way is to just make your .form-control
an inline
element (the way a span
would render)
If you have a for loop such as the one below.
Change @item.StartDate to @item.StartDate.Value.ToShortDateString()
This will remove the time just in case you can't annotate your property in the model like in my case.
<table>
<tr>
<th>Type</th>
<th>Start Date</th>
</tr>
@foreach (var item in Model.TestList) {
<tr>
<td>@item.TypeName</td>
<td>@item.StartDate.Value.ToShortDateString()</td>
</tr>
}
</table>
To show the dots instead of the password set the PasswordTransformationMethod:
yourEditText.setTransformationMethod(new PasswordTransformationMethod());
of course you can set this by default in your edittext element in the xml layout with
android:password
To re-show the readable password, just pass null as transformation method:
yourEditText.setTransformationMethod(null);
If the icon is from Font Awesome (https://fontawesome.com/icons/) then you could tap into the color css property to change it's background.
fb-icon{
color:none;
}
fb-icon:hover{
color:#0000ff;
}
This is irrespective of the color it had. So you could use an entirely different color in its usual state and define another in its active state.
I always use this code while converting Date
to String
. (Swift 3)
extension Date
{
func toString( dateFormat format : String ) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
and call like this . .
let today = Date()
today.toString(dateFormat: "dd-MM")
var dict = File.ReadLines("test.txt")
.Where(line => !string.IsNullOrWhitespace(line))
.Select(line => line.Split(new char[] { '=' }, 2, 0))
.ToDictionary(parts => parts[0], parts => parts[1]);
or
enter code here
line="[email protected][email protected]";
string[] tokens = line.Split(new char[] { '=' }, 2, 0);
ans:
tokens[0]=to
token[1][email protected][email protected]
You can use the finish
command.
finish
: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated asfin
.
(See 5.2 Continuing and Stepping.)
I would go with Larry K's solution, but you can also set the display to inline-block if you want the benefits of both block and inline elements.
You can do this in the div tag by inserting:
style="display:inline-block;"
Or in a CSS stylesheet with this method:
div { display:inline-block; }
Hope it helps, but as earlier mentioned, I would personally go for Larry K's solution ;-)
You can use JavaScript if you're familiar with, like that:
swfobject.embedSWF("filename.swf", "Title", "width", "height", "9.0.0");
--the 9.0.0 is the flash version.
Or you can use the <object>
tag of HTML5.
Based on robertc's answer:
To get proper conversion from colored image to grayscale image instead of using matrix like this:
0.3333 0.3333 0.3333 0 0
0.3333 0.3333 0.3333 0 0
0.3333 0.3333 0.3333 0 0
0 0 0 1 0
You should use conversion matrix like this:
0.299 0.299 0.299 0
0.587 0.587 0.587 0
0.112 0.112 0.112 0
0 0 0 1
This should work fine for all the types of images based on RGBA (red-green-blue-alpha) model.
For more information why you should use matrix I posted more likely that the robertc's one check following links:
VERSION NOTE: You must be using SQL Server 2005 or greater with Compatibility Level set to 90 or greater for this solution.
See this MSDN article for the first example of creating a user-defined aggregate function that concatenates a set of string values taken from a column in a table.
My humble recommendation would be to leave out the appended comma so you can use your own ad-hoc delimiter, if any.
Referring to the C# version of Example 1:
change: this.intermediateResult.Append(value.Value).Append(',');
to: this.intermediateResult.Append(value.Value);
And
change: output = this.intermediateResult.ToString(0, this.intermediateResult.Length - 1);
to: output = this.intermediateResult.ToString();
That way when you use your custom aggregate, you can opt to use your own delimiter, or none at all, such as:
SELECT dbo.CONCATENATE(column1 + '|') from table1
NOTE: Be careful about the amount of the data you attempt to process in your aggregate. If you try to concatenate thousands of rows or many very large datatypes you may get a .NET Framework error stating "[t]he buffer is insufficient."
Although you might not have a technical advantage to choosing one format over the other, you should be aware of some important differences between the two syntaxes. One obvious difference is that ViewBag works only when the key you’re accessing is a valid C# identifi er. For example, if you place a value in ViewData["Key With Spaces"], you can’t access that value using ViewBag because the code won’t compile. Another key issue to consider is that you cannot pass in dynamic values as parameters to extension methods. The C# compiler must know the real type of every parameter at compile time in order to choose the correct extension method. If any parameter is dynamic, compilation will fail. For example, this code will always fail: @Html.TextBox("name", ViewBag.Name). To work around this, either use ViewData["Name"] or cast the va
Consider installing the more_itertools
package.
> pip install more_itertools
It ships with an implementation for flatten
(source, from the itertools recipes):
import more_itertools
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(more_itertools.flatten(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
Note: as mentioned in the docs, flatten
requires a list of lists. See below on flattening more irregular inputs.
As of version 2.4, you can flatten more complicated, nested iterables with more_itertools.collapse
(source, contributed by abarnet).
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(more_itertools.collapse(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
lst = [[1, 2, 3], [[4, 5, 6]], [[[7]]], 8, 9] # complex nesting
list(more_itertools.collapse(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
Use a long datatype.
You can use click touchend
,
example:
$('a').on('click touchend', function() {
var linkToAffect = $(this);
var linkToAffectHref = linkToAffect.attr('href');
window.location = linkToAffectHref;
});
Above example will affect all links on touch devices.
If you want to target only specific links, you can do this by setting a class on them, ie:
HTML:
<a href="example.html" class="prevent-extra-click">Prevent extra click on touch device</a>
Jquery:
$('a.prevent-extra-click').on('click touchend', function() {
var linkToAffect = $(this);
var linkToAffectHref = linkToAffect.attr('href');
window.location = linkToAffectHref;
});
Cheers,
Jeroen
I solved the error by modifying the following property in hibernate.cfg.xml
<property name="hibernate.hbm2ddl.auto">validate</property>
Earlier, the table was getting deleted each time I ran the program and now it doesnt, as hibernate only validates the schema and does not affect changes to it.
As far as I know you can also change from validate to update e.g.:
<property name="hibernate.hbm2ddl.auto">update</property>
console.log("your message here");
working for me.. i'm searching for this.. i used Firefox. here is my Script.
$('document').ready(function() {
console.log('all images are loaded');
});
works in Firefox and Chrome.
This is fixed in Hamcrest 1.3. The below code compiles and does not generate any warnings:
// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, is(not(empty())));
But if you have to use older version - instead of bugged empty()
you could use:
hasSize(greaterThan(0))
(import static org.hamcrest.number.OrderingComparison.greaterThan;
or
import static org.hamcrest.Matchers.greaterThan;
)
Example:
// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, hasSize(greaterThan(0)));
The most important thing about above solutions is that it does not generate any warnings. The second solution is even more useful if you would like to estimate minimum result size.
You can implement a SoapExtension that logs the full request and response to a log file. You can then enable the SoapExtension in the web.config, which makes it easy to turn on/off for debugging purposes. Here is an example that I have found and modified for my own use, in my case the logging was done by log4net but you can replace the log methods with your own.
public class SoapLoggerExtension : SoapExtension
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Stream oldStream;
private Stream newStream;
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
return null;
}
public override object GetInitializer(Type serviceType)
{
return null;
}
public override void Initialize(object initializer)
{
}
public override System.IO.Stream ChainStream(System.IO.Stream stream)
{
oldStream = stream;
newStream = new MemoryStream();
return newStream;
}
public override void ProcessMessage(SoapMessage message)
{
switch (message.Stage)
{
case SoapMessageStage.BeforeSerialize:
break;
case SoapMessageStage.AfterSerialize:
Log(message, "AfterSerialize");
CopyStream(newStream, oldStream);
newStream.Position = 0;
break;
case SoapMessageStage.BeforeDeserialize:
CopyStream(oldStream, newStream);
Log(message, "BeforeDeserialize");
break;
case SoapMessageStage.AfterDeserialize:
break;
}
}
public void Log(SoapMessage message, string stage)
{
newStream.Position = 0;
string contents = (message is SoapServerMessage) ? "SoapRequest " : "SoapResponse ";
contents += stage + ";";
StreamReader reader = new StreamReader(newStream);
contents += reader.ReadToEnd();
newStream.Position = 0;
log.Debug(contents);
}
void ReturnStream()
{
CopyAndReverse(newStream, oldStream);
}
void ReceiveStream()
{
CopyAndReverse(newStream, oldStream);
}
public void ReverseIncomingStream()
{
ReverseStream(newStream);
}
public void ReverseOutgoingStream()
{
ReverseStream(newStream);
}
public void ReverseStream(Stream stream)
{
TextReader tr = new StreamReader(stream);
string str = tr.ReadToEnd();
char[] data = str.ToCharArray();
Array.Reverse(data);
string strReversed = new string(data);
TextWriter tw = new StreamWriter(stream);
stream.Position = 0;
tw.Write(strReversed);
tw.Flush();
}
void CopyAndReverse(Stream from, Stream to)
{
TextReader tr = new StreamReader(from);
TextWriter tw = new StreamWriter(to);
string str = tr.ReadToEnd();
char[] data = str.ToCharArray();
Array.Reverse(data);
string strReversed = new string(data);
tw.Write(strReversed);
tw.Flush();
}
private void CopyStream(Stream fromStream, Stream toStream)
{
try
{
StreamReader sr = new StreamReader(fromStream);
StreamWriter sw = new StreamWriter(toStream);
sw.WriteLine(sr.ReadToEnd());
sw.Flush();
}
catch (Exception ex)
{
string message = String.Format("CopyStream failed because: {0}", ex.Message);
log.Error(message, ex);
}
}
}
[AttributeUsage(AttributeTargets.Method)]
public class SoapLoggerExtensionAttribute : SoapExtensionAttribute
{
private int priority = 1;
public override int Priority
{
get { return priority; }
set { priority = value; }
}
public override System.Type ExtensionType
{
get { return typeof (SoapLoggerExtension); }
}
}
You then add the following section to your web.config where YourNamespace and YourAssembly point to the class and assembly of your SoapExtension:
<webServices>
<soapExtensionTypes>
<add type="YourNamespace.SoapLoggerExtension, YourAssembly"
priority="1" group="0" />
</soapExtensionTypes>
</webServices>
I had a similar problem with gitlab. It turns out I had restricted the users that are allowed to login via ssh. This won't affect github users, but in case people end up here for gitlab (and the like) issues, ensure you add git
to the AllowUsers
setting in /etc/ssh/sshd_config
:
# Authentication:
LoginGraceTime 120
PermitRootLogin no
StrictModes yes
AllowUsers batman git
I use this method in my css file
@font-face {
font-family: FontName1;
src: url("fontname1.eot"); /* IE */
src: local('FontName1'), url('fontname1.ttf') format('truetype'); /* others */
}
@font-face {
font-family: FontName2;
src: url("fontname1.eot"); /* IE */
src: local('FontName2'), url('fontname2.ttf') format('truetype'); /* others */
}
@font-face {
font-family: FontName3;
src: url("fontname1.eot"); /* IE */
src: local('FontName3'), url('fontname3.ttf') format('truetype'); /* others */
}
If you have a single Buffer
you can use its toString
method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8
if you don't provide a parameter, but I've explicitly set the encoding in this example.
var req = http.request(reqOptions, function(res) {
...
res.on('data', function(chunk) {
var textChunk = chunk.toString('utf8');
// process utf8 text chunk
});
});
If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8
-character may be contained in the first Buffer
(chunk) and the second byte in the second Buffer
then you should use a StringDecoder
. :
var StringDecoder = require('string_decoder').StringDecoder;
var req = http.request(reqOptions, function(res) {
...
var decoder = new StringDecoder('utf8');
res.on('data', function(chunk) {
var textChunk = decoder.write(chunk);
// process utf8 text chunk
});
});
This way bytes of incomplete characters are buffered by the StringDecoder
until all required bytes were written to the decoder.
No matter what we tried we couldn't manage to get the timeout below 21 seconds when the server we were checking was down.
To work around this we combined a TcpClient check to see if the domain was alive followed by a separate check to see if the URL was active
public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
try
{
//check the domain first
if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
{
//only now check the url itself
var request = System.Net.WebRequest.Create(aUrl);
request.Method = "HEAD";
request.Timeout = aTimeoutSeconds * 1000;
var response = (HttpWebResponse)request.GetResponse();
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
}
return false;
}
private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
try
{
using (TcpClient client = new TcpClient())
{
var result = client.BeginConnect(aDomain, 80, null, null);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));
if (!success)
{
return false;
}
// we have connected
client.EndConnect(result);
return true;
}
}
catch
{
}
return false;
}
Its simple :)
<link rel="icon" href="{{ asset('favicon.ico')}}" type="image/x-icon" />
NSData *data = [strChangetoJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
For example you have a NSString
with special characters in NSString
strChangetoJSON.
Then you can convert that string to JSON response using above code.
I used the command pattern that @jk. mentioned, adding a return type:
public interface Callable<I, O> {
public O call(I input);
}
From long to DateTime: new DateTime(long ticks)
From DateTime to long: DateTime.Ticks
Use setImmediate
if you want to queue the function behind whatever I/O event callbacks that are already in the event queue. Use process.nextTick
to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes.
So in a case where you're trying to break up a long running, CPU-bound job using recursion, you would now want to use setImmediate
rather than process.nextTick
to queue the next iteration as otherwise any I/O event callbacks wouldn't get the chance to run between iterations.
This is really old, but <font size="10">
would be about <p style= "font-size:55px">
I know this is old, but since Postgresql 9.3 there is an option to use a keyword "LATERAL" to use RELATED subqueries inside of JOINS, so the query from the question would look like:
SELECT
name, author_id, count(*), t.total
FROM
names as n1
INNER JOIN LATERAL (
SELECT
count(*) as total
FROM
names as n2
WHERE
n2.id = n1.id
AND n2.author_id = n1.author_id
) as t ON 1=1
GROUP BY
n1.name, n1.author_id
Assuming you have something like so:
public class MyFirstClass {
...
public ArrayList<Integer> myNumbers() {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(11);
numbers.add(3);
return(numbers);
}
...
}
You can call that method like so:
public class MySecondClass {
...
MyFirstClass m1 = new MyFirstClass();
List<Integer> myList = m1.myNumbers();
...
}
Since the method you are trying to call is not static, you will have to create an instance of the class which provides this method. Once you create the instance, you will then have access to the method.
Note, that in the code example above, I used this line: List<Integer> myList = m1.myNumbers();
. This can be changed by the following: ArrayList<Integer> myList = m1.myNumbers();
. However, it is usually recommended to program to an interface, and not to a concrete implementation, so my suggestion for the method you are using would be to do something like so:
public List<Integer> myNumbers() {
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(11);
numbers.add(3);
return(numbers);
}
This will allow you to assign the contents of that list to whatever implements the List
interface.
there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD')
and heredoc(<<<EOD)
strings
you can use both single quotes and double quotes inside heredoc string. Variables will be expanded just as double quotes.
nowdoc strings will not expand variables just like single quotes.
ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
Try <input type="number" step="any" />
It won't have validation problems and the arrows will have step of "1"
Constraint validation: When the element has an allowed value step, and the result of applying the algorithm to convert a string to a number to the string given by the element's value is a number, and that number subtracted from the step base is not an integral multiple of the allowed value step, the element is suffering from a step mismatch.
The following range control only accepts values in the range 0..1, and allows 256 steps in that range:
<input name=opacity type=range min=0 max=1 step=0.00392156863>
The following control allows any time in the day to be selected, with any accuracy (e.g. thousandth-of-a-second accuracy or more):
<input name=favtime type=time step=any>
Normally, time controls are limited to an accuracy of one minute.
http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-attributes.html#attr-input-step
Since eval()
is evil, and new Function()
is not the most efficient way to achieve this, here is a quick JS function that returns the function from its name in string.
function convertStringtoFunction(functionName){ var nullFunc = function(){}; // Fallback Null-Function var ret = window; // Top level namespace // If null/undefined string, then return a Null-Function if(functionName==null) return nullFunc; // Convert string to function name functionName.split('.').forEach(function(key){ ret = ret[key]; }); // If function name is not available, then return a Null-Function else the actual function return (ret==null ? nullFunc : ret); }
Usage:
convertStringtoFunction("level1.midLevel.myFunction")(arg1, arg2, ...);
The three ways are:
//NSArray
NSArray *arrData = @[@1,@2,@3,@4];
// 1.Classical
for (int i=0; i< [arrData count]; i++){
NSLog(@"[%d]:%@",i,arrData[i]);
}
// 2.Fast iteration
for (id element in arrData){
NSLog(@"%@",element);
}
// 3.Blocks
[arrData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"[%lu]:%@",idx,obj);
// Set stop to YES in case you want to break the iteration
}];
With Kotlin, you can use:
val content = LayoutInflater.from(context).inflate(R.layout.[custom_layout_name], null)
[your_main_layout].apply {
//..
addView(content)
}
What happens with bittorrent and a DHT is that at the beginning bittorrent uses information embedded in the torrent file to go to either a tracker or one of a set of nodes from the DHT. Then once it finds one node, it can continue to find others and persist using the DHT without needing a centralized tracker to maintain it.
The original information bootstraps the later use of the DHT.
Not exactly an answer, but I have never heard of a way to do this in Apache itself. I guess it might be possible with an extension module, but I don't know whether one has been written.
One concern is that POST data can be pretty large, and if you don't put some kind of limit on how much is being logged, you might run out of disk space after a while. It's a possible route for hackers to mess with your server.
Running the apc.php script is key to understanding what your problem is, IMO. This helped us size our cache properly and for the moment, seems to have resolved the problem.
Daniel has a good explanation of the syntax relationships, but I put this document together for my team in order to make it a little simpler for them to understand. Hope this helps someone
In Spring or Spring boot application.properties file here is the way to escape the special characters;
table.whereclause=where id'\='100
You cannot 'alter' the property syntax this way. What you can do is this:
class Foo
{
string MyProperty { get; set; } // auto-property with inaccessible backing field
}
and a generic version would look like this:
class Foo<T>
{
T MyProperty { get; set; }
}
The Set interface itself does not stipulate any particular order. The SortedSet does however.
As other mentioned JSX
is not a standard Javascript extension. It's better to name your entry point of Application based on .js
and for the rest components, you can use .jsx
.
I have an important reason for why I'm using .JSX
for all component's file names.
Actually, In a large scale project with huge bunch of code, if we set all React's component with .jsx
extension, It'll be easier while navigating to different javascript files across the project(like helpers, middleware, etc.) and you know this is a React Component and not other types of the javascript file.
Assuming that by "string" you're talking about std::string in C++, you might have a look at the Tokenizer package in Boost.
Sometimes specifying the database (instead of default) solves this error.
Building off of Alberto, I added the rollup.
SELECT [Narrative] = CASE
WHEN [Narrative] IS NULL THEN 'count_total' ELSE [Narrative] END
,[Count]=SUM([Count]) FROM (SELECT COUNT(*) [Count], 'count_nulls' AS [Narrative]
FROM [CrmDW].[CRM].[User]
WHERE [EmployeeID] IS NULL
UNION
SELECT COUNT(*), 'count_not_nulls ' AS narrative
FROM [CrmDW].[CRM].[User]
WHERE [EmployeeID] IS NOT NULL) S
GROUP BY [Narrative] WITH CUBE;
Try this.
Dim Workbk as workbook
Set Workbk = thisworkbook
Now everything you program will apply just for your containing macro workbook.