the lockforConfiguration
is set in your code, where you declare your AVCaptureDevice
is a property.
[videoCaptureDevice lockForConfiguration:nil];
@sedit was on the right path, but it's a bit awkward to define a variable.
The way to do this in bash is to put a dollar sign in front of your single quoted string.
$ echo -e '1\n2\n3'
1
2
3
$ echo -e '1\n2\n3' | sed 's/.*/\t&/g'
t1
t2
t3
$ echo -e '1\n2\n3' | sed $'s/.*/\t&/g'
1
2
3
If your string needs to include variable expansion, you can put quoted strings together like so:
$ timestamp=$(date +%s)
$ echo -e '1\n2\n3' | sed "s/.*/$timestamp"$'\t&/g'
1491237958 1
1491237958 2
1491237958 3
In bash $'string'
causes "ANSI-C expansion". And that is what most of us expect when we use things like \t
, \r
, \n
, etc. From: https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html#ANSI_002dC-Quoting
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded...
The expanded result is single-quoted, as if the dollar sign had not been present.
I personally think most efforts to avoid bash are silly because avoiding bashisms does NOT* make your code portable. (Your code will be less brittle if you shebang it to bash -eu
than if you try to avoid bash and use sh
[unless you are an absolute POSIX ninja].) But rather than have a religious argument about that, I'll just give you the BEST* answer.
$ echo -e '1\n2\n3' | sed "s/.*/$(printf '\t')&/g"
1
2
3
* BEST answer? Yes, because one example of what most anti-bash shell scripters would do wrong in their code is use echo '\t'
as in @robrecord's answer. That will work for GNU echo, but not BSD echo. That is explained by The Open Group at http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html#tag_20_37_16 And this is an example of why trying to avoid bashisms usually fail.
This page shows up when you google how to convert to base64, so for completeness:
$b = [System.Text.Encoding]::UTF8.GetBytes("blahblah")
[System.Convert]::ToBase64String($b)
You can pass data from PHP to javascript but the only way to get data from javascript to PHP is via AJAX.
The reason for that is you can build a valid javascript through PHP but to get data to PHP you will need to get PHP running again, and since PHP only runs to process the output, you will need a page reload or an asynchronous query.
The following are the major differences between procedure and function,
You can specify a width on string fields, e.g.
printf("%-20s", "initialization...");
And then whatever's printed with that field will be blank-padded to the width you indicate.
The -
left-justifies your text in that field.
Following Rory McCrossan answer, if you want to send an array of integer (almost for .NET), this is the code:
// ...
url: "MyUrl", // For example --> @Url.Action("Method", "Controller")
method: "post",
traditional: true,
data:
$('#myForm').serialize() +
"¶m1="xxx" +
"¶m2="33" +
"&" + $.param({ paramArray: ["1","2","3"]}, true)
,
// ...
If you look for POSIX compliant solution:
cd DirsRoot && find . -type f -print -o -name . -o -prune
-maxdepth is not POSIX compliant option.
you can use plt.matshow()
instead of plt.imshow()
or you can use seaborn module's heatmap
(see documentation) to plot the confusion matrix
import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
array = [[33,2,0,0,0,0,0,0,0,1,3],
[3,31,0,0,0,0,0,0,0,0,0],
[0,4,41,0,0,0,0,0,0,0,1],
[0,1,0,30,0,6,0,0,0,0,1],
[0,0,0,0,38,10,0,0,0,0,0],
[0,0,0,3,1,39,0,0,0,0,4],
[0,2,2,0,4,1,31,0,0,0,2],
[0,1,0,0,0,0,0,36,0,2,0],
[0,0,0,0,0,0,1,5,37,5,1],
[3,0,0,0,0,0,0,0,0,39,0],
[0,0,0,0,0,0,0,0,0,0,38]]
df_cm = pd.DataFrame(array, index = [i for i in "ABCDEFGHIJK"],
columns = [i for i in "ABCDEFGHIJK"])
plt.figure(figsize = (10,7))
sn.heatmap(df_cm, annot=True)
First, add the dependency of FFmpeg library
implementation 'com.writingminds:FFmpegAndroid:0.3.2'
Then load in activity
FFmpeg ffmpeg;
private void trimVideo(ProgressDialog progressDialog) {
outputAudioMux = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath()
+ "/VidEffectsFilter" + "/" + new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date())
+ "filter_apply.mp4";
if (startTrim.equals("")) {
startTrim = "00:00:00";
}
if (endTrim.equals("")) {
endTrim = timeTrim(player.getDuration());
}
String[] cmd = new String[]{"-ss", startTrim + ".00", "-t", endTrim + ".00", "-noaccurate_seek", "-i", videoPath, "-codec", "copy", "-avoid_negative_ts", "1", outputAudioMux};
execFFmpegBinary1(cmd, progressDialog);
}
private void execFFmpegBinary1(final String[] command, ProgressDialog prpg) {
ProgressDialog progressDialog = prpg;
try {
ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
@Override
public void onFailure(String s) {
progressDialog.dismiss();
Toast.makeText(PlayerTestActivity.this, "Fail to generate video", Toast.LENGTH_SHORT).show();
Log.d(TAG, "FAILED with output : " + s);
}
@Override
public void onSuccess(String s) {
Log.d(TAG, "SUCCESS wgith output : " + s);
// pathVideo = outputAudioMux;
String finalPath = outputAudioMux;
videoPath = outputAudioMux;
Toast.makeText(PlayerTestActivity.this, "Storage Path =" + finalPath, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(PlayerTestActivity.this, ShareVideoActivity.class);
intent.putExtra("pathGPU", finalPath);
startActivity(intent);
finish();
MediaScannerConnection.scanFile(PlayerTestActivity.this, new String[]{finalPath}, new String[]{"mp4"}, null);
}
@Override
public void onProgress(String s) {
Log.d(TAG, "Started gcommand : ffmpeg " + command);
progressDialog.setMessage("Please Wait video triming...");
}
@Override
public void onStart() {
Log.d(TAG, "Startedf command : ffmpeg " + command);
}
@Override
public void onFinish() {
Log.d(TAG, "Finished f command : ffmpeg " + command);
progressDialog.dismiss();
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// do nothing for now
}
}
private void loadFFMpegBinary() {
try {
if (ffmpeg == null) {
ffmpeg = FFmpeg.getInstance(this);
}
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
@Override
public void onFailure() {
showUnsupportedExceptionDialog();
}
@Override
public void onSuccess() {
Log.d("dd", "ffmpeg : correct Loaded");
}
});
} catch (FFmpegNotSupportedException e) {
showUnsupportedExceptionDialog();
} catch (Exception e) {
Log.d("dd", "EXception no controlada : " + e);
}
}
private void showUnsupportedExceptionDialog() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Not Supported")
.setMessage("Device Not Supported")
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create()
.show();
}
public String timeTrim(long milliseconds) {
String finalTimerString = "";
String minutString = "";
String secondsString = "";
// Convert total duration into time
int hours = (int) (milliseconds / (1000 * 60 * 60));
int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
// Add hours if there
if (hours < 10) {
finalTimerString = "0" + hours + ":";
} else {
finalTimerString = hours + ":";
}
if (minutes < 10) {
minutString = "0" + minutes;
} else {
minutString = "" + minutes;
}
// Prepending 0 to seconds if it is one digit
if (seconds < 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}
finalTimerString = finalTimerString + minutString + ":" + secondsString;
// return timer string
return finalTimerString;
}
Also use another feature by FFmpeg
===> merge audio to video
String[] cmd = new String[]{"-i", yourRealPath, "-i", arrayList.get(posmusic).getPath(), "-map", "1:a", "-map", "0:v", "-codec", "copy", "-shortest", outputcrop};
===> Flip vertical :
String[] cm = new String[]{"-i", yourRealPath, "-vf", "vflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};
===> Flip horizontally :
String[] cm = new String[]{"-i", yourRealPath, "-vf", "hflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};
===> Rotate 90 degrees clockwise:
String[] cm=new String[]{"-i", yourRealPath, "-c", "copy", "-metadata:s:v:0", "rotate=90", outputcrop1};
===> Compress Video
String[] complexCommand = {"-y", "-i", yourRealPath, "-strict", "experimental", "-vcodec", "libx264", "-preset", "ultrafast", "-crf", "24", "-acodec", "aac", "-ar", "22050", "-ac", "2", "-b", "360k", "-s", "1280x720", outputcrop1};
===> Speed up down video
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=2.0*PTS[v];[0:a]atempo=0.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=1.0*PTS[v];[0:a]atempo=1.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.75*PTS[v];[0:a]atempo=1.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.5*PTS[v];[0:a]atempo=2.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
===> Add two mp3 files
StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(textSngname);
sb.append(" -i ");
sb.append(mAudioFilename);
sb.append(" -filter_complex [0:0][1:0]concat=n=2:v=0:a=1[out] -map [out] ");
sb.append(finalfile);
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()
===> Add three mp3 files
StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(firstSngname);
sb.append(" -i ");
sb.append(textSngname);
sb.append(" -i ");
sb.append(mAudioFilename);
sb.append(" -filter_complex [0:0][1:0][2:0]concat=n=3:v=0:a=1[out] -map [out] ");
sb.append(finalfile);
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()
A workaround (until Google fix this bug) is to use an EditText
with android:inputType="numberDecimal"
and android:digits="0123456789.,"
.
Then add a TextChangedListener to the EditText with the following afterTextChanged:
public void afterTextChanged(Editable s) {
double doubleValue = 0;
if (s != null) {
try {
doubleValue = Double.parseDouble(s.toString().replace(',', '.'));
} catch (NumberFormatException e) {
//Error
}
}
//Do something with doubleValue
}
Here's another idea. You have to remember, that it's .NET underneath:
$arr = [System.Array]::CreateInstance([System.Object], 5)
$arr.GetType()
$arr.Length
$arr = [Object[]]::new(5)
$arr.GetType()
$arr.Length
Result:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
5
True True Object[] System.Array
5
Using new()
has one distinct advantage: when you're programming in ISE and want to create an object, ISE will give you hint with all paramer combinations and their types. You don't have that with New-Object
, where you have to remember the types and order of arguments.
file
PS /home/edward/Desktop>
Get-Content ./copy.txt
[Desktop Entry]
Name=calibre Exec=~/Apps/calibre/calibre
Icon=~/Apps/calibre/resources/content-server/calibre.png
Type=Application*
Start by get the content from file and trim the white spaces if any found in each line of the text document. That becomes the object passed to the where-object to go through the array looking at each member of the array with string length greater then 0. That object is passed to replace the content of the file you started with. It would probably be better to make a new file... Last thing to do is reads back the newly made file's content and see your awesomeness.
(Get-Content ./copy.txt).Trim() | Where-Object{$_.length -gt 0} | Set-Content ./copy.txt
Get-Content ./copy.txt
Webkit browsers (such as Chrome, Safari and Opera) supports the non-standard ::-webkit-scrollbar pseudo element, which allows us to modify the look of the browser's scrollbar.
Note: The ::-webkit-scrollbar is not supported by Firefox or IE and Edge.
* {_x000D_
box-sizing: border-box;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
_x000D_
div {_x000D_
width: 15rem;_x000D_
height: 8rem;_x000D_
padding: .5rem;_x000D_
border: 1px solid #aaa;_x000D_
margin-bottom: 1rem;_x000D_
overflow: auto;_x000D_
}_x000D_
_x000D_
.box::-webkit-scrollbar {_x000D_
width: .8em;_x000D_
}_x000D_
_x000D_
.box::-webkit-scrollbar-track {_x000D_
box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);_x000D_
}_x000D_
_x000D_
.box::-webkit-scrollbar-thumb {_x000D_
background-color: dodgerblue;_x000D_
}
_x000D_
<div class="box">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate</p>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate</p>_x000D_
</div>
_x000D_
Reference: How To Create a Custom Scrollbar
My solution, to only hide the navigation bar, is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final View decorView = getWindow().getDecorView();
decorView.setOnSystemUiVisibilityChangeListener (new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
});
}
@Override
protected void onResume() {
super.onResume();
final int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
final View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(uiOptions);
}
If you want the position relative to the document then:
$("#myTable").offset().top;
but often you will want the position relative to the closest positioned parent:
$("#myTable").position().top;
You can select elements with multiple classes like so:
$("element.firstClass.anotherClass");
Simply chain the next class onto the first one, without a space (spaces mean "children of").
Here's one more approach by using SET
and FOR /F
@echo off
set "var=<?xml version="1.0" encoding="utf-8" ?>"
for /f "tokens=1* delims==" %%a in ('set var') do echo %%b
and you can beautify it like:
@echo off
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "print{[=for /f "tokens=1* delims==" %%a in ('set " & set "]}=') do echo %%b"
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "xml_line.1=<?xml version="1.0" encoding="utf-8" ?>"
set "xml_line.2=<root>"
set "xml_line.3=</root>"
%print{[% xml_line %]}%
If you paste the string in server-side into the html don't need to do nothing:
For plain java in jsp:
var jsonObj=<%=jsonStringInJavaServlet%>;
For jsp width struts:
var jsonObj=<s:property value="jsonStringInJavaServlet" escape="false" escapeHtml="false"/>;
The HTML4 spec for the <input>
element specifies the following script events are available:
onfocus, onblur, onselect, onchange, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup
here's an example that bind's to all these events and shows what's going on http://jsfiddle.net/pxfunc/zJ7Lf/
I think you can filter out which events are truly relevent to your situation and detect what the text value was before and after the event to determine a change
Read about Storage Engines.
MyISAM:
The MyISAM storage engine in MySQL.
InnoDB:
The InnoDB storage engine in MySQL.
MyISAM Limitations:
InnoDB Limitations:
ROW_FORMAT=COMPRESSED
)For brief understanding read below links:
In your case, use git filter-branch
instead of git rm
.
git rm
will delete the files in the sense that they will not be tracked by git anymore, but that does not remove the old commit objects corresponding to those images, and so you will still be stuck with pushing the earlier commits which correspond to 12GB of images.
The git filter-branch
, on the other hand, can remove those files from all the previous commits as well, thus doing away with the need to push any of them.
Use the command
git filter-branch --force --index-filter \
'git rm -r --cached --ignore-unmatch public/photos' \
--prune-empty --tag-name-filter cat -- --all
After the filter branch is complete, verify that no unintended file was lost.
Now add a .gitignore rule
echo public/photos >> .gitignore
git add .gitignore && git commit -m "ignore rule for photos"
Now do a push
git push -f origin branch
Check this, this and this for further help. Just to be on the safer side, I would suggest you create a backup copy of the repo on your system before going ahead with these instructions.
As for your orignial error message, it is happening because you already untracked them using git rm
, and hence git is complaining because it can't remove a file it isn't tracking. Read more about this here.
I did a pure javascript hack to make this possible.
<div class="my_background_image" style="background-image: url(broken-image.jpg)">
<img class="image_error" src="broken-image.jpg" onerror="this.parentElement.style.display='none';">
</div>
Or
onerror="this.parentElement.backgroundImage = "url('image_placeHolder.png')";
css:
.image_error {
display: none;
}
Implicit and explicit wait is better.
But if you are handling an exception in Java, then you can use this for waiting for a page to reload:
Thead.sleep(1000);
-w
is the GCC-wide option to disable warning messages.
FYI:
git log tagA...tagB
provides standard log output in a range.
You can achieve this by adding alternating style classes to each list item
<ul>
<li class="odd"><a href="link">Link 1</a></li>
<li><a href="link">Link 2</a></li>
<li class="odd"><a href="link">Link 2</a></li>
<li><a href="link">Link 2</a></li>
</ul>
And then styling it like
li { backgorund:white; }
li.odd { background:silver; }
You can further automate this process with javascript (jQuery example below)
$(document).ready(function() {
$('table tbody tr:odd').addClass('odd');
});
App Engine is a Platform-as-a-Service. It means that you simply deploy your code, and the platform does everything else for you. For example, if your app becomes very successful, App Engine will automatically create more instances to handle the increased volume.
Compute Engine is an Infrastructure-as-a-Service. You have to create and configure your own virtual machine instances. It gives you more flexibility and generally costs much less than App Engine. The drawback is that you have to manage your app and virtual machines yourself.
Read more about Compute Engine
You can mix both App Engine and Compute Engine, if necessary. They both work well with the other parts of the Google Cloud Platform.
EDIT (May 2016):
One more important distinction: projects running on App Engine can scale down to zero instances if no requests are coming in. This is extremely useful at the development stage as you can go for weeks without going over the generous free quota of instance-hours. Flexible runtime (i.e. "managed VMs") require at least one instance to run constantly.
EDIT (April 2017):
Cloud Functions (currently in beta) is the next level up from App Engine in terms of abstraction - no instances! It allows developers to deploy bite-size pieces of code that execute in response to different events, which may include HTTP requests, changes in Cloud Storage, etc.
The biggest difference with App Engine is that functions are priced per 100 milliseconds, while App Engine's instances shut down only after 15 minutes of inactivity. Another advantage is that Cloud Functions execute immediately, while a call to App Engine may require a new instance - and cold-starting a new instance may take a few seconds or longer (depending on runtime and your code).
This makes Cloud Functions ideal for (a) rare calls - no need to keep an instance live just in case something happens, (b) rapidly changing loads where instances are often spinning and shutting down, and possibly more use cases.
In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
try:
image = pygame.image.load(imgfile, 'img_01.png')
finally:
imgfile.close()
If you look this file Namespace is not the first statement.
<?php
class BulletProofException extends Exception{}
namespace BulletProof;
You can try to move the namespace over the class definition.
Piece of cake.
Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.
No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.
Voila. Grids FTW.
Here's a method my Grandfather taught me when I was a child. It requires + and / operators but it makes calculations easy.
Add the individual digits together and then see if its a multiple of 3.
But this method works for numbers above 12.
Example: 36,
3+6=9 which is a multiple of 3.
42,
4+2=6 which is a multiple of 3.
The inclusion of your comparison class (or more specifically the AsEnumerable
call you needed to use to get it to work) meant that the sorting logic went from being based on the database server to being on the database client (your application). This meant that your client now needs to retrieve and then process a larger number of records, which will always be less efficient that performing the lookup on the database where the approprate indexes can be used.
You should try to develop a where clause that satisfies your requirements instead, see Using an IEqualityComparer with a LINQ to Entities Except clause for more details.
If your server is expecting the POST request to be json, then you would need to add a header, and also serialize the data for your request...
Python 2.x
import json
import urllib2
data = {
'ids': [12, 3, 4, 5, 6]
}
req = urllib2.Request('http://example.com/api/posts/create')
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(data))
Python 3.x
https://stackoverflow.com/a/26876308/496445
If you don't specify the header, it will be the default application/x-www-form-urlencoded
type.
In php, we have two option to concatenate table columns.
First Option using Query
In query, CONCAT keyword used to concatenate two columns
SELECT CONCAT(`SUBJECT`,'_', `YEAR`) AS subject_year FROM `table_name`;
Second Option using symbol ( . )
After fetch the data from database table, assign the values to variable, then using ( . ) Symbol and concatenate the values
$subject = $row['SUBJECT'];
$year = $row['YEAR'];
$subject_year = $subject . "_" . $year;
Instead of underscore( _ ) , we will use the spaces, comma, letters,numbers..etc
This question has been posted long time ago, but I found an alternative way to answer it. So I decided to share it here.
Firstly, one must know that: if two vectors are perpendicular, their dot product equals zero.
The normal vector (x',y')
is perpendicular to the line connecting (x1,y1)
and (x2,y2)
. This line has direction (x2-x1,y2-y1)
, or (dx,dy)
.
So,
(x',y').(dx,dy) = 0
x'.dx + y'.dy = 0
The are plenty of pairs (x',y') that satisfy the above equation. But the best pair that ALWAYS satisfies is either (dy,-dx)
or (-dy,dx)
You can use:
<td onclick='javascript:someFunc(this);'></td>
With passing this you can access the DOM object via your function parameters.
I use Google's JSON library to serialize it then create a new instance of the serialized object. It does deep copy with a few restrictions:
there can't be any recursive references
it won't copy arrays of disparate types
arrays and lists should be typed or it won't find the class to instantiate
you may need to encapsulate strings in a class you declare yourself
I also use this class to save user preferences, windows and whatnot to be reloaded at runtime. It is very easy to use and effective.
import com.google.gson.*;
public class SerialUtils {
//___________________________________________________________________________________
public static String serializeObject(Object o) {
Gson gson = new Gson();
String serializedObject = gson.toJson(o);
return serializedObject;
}
//___________________________________________________________________________________
public static Object unserializeObject(String s, Object o){
Gson gson = new Gson();
Object object = gson.fromJson(s, o.getClass());
return object;
}
//___________________________________________________________________________________
public static Object cloneObject(Object o){
String s = serializeObject(o);
Object object = unserializeObject(s,o);
return object;
}
}
Every control that uses Collections to store data have SelectedValue, SelectedItem property. Examples of these controls are ListBox, Dropdown, RadioButtonList, CheckBoxList.
To be more specific if you literally want to retrieve Text of Selected Item then you can write:
ListBox1.SelectedItem.Text;
Your ListBox1 can also return Text using SelectedValue property if value has set to that before. But above is more effective way to get text.
Now, the value is something that is not visible to user but it is used mostly to store in database. We don't insert Text of ListBox1, however we can insert it also, but we used to insert value of selected item. To get value we can use
ListBox1.SelectedValue
This works for me:
$("#dateselector").datepicker("option", "defaultDate", new Date(2008,9,3));
My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!
I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:
# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root virsh start download
I think this is correct, and hope it helps someone else too.
md5="$(md5sum "${my_iso_file}")"
md5="${md5%% *}" # remove the first space and everything after it
echo "${md5}"
Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":
List initialization does not allow narrowing (§iso.8.5.4). That is:
Example:
void fun(double val, int val2) {
int x2 = val; // if val == 7.9, x2 becomes 7 (bad)
char c2 = val2; // if val2 == 1025, c2 becomes 1 (bad)
int x3 {val}; // error: possible truncation (good)
char c3 {val2}; // error: possible narrowing (good)
char c4 {24}; // OK: 24 can be represented exactly as a char (good)
char c5 {264}; // error (assuming 8-bit chars): 264 cannot be
// represented as a char (good)
int x4 {2.0}; // error: no double to int value conversion (good)
}
The only situation where = is preferred over {} is when using auto
keyword to get the type determined by the initializer.
Example:
auto z1 {99}; // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99; // z3 is an int
Prefer {} initialization over alternatives unless you have a strong reason not to.
As of Java-8, there are four variants of the setAll method which sets all elements of the specified array, using a provided generator function to compute each element.
Of those four overloads only three of them accept an array of primitives declared as such:
Examples of how to use the aforementioned methods:
// given an index, set the element at the specified index with the provided value
double [] doubles = new double[50];
Arrays.setAll(doubles, index -> 30D);
// given an index, set the element at the specified index with the provided value
int [] ints = new int[50];
Arrays.setAll(ints, index -> 60);
// given an index, set the element at the specified index with the provided value
long [] longs = new long[50];
Arrays.setAll(longs, index -> 90L);
The function provided to the setAll
method receives the element index and returns a value for that index.
you may be wondering how about characters array?
This is where the fourth overload of the setAll
method comes into play. As there is no overload that consumes an array of character primitives, the only option we have is to change the declaration of our character array to a type Character[]
.
If changing the type of the array to Character
is not appropriate then you can fall back to the Arrays.fill method.
Example of using the setAll
method with Character[]
:
// given an index, set the element at the specified index with the provided value
Character[] character = new Character[50];
Arrays.setAll(characters, index -> '+');
Although, it's simpler to use the Arrays.fill
method rather than the setAll
method to set a specific value.
The setAll
method has the advantage that you can either set all the elements of the array to have the same value or generate an array of even numbers, odd numbers or any other formula:
e.g.
int[] evenNumbers = new int[10];
Arrays.setAll(evenNumbers, i -> i * 2);
There's also several overloads of the parallelSetAll method which is executed in parallel, although it's important to note that the function passed to the parallelSetAll method must be side-effect free.
Conclusion
If your goal is simply to set a specific value for each element of the array then using the Arrays.fill
overloads would be the most appropriate option. However, if you want to be more flexible or generate elements on demand then using the Arrays.setAll
or Arrays.parallelSetAll
(when appropriate) would be the option to go for.
According to the SQLite documentation for the Command Line Shell For SQLite you can export an SQLite table (or part of a table) as CSV, simply by setting the "mode" to "csv" and then run a query to extract the desired rows of the table:
sqlite> .header on
sqlite> .mode csv
sqlite> .once c:/work/dataout.csv
sqlite> SELECT * FROM tab1;
sqlite> .exit
Then use the ".import" command to import CSV (comma separated value) data into an SQLite table:
sqlite> .mode csv
sqlite> .import C:/work/dataout.csv tab1
sqlite> .exit
Please read the further documentation about the two cases to consider: (1) Table "tab1" does not previously exist and (2) table "tab1" does already exist.
You can use following:
protected void Application_Start(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(StartMySystem));
}
private void StartMySystem(object state)
{
Log(HttpContext.Current.Request.ToString());
}
String text = "I don't like Hasina.";
textView.setText(spannableString(text, 8, 14));
private SpannableString spannableString(String text, int start, int end) {
SpannableString spannableString = new SpannableString(text);
ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{0xffa10901});
TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);
spannableString.setSpan(highlightSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new BackgroundColorSpan(0xFFFCFF48), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new RelativeSizeSpan(1.5f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
Output:
Use the .str()-method:
Manages the contents of the underlying string object.
1) Returns a copy of the underlying string as if by calling
rdbuf()->str()
.2) Replaces the contents of the underlying string as if by calling
rdbuf()->str(new_str)
...Notes
The copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling
c_str()
on the result ofstr()
(for example inauto *ptr = out.str().c_str();
) results in a dangling pointer...
javax.servlet
is a package that's part of Java EE (Java Enterprise Edition). You've got the JDK for Java SE (Java Standard Edition).
You could use the Java EE SDK for example.
Alternatively simple servlet containers such as Apache Tomcat also come with this API (look for servlet-api.jar
).
Instance variable on a class:
class Parent
@things = []
def self.things
@things
end
def things
self.class.things
end
end
class Child < Parent
@things = []
end
Parent.things << :car
Child.things << :doll
mom = Parent.new
dad = Parent.new
p Parent.things #=> [:car]
p Child.things #=> [:doll]
p mom.things #=> [:car]
p dad.things #=> [:car]
Class variable:
class Parent
@@things = []
def self.things
@@things
end
def things
@@things
end
end
class Child < Parent
end
Parent.things << :car
Child.things << :doll
p Parent.things #=> [:car,:doll]
p Child.things #=> [:car,:doll]
mom = Parent.new
dad = Parent.new
son1 = Child.new
son2 = Child.new
daughter = Child.new
[ mom, dad, son1, son2, daughter ].each{ |person| p person.things }
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
With an instance variable on a class (not on an instance of that class) you can store something common to that class without having sub-classes automatically also get them (and vice-versa). With class variables, you have the convenience of not having to write self.class
from an instance object, and (when desirable) you also get automatic sharing throughout the class hierarchy.
Merging these together into a single example that also covers instance variables on instances:
class Parent
@@family_things = [] # Shared between class and subclasses
@shared_things = [] # Specific to this class
def self.family_things
@@family_things
end
def self.shared_things
@shared_things
end
attr_accessor :my_things
def initialize
@my_things = [] # Just for me
end
def family_things
self.class.family_things
end
def shared_things
self.class.shared_things
end
end
class Child < Parent
@shared_things = []
end
And then in action:
mama = Parent.new
papa = Parent.new
joey = Child.new
suzy = Child.new
Parent.family_things << :house
papa.family_things << :vacuum
mama.shared_things << :car
papa.shared_things << :blender
papa.my_things << :quadcopter
joey.my_things << :bike
suzy.my_things << :doll
joey.shared_things << :puzzle
suzy.shared_things << :blocks
p Parent.family_things #=> [:house, :vacuum]
p Child.family_things #=> [:house, :vacuum]
p papa.family_things #=> [:house, :vacuum]
p mama.family_things #=> [:house, :vacuum]
p joey.family_things #=> [:house, :vacuum]
p suzy.family_things #=> [:house, :vacuum]
p Parent.shared_things #=> [:car, :blender]
p papa.shared_things #=> [:car, :blender]
p mama.shared_things #=> [:car, :blender]
p Child.shared_things #=> [:puzzle, :blocks]
p joey.shared_things #=> [:puzzle, :blocks]
p suzy.shared_things #=> [:puzzle, :blocks]
p papa.my_things #=> [:quadcopter]
p mama.my_things #=> []
p joey.my_things #=> [:bike]
p suzy.my_things #=> [:doll]
Take this as a sample code. Replace imageheight and image width with your image dimensions.
<div style="background:yourimage.jpg no-repeat;height:imageheight px;width:imagewidth px">
</div>
You would use a service for that in Angular. A service is a function you register with Angular, and that functions job is to return an object which will live until the browser is closed/refreshed. So it's a good place to store state in, and to synchronize that state with the server asynchronously as that state changes.
None of the answers on the web so far have helped. Build > Make Project did not work for me. For me it was as simple as choosing this other option (on Android Studio 1.3.1):
Build > Make Module 'module name'
This answer was not working for me so I went on to MSDN. There I found that now the code should look like this:
//var is of MessageBoxResult type
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
// If the no button was pressed ...
if (result == DialogResult.No)
{
...
}
Hope it helps
You need to create another migration file - and place it in there:
Run
Laravel 4: php artisan migrate:make rename_stnk_column
Laravel 5: php artisan make:migration rename_stnk_column
Then inside the new migration file place:
class RenameStnkColumn extends Migration
{
public function up()
{
Schema::table('stnk', function(Blueprint $table) {
$table->renameColumn('id', 'id_stnk');
});
}
public function down()
{
Schema::table('stnk', function(Blueprint $table) {
$table->renameColumn('id_stnk', 'id');
});
}
}
Don't forget to escape your data! If you want to put data in a CSV file without fputcsv function or put it in a SQL query use this code:
$comma_separated = "'" . implode("','", array_map('addslashes', $array)) . "'";
This code avoids SQL injection or data fragmentation when input array contains single quotation or backslash characters.
I had a similar problem; the anchor text in my Bootstrap4 navbar wasn't centered. Simply added text-center
in the anchor's class.
I solved this problem in a completely different way.
Package installer = Conda (Miniconda)
List of available envs = base, djenv(Django environment created for keeping project related modules).
When I was using the command line to activate the djenv using conda activate djenv
, the base environment was already activated. I did not notice that and when djenv was activated, (djenv)
was being displayed at the beginning of the prompt on the command line. When i tired executing , python manage.py migrate
, this happened.
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
I deactivated the current environment, i.e conda deactivate
. This deactivated djenv
. Then, i deactivated the base
environment.
After that, I again activated djenv
. And the command worked like a charm!!
If someone is facing a similar issue, I hope you should consider trying this as well. Maybe it helps.
You could use a StringReader and convert the reader to an input stream using the solution in this other stackoverflow post.
Try this code
SELECT CONVERT(varchar(max), CAST(1000.2324422 AS decimal(11,2)))
result:1000.23
here decimal(11,2):11-total digits count(without point),2-for two digits after decimal point
Class selectors are prefixed with a dot. Your .find()
is missing that so jQuery thinks you're looking for <myClass>
elements.
var myVar = $("#start").find('.myClass').val();
this worked for me
sudo letsencrypt certonly -a webroot --webroot-path=/var/www/html -d
domain.com -d www.domain.com
Setting the Environment System variable:
Variable Value ANDROID_HOME D:\Android_Sdk\Sdk (your path)
__func__
is an implicitly declared identifier that expands to a character array variable containing the function name when it is used inside of a function. It was added to C in C99. From C99 §6.4.2.2/1:
The identifier
__func__
is implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declarationstatic const char __func__[] = "function-name";
appeared, where function-name is the name of the lexically-enclosing function. This name is the unadorned name of the function.
Note that it is not a macro and it has no special meaning during preprocessing.
__func__
was added to C++ in C++11, where it is specified as containing "an implementation-de?ned string" (C++11 §8.4.1[dcl.fct.def.general]/8), which is not quite as useful as the specification in C. (The original proposal to add __func__
to C++ was N1642).
__FUNCTION__
is a pre-standard extension that some C compilers support (including gcc and Visual C++); in general, you should use __func__
where it is supported and only use __FUNCTION__
if you are using a compiler that does not support it (for example, Visual C++, which does not support C99 and does not yet support all of C++0x, does not provide __func__
).
__PRETTY_FUNCTION__
is a gcc extension that is mostly the same as __FUNCTION__
, except that for C++ functions it contains the "pretty" name of the function including the signature of the function. Visual C++ has a similar (but not quite identical) extension, __FUNCSIG__
.
For the nonstandard macros, you will want to consult your compiler's documentation. The Visual C++ extensions are included in the MSDN documentation of the C++ compiler's "Predefined Macros". The gcc documentation extensions are described in the gcc documentation page "Function Names as Strings."
check for keyCode
&& which
& keyup
|| keydown
$(document).keydown(function(e){
var code = e.keyCode || e.which;
alert(code);
});
I like and upvoted @Simon Sapin's answer. I ended up taking a slightly different tack, however, and created my own decorator:
from flask import Response
from functools import wraps
def returns_xml(f):
@wraps(f)
def decorated_function(*args, **kwargs):
r = f(*args, **kwargs)
return Response(r, content_type='text/xml; charset=utf-8')
return decorated_function
and use it thus:
@app.route('/ajax_ddl')
@returns_xml
def ajax_ddl():
xml = 'foo'
return xml
I think this is slightly more comfortable.
Incase you are dynamically getting your data e.g When you need data based on the user logged in by their id use consider the following code example for a No Active Record:
$this->db->query('SELECT * FROM my_users_table WHERE id = ?', $this->session->userdata('id'));
return $query->row_array();
This will return a specific row based on your the set session data of user.
If you already have the Groovy (Postbuild) plugin installed, I think it's a valid desire to get this done with (generic) Groovy instead of installing a (specialized) plugin.
That said, you can get the workspace using manager.build.workspace.getRemote()
. Don't forget to add File.separator
between path and file name.
I've found a solution. If you want to update razor version or mvc 4 to 5, change some lines.
Old code in Views/web.config
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
Replaced with
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
sectionGroup
must be change, too.
I have read whole this thread and many others but I can't find as thorough answer as this is.
By which I completely understood the "why to use ?? and when to use ?? and how to use ??."
Windows communication foundation unleashed By Craig McMurtry ISBN 0-672-32948-4
There are two common circumstances in which one would like to know whether a value has been assigned to an instance of a value type. The first is when the instance represents a value in a database. In such a case, one would like to be able to examine the instance to ascertain whether a value is indeed present in the database. The other circumstance, which is more pertinent to the subject matter of this book, is when the instance represents a data item received from some remote source. Again, one would like to determine from the instance whether a value for that data item was received.
The .NET Framework 2.0 incorporates a generic type definition that provides for cases like these in which one wants to assign null to an instance of a value type, and test whether the value of the instance is null. That generic type definition is System.Nullable<T>
, which constrains the generic type arguments that may be substituted for T to value types.
Instances of types constructed from System.Nullable<T>
can be assigned a value of null; indeed, their values are null by default. Thus, types constructed from
System.Nullable<T>
may be referred to as nullable value types.
System.Nullable<T>
has a property, Value, by which the value assigned to an instance of
a type constructed from it can be obtained if the value of the instance is not null.
Therefore, one can write:
System.Nullable<int> myNullableInteger = null;
myNullableInteger = 1;
if (myNullableInteger != null)
{
Console.WriteLine(myNullableInteger.Value);
}
The C# programming language provides an abbreviated syntax for declaring types
constructed from System.Nullable<T>
. That syntax allows one to abbreviate:
System.Nullable<int> myNullableInteger;
to
int? myNullableInteger;
The compiler will prevent one from attempting to assign the value of a nullable value type to an ordinary value type in this way:
int? myNullableInteger = null;
int myInteger = myNullableInteger;
It prevents one from doing so because the nullable value type could have the value null, which it actually would have in this case, and that value cannot be assigned to an ordinary value type. Although the compiler would permit this code,
int? myNullableInteger = null;
int myInteger = myNullableInteger.Value;
The second statement would cause an exception to be thrown because any attempt to
access the System.Nullable<T>
.Value property is an invalid operation if the type
constructed from System.Nullable<T>
has not been assigned a valid value of T, which has not happened in this case.
One proper way to assign the value of a nullable value type to an ordinary value type is to use the System.Nullable<T>
.HasValue property to ascertain whether a valid value of T has been assigned to the nullable value type:
int? myNullableInteger = null;
if (myNullableInteger.HasValue)
{
int myInteger = myNullableInteger.Value;
}
Another option is to use this syntax:
int? myNullableInteger = null;
int myInteger = myNullableInteger ?? -1;
By which the ordinary integer myInteger is assigned the value of the nullable integer "myNullableInteger" if the latter has been assigned a valid integer value; otherwise, myInteger is assigned the value of -1.
The solution I opted for was to format the date with the mysql query :
String l_mysqlQuery = "SELECT DATE_FORMAT(time, '%Y-%m-%d %H:%i:%s') FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));
I had the exact same issue.
Even though my mysql table contains dates formatted as such : 2017-01-01 21:02:50
String l_mysqlQuery = "SELECT time FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));
was returning a date formatted as such :
2017-01-01 21:02:50.0
Filter: - A filter as the name suggests is a Java class executed by the servlet container for each incoming HTTP request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.
Interceptor: - Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sophisticated behavior because can access to all Spring context.
This is documented on ?logical
. The pertinent section of which is:
Details:
‘TRUE’ and ‘FALSE’ are reserved words denoting logical constants
in the R language, whereas ‘T’ and ‘F’ are global variables whose
initial values set to these. All four are ‘logical(1)’ vectors.
Logical vectors are coerced to integer vectors in contexts where a
numerical value is required, with ‘TRUE’ being mapped to ‘1L’,
‘FALSE’ to ‘0L’ and ‘NA’ to ‘NA_integer_’.
The second paragraph there explains the behaviour you are seeing, namely 5 == 1L
and 5 == 0L
respectively, which should both return FALSE
, where as 1 == 1L
and 0 == 0L
should be TRUE for 1 == TRUE
and 0 == FALSE
respectively. I believe these are not testing what you want them to test; the comparison is on the basis of the numerical representation of TRUE
and FALSE
in R, i.e. what numeric values they take when coerced to numeric.
However, only TRUE
is guaranteed to the be TRUE
:
> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE
isTRUE
is a wrapper for identical(x, TRUE)
, and from ?isTRUE
we note:
Details:
....
‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is
true if and only if ‘x’ is a length-one logical vector whose only
element is ‘TRUE’ and which has no attributes (not even names).
So by the same virtue, only FALSE
is guaranteed to be exactly equal to FALSE
.
> identical(F, FALSE)
[1] TRUE
> identical(0, FALSE)
[1] FALSE
> F <- "hello"
> identical(F, FALSE)
[1] FALSE
If this concerns you, always use isTRUE()
or identical(x, FALSE)
to check for equivalence with TRUE
and FALSE
respectively. ==
is not doing what you think it is.
I use this little PowerShell snippet:
function Get-SystemUptime {
$operatingSystem = Get-WmiObject Win32_OperatingSystem
"$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}
which then yields something like the following:
PS> Get-SystemUptime
6.20:40:40.2625526
They can be considered as equivalent. The limits in size are the same:
There is also the DBCLOBs, for double byte characters.
References:
Solutions mentioned here stopped working, once I enabled Auto Layout. I had to come up with my own:
Subclass UIButton and override layoutSubviews
method:
//
// MIThemeButtonImageAtRight.m
// Created by Lukasz Margielewski on 7/9/13.
//
#import "MIThemeButtonImageAtRight.h"
static CGRect CGRectByApplyingUIEdgeInsets(CGRect frame, UIEdgeInsets insets);
@implementation MIThemeButtonImageAtRight
- (void)layoutSubviews
{
[super layoutSubviews];
CGRect contentFrame = CGRectByApplyingUIEdgeInsets(self.bounds, self.contentEdgeInsets);
CGRect frameIcon = self.imageView.frame;
CGRect frameText = self.titleLabel.frame;
frameText.origin.x = CGRectGetMinX(contentFrame) + self.titleEdgeInsets.left;
frameIcon.origin.x = CGRectGetMaxX(contentFrame) - CGRectGetWidth(frameIcon);
self.imageView.frame = frameIcon;
self.titleLabel.frame = frameText;
}
@end
static CGRect CGRectByApplyingUIEdgeInsets(CGRect frame, UIEdgeInsets insets){
CGRect f = frame;
f.origin.x += insets.left;
f.size.width -= (insets.left + insets.right);
f.origin.y += (insets.top);
f.size.height -= (insets.top + insets.bottom);
return f;
}
Result:
In my case, it was an accidental double escaping.
this works:
SelectedPath = @"C:\Program Files\My Company\My product";
this doesn't:
SelectedPath = @"C:\\Program Files\\My Company\\My product";
try this solution and it is working fine for me
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
<IfModule mod_headers.c>
<FilesMatch "\.(js|css|xml|gz)$">
Header append Vary: Accept-Encoding
</FilesMatch>
</IfModule>
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml text/x-js text/js
</IfModule>
## EXPIRES CACHING ##
The other option for using PHP scripts sans extension is
Options +MultiViews
Or even just following in the directories .htaccess
:
DefaultType application/x-httpd-php
The latter allows having all filenames without extension script
being treated as PHP scripts. While MultiViews makes the webserver look for alternatives, when just the basename is provided (there's a performance hit with that however).
What you need is nm
and its -D
option:
$ nm -D /usr/lib/libopenal.so.1
.
.
.
00012ea0 T alcSetThreadContext
000140f0 T alcSuspendContext
U atanf
U calloc
.
.
.
Exported sumbols are indicated by a T
. Required symbols that must be loaded from other shared objects have a U
. Note that the symbol table does not include just functions, but exported variables as well.
See the nm
manual page for more information.
The best HTTP header for your client to send an access token (JWT or any other token) is the Authorization
header with the Bearer
authentication scheme.
This scheme is described by the RFC6750.
Example:
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIXVCJ9TJV...r7E20RMHrHDcEfxjoYZgeFONFh7HgQ
If you need stronger security protection, you may also consider the following IETF draft: https://tools.ietf.org/html/draft-ietf-oauth-pop-architecture. This draft seems to be a good alternative to the (abandoned?) https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac.
Note that even if this RFC and the above specifications are related to the OAuth2 Framework protocol, they can be used in any other contexts that require a token exchange between a client and a server.
Unlike the custom JWT
scheme you mention in your question, the Bearer
one is registered at the IANA.
Concerning the Basic
and Digest
authentication schemes, they are dedicated to authentication using a username and a secret (see RFC7616 and RFC7617) so not applicable in that context.
We can copy all columns from one table to another, existing table:
INSERT INTO table2 SELECT * FROM table1;
Or we can copy only the columns we want to into another, existing table:
INSERT INTO table2 (column_name(s)) SELECT column_name(s) FROM table1;
or SELECT * INTO BACKUP_TABLE1 FROM TABLE1
If the table you are deleting from has BEFORE/AFTER DELETE triggers, something in there could be causing your delay.
Additionally, if you have foreign keys referencing that table, additional UPDATEs or DELETEs may be occurring.
If your check would have worked, it would have either added all the items, or none at all. However, calling the ToString
method on an array returns the name of the data type, not the contents of the array, and the Contains
method can only look for a single item, not a collection of items anyway.
You have to check each string in the array:
string[] lines3;
List<string> lines2 = new List<string>();
lines3 = Regex.Split(s1, @"\s*,\s*");
foreach (string s in lines3) {
if (!lines2.Contains(s)) {
lines2.Add(s);
}
}
However, if you start with an empty list, you can use the Distinct
method to remove the duplicates, and you only need a single line of code:
List<string> lines2 = Regex.Split(s1, @"\s*,\s*").Distinct().ToList();
The syntax for using an alias in an update statement on SQL Server is as follows:
UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;
The alias should not be necessary here though.
For horizontal alignment (No CSS)
Just insert an align attribute inside the table tag
<table align="center"></table
When the first characters in a script are #!
, that is called the shebang. If your file starts with
#!/path/to/something
the standard is to run something
and pass the rest of the file to that program as an input.
With that said, the difference between #!/bin/bash
, #!/bin/sh
, or even #!/bin/zsh
is whether the bash, sh, or zsh programs are used to interpret the rest of the file. bash
and sh
are just different programs, traditionally. On some Linux systems they are two copies of the same program. On other Linux systems, sh
is a link to dash
, and on traditional Unix systems (Solaris, Irix, etc) bash
is usually a completely different program from sh
.
Of course, the rest of the line doesn't have to end in sh. It could just as well be #!/usr/bin/python
, #!/usr/bin/perl
, or even #!/usr/local/bin/my_own_scripting_language
.
If you want to redirect from a button in the View you could use:
@Html.ActionLink("Back to previous page", null, null, null, new { href = Request.UrlReferrer})
There are many ways of doing this(listed by priority, specific to the OP's problem)
Option 1: Straight approach - Create multiple functions for each type you expect rather than having one generic function.
public static bool ConfigSettingInt(string settingName)
{
return Convert.ToBoolean(ConfigurationManager.AppSettings[settingName]);
}
Option 2: When you don't want to use fancy methods of conversion - Cast the value to object and then to generic type.
public static T ConfigSetting<T>(string settingName)
{
return (T)(object)ConfigurationManager.AppSettings[settingName];
}
Note - This will throw an error if the cast is not valid(your case). I would not recommend doing this if you are not sure about the type casting, rather go for option 3.
Option 3: Generic with type safety - Create a generic function to handle type conversion.
public static T ConvertValue<T,U>(U value) where U : IConvertible
{
return (T)Convert.ChangeType(value, typeof(T));
}
Note - T is the expected type, note the where constraint here(type of U must be IConvertible to save us from the errors)
You don't need ANY of these other fancy answers. Below is a simplistic example that doesn't have all the Margin
, Height
, Width
properties set in the XAML, but should be enough to show how to get this done at a basic level.
XAML
Build a Window
page like you would normally and add your fields to it, say a Label
and TextBox
control inside a StackPanel
:
<StackPanel Orientation="Horizontal">
<Label Name="lblUser" Content="User Name:" />
<TextBox Name="txtUser" />
</StackPanel>
Then create a standard Button
for Submission ("OK" or "Submit") and a "Cancel" button if you like:
<StackPanel Orientation="Horizontal">
<Button Name="btnSubmit" Click="btnSubmit_Click" Content="Submit" />
<Button Name="btnCancel" Click="btnCancel_Click" Content="Cancel" />
</StackPanel>
Code-Behind
You'll add the Click
event handler functions in the code-behind, but when you go there, first, declare a public variable where you will store your textbox value:
public static string strUserName = String.Empty;
Then, for the event handler functions (right-click the Click
function on the button XAML, select "Go To Definition", it will create it for you), you need a check to see if your box is empty. You store it in your variable if it is not, and close your window:
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(txtUser.Text))
{
strUserName = txtUser.Text;
this.Close();
}
else
MessageBox.Show("Must provide a user name in the textbox.");
}
Calling It From Another Page
You're thinking, if I close my window with that this.Close()
up there, my value is gone, right? NO!! I found this out from another site: http://www.dreamincode.net/forums/topic/359208-wpf-how-to-make-simple-popup-window-for-input/
They had a similar example to this (I cleaned it up a bit) of how to open your Window
from another and retrieve the values:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
{
MyPopupWindow popup = new MyPopupWindow(); // this is the class of your other page
//ShowDialog means you can't focus the parent window, only the popup
popup.ShowDialog(); //execution will block here in this method until the popup closes
string result = popup.strUserName;
UserNameTextBlock.Text = result; // should show what was input on the other page
}
}
Cancel Button
You're thinking, well what about that Cancel button, though? So we just add another public variable back in our pop-up window code-behind:
public static bool cancelled = false;
And let's include our btnCancel_Click
event handler, and make one change to btnSubmit_Click
:
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
cancelled = true;
strUserName = String.Empty;
this.Close();
}
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(txtUser.Text))
{
strUserName = txtUser.Text;
cancelled = false; // <-- I add this in here, just in case
this.Close();
}
else
MessageBox.Show("Must provide a user name in the textbox.");
}
And then we just read that variable in our MainWindow
btnOpenPopup_Click
event:
private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
{
MyPopupWindow popup = new MyPopupWindow(); // this is the class of your other page
//ShowDialog means you can't focus the parent window, only the popup
popup.ShowDialog(); //execution will block here in this method until the popup closes
// **Here we find out if we cancelled or not**
if (popup.cancelled == true)
return;
else
{
string result = popup.strUserName;
UserNameTextBlock.Text = result; // should show what was input on the other page
}
}
Long response, but I wanted to show how easy this is using public static
variables. No DialogResult
, no returning values, nothing. Just open the window, store your values with the button events in the pop-up window, then retrieve them afterwards in the main window function.
You should have look at http://en.wikipedia.org/wiki/Breadth-first_search first.
Below is a quick implementation, in which I used a list of list to represent the queue of paths.
# graph is in adjacent list representation
graph = {
'1': ['2', '3', '4'],
'2': ['5', '6'],
'5': ['9', '10'],
'4': ['7', '8'],
'7': ['11', '12']
}
def bfs(graph, start, end):
# maintain a queue of paths
queue = []
# push the first path into the queue
queue.append([start])
while queue:
# get the first path from the queue
path = queue.pop(0)
# get the last node from the path
node = path[-1]
# path found
if node == end:
return path
# enumerate all adjacent nodes, construct a new path and push it into the queue
for adjacent in graph.get(node, []):
new_path = list(path)
new_path.append(adjacent)
queue.append(new_path)
print bfs(graph, '1', '11')
Another approach would be maintaining a mapping from each node to its parent, and when inspecting the adjacent node, record its parent. When the search is done, simply backtrace according the parent mapping.
graph = {
'1': ['2', '3', '4'],
'2': ['5', '6'],
'5': ['9', '10'],
'4': ['7', '8'],
'7': ['11', '12']
}
def backtrace(parent, start, end):
path = [end]
while path[-1] != start:
path.append(parent[path[-1]])
path.reverse()
return path
def bfs(graph, start, end):
parent = {}
queue = []
queue.append(start)
while queue:
node = queue.pop(0)
if node == end:
return backtrace(parent, start, end)
for adjacent in graph.get(node, []):
if node not in queue :
parent[adjacent] = node # <<<<< record its parent
queue.append(adjacent)
print bfs(graph, '1', '11')
The above codes are based on the assumption that there's no cycles.
Here is an updated answer which works in Access 2010 VBA using Data Access Objects (DAO). The table's name is held in TableDef.Name. The collection of all table definitions is held in TableDefs. Here is a quick example of looping through the table names:
Dim db as Database
Dim td as TableDef
Set db = CurrentDb()
For Each td In db.TableDefs
YourSubTakingTableName(td.Name)
Next td
Here is my contribution.
I will not try to list all tools/libraries/plugins that exist to take advantage of Docker with Maven. Some answers have already done it.
instead of, I will focus on applications typology and the Dockerfile way.
Dockerfile
is really a simple and important concept of Docker (all known/public images rely on that) and I think that trying to avoid understanding and using Dockerfile
s is not necessarily the better way to enter in the Docker world.
1) For applications that we want to go on to run them on installed/standalone Java server (Tomcat, JBoss, etc...)
The road is harder and that is not the ideal target because that adds complexity (we have to manage/maintain the server) and it is less scalable and less fast than embedded servers in terms of build/deploy/undeploy.
But for legacy applications, that may considered as a first step.
Generally, the idea here is to define a Docker image for the server and to define an image per application to deploy.
The docker images for the applications produce the expected WAR/EAR but these are not executed as container and the image for the server application deploys the components produced by these images as deployed applications.
For huge applications (millions of line of codes) with a lot of legacy stuffs, and so hard to migrate to a full spring boot embedded solution, that is really a nice improvement.
I will not detail more that approach since that is for minor use cases of Docker but I wanted to expose the overall idea of that approach because I think that for developers facing to these complex cases, it is great to know that some doors are opened to integrate Docker.
2) For applications that embed/bootstrap the server themselves (Spring Boot with server embedded : Tomcat, Netty, Jetty...)
That is the ideal target with Docker.
I specified Spring Boot because that is a really nice framework to do that and that has also a very high level of maintainability but in theory we could use any other Java way to achieve that.
Generally, the idea here is to define a Docker image per application to deploy.
The docker images for the applications produce a JAR or a set of JAR/classes/configuration files and these start a JVM with the application (java command) when we create and start a container from these images.
For new applications or applications not too complex to migrate, that way has to be favored over standalone servers because that is the standard way and the most efficient way of using containers.
I will detail that approach.
1) Without Spring Boot
The idea is to create a fat jar with Maven (the maven assembly plugin and the maven shade plugin help for that) that contains both the compiled classes of the application and needed maven dependencies.
Then we can identify two cases :
if the application is a desktop or autonomous application (that doesn't need to be deployed on a server) : we could specify as CMD/ENTRYPOINT
in the Dockerfile
the java execution of the application : java -cp .:/fooPath/* -jar myJar
if the application is a server application, for example Tomcat, the idea is the same : to get a fat jar of the application and to run a JVM in the CMD/ENTRYPOINT
. But here with an important difference : we need to include some logic and specific libraries (org.apache.tomcat.embed
libraries and some others) that starts the embedded server when the main application is started.
We have a comprehensive guide on the heroku website.
For the first case (autonomous application), that is a straight and efficient way to use Docker.
For the second case (server application), that works but that is not straight, may be error prone and is not a very extensible model because you don't place your application in the frame of a mature framework such as Spring Boot that does many of these things for you and also provides a high level of extension.
But that has a advantage : you have a high level of freedom because you use directly the embedded Tomcat API.
2) With Spring Boot
At last, here we go.
That is both simple, efficient and very well documented.
There are really several approaches to make a Maven/Spring Boot application to run on Docker.
Exposing all of them would be long and maybe boring.
The best choice depends on your requirement.
But whatever the way, the build strategy in terms of docker layers looks like the same.
We want to use a multi stage build : one relying on Maven for the dependency resolution and for build and another one relying on JDK or JRE to start the application.
Build stage (Maven image) :
mvn dependency:resolve-plugins
chained to mvn dependency:resolve
may do the job but not always.package
execution to package the fat jar may rely on different artifacts/plugins and even for a same artifact/plugin, these may still pull a different version.
So a safer approach while potentially slower is resolving dependencies by executing exactly the mvn
command used to package the application (which will pull exactly dependencies that you are need) but by skipping the source compilation and by deleting the target folder to make the processing faster and to prevent any undesirable layer change detection for that step. Run stage (JDK or JRE image) :
Here two examples.
a) A simple way without cache for downloaded maven dependencies
Dockerfile :
########Maven build stage########
FROM maven:3.6-jdk-11 as maven_build
WORKDIR /app
#copy pom
COPY pom.xml .
#resolve maven dependencies
RUN mvn clean package -Dmaven.test.skip -Dmaven.main.skip -Dspring-boot.repackage.skip && rm -r target/
#copy source
COPY src ./src
# build the app (no dependency download here)
RUN mvn clean package -Dmaven.test.skip
# split the built app into multiple layers to improve layer rebuild
RUN mkdir -p target/docker-packaging && cd target/docker-packaging && jar -xf ../my-app*.jar
########JRE run stage########
FROM openjdk:11.0-jre
WORKDIR /app
#copy built app layer by layer
ARG DOCKER_PACKAGING_DIR=/app/target/docker-packaging
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/BOOT-INF/lib /app/lib
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/BOOT-INF/classes /app/classes
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/META-INF /app/META-INF
#run the app
CMD java -cp .:classes:lib/* \
-Djava.security.egd=file:/dev/./urandom \
foo.bar.MySpringBootApplication
Drawback of that solution ? Any changes in the pom.xml means re-creates the whole layer that download and stores the maven dependencies. That is generally not acceptable for applications with many dependencies (and Spring Boot pulls many dependencies), overall if you don't use a maven repository manager during the image build.
b) A more efficient way with cache for maven dependencies downloaded
The approach is here the same but maven dependencies downloads that are cached in the docker builder cache.
The cache operation relies on buildkit (experimental api of docker).
To enable buildkit, the env variable DOCKER_BUILDKIT=1 has to be set (you can do that where you want : .bashrc, command line, docker daemon json file...).
Dockerfile :
# syntax=docker/dockerfile:experimental
########Maven build stage########
FROM maven:3.6-jdk-11 as maven_build
WORKDIR /app
#copy pom
COPY pom.xml .
#copy source
COPY src ./src
# build the app (no dependency download here)
RUN --mount=type=cache,target=/root/.m2 mvn clean package -Dmaven.test.skip
# split the built app into multiple layers to improve layer rebuild
RUN mkdir -p target/docker-packaging && cd target/docker-packaging && jar -xf ../my-app*.jar
########JRE run stage########
FROM openjdk:11.0-jre
WORKDIR /app
#copy built app layer by layer
ARG DOCKER_PACKAGING_DIR=/app/target/docker-packaging
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/BOOT-INF/lib /app/lib
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/BOOT-INF/classes /app/classes
COPY --from=maven_build ${DOCKER_PACKAGING_DIR}/META-INF /app/META-INF
#run the app
CMD java -cp .:classes:lib/* \
-Djava.security.egd=file:/dev/./urandom \
foo.bar.MySpringBootApplication
This was the best solution I found that works reliably.
function round(value, decimals) {
return Number(Math.floor(parseFloat(value + 'e' + decimals)) + 'e-' + decimals);
}
Credit to: Jack L Moore's blog
You need both a value and a field to assign it to. The value is TableField + 1
, so the assignment is:
SET TableField = TableField + 1
What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.
On a rooted device, you may be able to bypass the message using either
the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup>
is set to any value but "mifareclassic" or "all". For instance, you could use:
<CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet>
that already exists in that file).
Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).
This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode
) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK
.
You should use options.addAll(allPoints);
instead of options.add(point);
As of now, the Go compiler generates identical code in both cases, so it is a matter of taste. GCCGo does generate different code, but barely anyone uses it so I wouldn't worry about that.
The return type of Html.RenderAction
is void
that means it directly renders the responses in View where the return type of Html.Action
is MvcHtmlString
You can catch its render view in controller and modify it by using following method
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
This will return the Html string of the View.
This is also applicable to Html.Partial
and Html.RenderPartial
Taking into account that the separator can be more than one space/tab and that we want to preserve them:
public static String reverse(String string)
{
StringBuilder sb = new StringBuilder(string.length());
StringBuilder wsb = new StringBuilder(string.length());
for (int i = 0; i < string.length(); i++)
{
char c = string.charAt(i);
if (c == '\t' || c == ' ')
{
if (wsb.length() > 0)
{
sb.append(wsb.reverse().toString());
wsb = new StringBuilder(string.length() - sb.length());
}
sb.append(c);
}
else
{
wsb.append(c);
}
}
if (wsb.length() > 0)
{
sb.append(wsb.reverse().toString());
}
return sb.toString();
}
Another option is to use \dfrac instead of \frac, which makes the whole fraction larger and hence more readable.
And no, I don't know if there is an option to get something in between \frac and \dfrac, sorry.
Makefile part of the question
This is pretty easy, unless you don't need to generalize try something like the code below (but replace space indentation with tabs near g++)
SRC_DIR := .../src
OBJ_DIR := .../obj
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))
LDFLAGS := ...
CPPFLAGS := ...
CXXFLAGS := ...
main.exe: $(OBJ_FILES)
g++ $(LDFLAGS) -o $@ $^
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<
Automatic dependency graph generation
A "must" feature for most make systems. With GCC in can be done in a single pass as a side effect of the compilation by adding -MMD
flag to CXXFLAGS
and -include $(OBJ_FILES:.o=.d)
to the end of the makefile body:
CXXFLAGS += -MMD
-include $(OBJ_FILES:.o=.d)
And as guys mentioned already, always have GNU Make Manual around, it is very helpful.
As of Rails 5, the rake
commandline tool has been aliased as rails
so now
rails db:reset
instead of rake db:reset
will work just as well
a = 0.000006;
b = 6;
c = a/b;
textbox.Text = c.ToString("0.000000");
As you requested:
textbox.Text = c.ToString("0.######");
This will only display out to the 6th decimal place if there are 6 decimals to display.
Use .. LIMIT :pageSize OFFSET :pageStart
Where :pageStart
is bound to the_page_index (i.e. 0 for the first page) * number_of_items_per_pages (e.g. 4) and :pageSize
is bound to number_of_items_per_pages.
To detect for "has more pages", either use SQL_CALC_FOUND_ROWS or use .. LIMIT :pageSize OFFSET :pageStart + 1
and detect a missing last (pageSize+1) record. Needless to say, for pages with an index > 0, there exists a previous page.
If the page index value is embedded in the URL (e.g. in "prev page" and "next page" links) then it can be obtained via the appropriate $_GET
item.
you should use position:fixed
to make z-index
values to apply to your div
Something like this should work:
INSERT INTO #IMEIS (imei) VALUES ('val1'), ('val2'), ...
UPDATE:
Apparently this syntax is only available starting on SQL Server 2008.
Original answer using git's start-ssh-agent
Make sure you have Git installed and have git's cmd
folder in your PATH. For example, on my computer the path to git's cmd folder is C:\Program Files\Git\cmd
Make sure your id_rsa
file is in the folder c:\users\yourusername\.ssh
Restart your command prompt if you haven't already, and then run start-ssh-agent
. It will find your id_rsa
and prompt you for the passphrase
Update 2019 - A better solution if you're using Windows 10: OpenSSH is available as part of Windows 10 which makes using SSH from cmd/powershell much easier in my opinion. It also doesn't rely on having git installed, unlike my previous solution.
Open Manage optional features
from the start menu and make sure you have Open SSH Client
in the list. If not, you should be able to add it.
Open Services
from the start Menu
Scroll down to OpenSSH Authentication Agent
> right click > properties
Change the Startup type from Disabled to any of the other 3 options. I have mine set to Automatic (Delayed Start)
Open cmd and type where ssh
to confirm that the top listed path is in System32. Mine is installed at C:\Windows\System32\OpenSSH\ssh.exe
. If it's not in the list you may need to close and reopen cmd.
Once you've followed these steps, ssh-agent, ssh-add and all other ssh commands should now work from cmd. To start the agent you can simply type ssh-agent
.
GIT_SSH
environment variable to the output of where ssh
which you ran before (e.g C:\Windows\System32\OpenSSH\ssh.exe
). This is to stop inconsistencies between the version of ssh you're using (and your keys are added/generated with) and the version that git uses internally. This should prevent issues that are similar to thisSome nice things about this solution:
id_rsa
Hope this helps
Use the below code
val hidePasswordMethod = PasswordTransformationMethod()
showOrHidePasswordButton.setOnClickListener {
passwordEditText.apply {
transformationMethod =
if (transformationMethod is PasswordTransformationMethod)
null //shows password
else
hidePasswordMethod //hides password
}
}
and make sure you add this to your password edittext in layout
android:inputType="textPassword"
To suppress warnings while leaving all other error reporting enabled:
error_reporting(E_ALL ^ E_WARNING);
As an alternative to homebrew, you could download and install macports. Once you have macports, you can use:
sudo port install apache-ant
It's in the python docs.
import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1),
datetime.time(10, 23))
returns
datetime.datetime(2011, 1, 1, 10, 23)
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Toast;
import com.example.fyp.R;
import java.util.Locale;
import cn.pedant.SweetAlert.SweetAlertDialog;
public class textTospeech_class extends AppCompatActivity {
TextToSpeech textToSpeech;
String text;
int result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_tospeech);
textToSpeech = new TextToSpeech(textTospeech_class.this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(textTospeech_class.this, "Not Support in your device", Toast.LENGTH_SHORT).show();
}
}
});
}
public void tts(View view)
{
switch (view.getId()) {
case R.id.speechid:
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(textTospeech_class.this, "Not Support in your device", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak("a for apple", TextToSpeech.QUEUE_FLUSH, null);
}
break;
case R.id.bid:
{
if(result==TextToSpeech.LANG_MISSING_DATA || result== TextToSpeech.LANG_NOT_SUPPORTED)
{
Toast.makeText(textTospeech_class.this, "Not Support in your device", Toast.LENGTH_SHORT).show();
}
else
{
textToSpeech.speak("b for ball",TextToSpeech.QUEUE_FLUSH,null);
}
break;
}
}
You can modify various VM properties by adding the following configuration (see the Vagrant docs for a bit more info):
# Configure VM Ram usage
config.vm.customize [
"modifyvm", :id,
"--name", "Test_Environment",
"--memory", "1024"
]
You can obtain the properties that you want to change from the documents for VirtualBox command-line options:
The vagrant documentation has the section on how to change IP address:
Vagrant::Config.run do |config|
config.vm.network :hostonly, "192.168.50.4"
end
Also you can restructure the configuration like this, ending is do with end without nesting it. This is simpler.
config.vm.define :web do |web_config|
web_config.vm.box = "lucid32"
web_config.vm.forward_port 80, 8080
end
web_config.vm.provision :puppet do |puppet|
puppet.manifests_path = "manifests"
puppet.manifest_file = "lucid32.pp"
end
In Chrome, there is "Task Manager", accessible via Shift+ESC or through
Menu → More Tools → Task Manager
You can select your page task and end it by pressing "End Process" button.
Although it's often frowned upon, you can technically use:
display: inline !important;
It generally isn't good practice but in some cases might be necessary. What you should do is edit your code so that you aren't applying a style to the <li>
elements in the first place.
In order to avoid this kind of ClassCastException, if you have:
class A
class B extends A
You can define a constructor in B that takes an object of A. This way we can do the "cast" e.g.:
public B(A a) {
super(a.arg1, a.arg2); //arg1 and arg2 must be, at least, protected in class A
// If B class has more attributes, then you would initilize them here
}
The argument to remove()
is a filter document, so passing in an empty document means 'remove all':
db.user.remove({})
However, if you definitely want to remove everything you might be better off dropping the collection. Though that probably depends on whether you have user defined indexes on the collection i.e. whether the cost of preparing the collection after dropping it outweighs the longer duration of the remove()
call vs the drop()
call.
More details in the docs.
According to this example Random.nextInt(n)
has less predictable output then Math.random() * n. According to [sorted array faster than an unsorted array][1] I think we can say Random.nextInt(n) is hard to predict.
usingRandomClass : time:328 milesecond.
usingMathsRandom : time:187 milesecond.
package javaFuction;
import java.util.Random;
public class RandomFuction
{
static int array[] = new int[9999];
static long sum = 0;
public static void usingMathsRandom() {
for (int i = 0; i < 9999; i++) {
array[i] = (int) (Math.random() * 256);
}
for (int i = 0; i < 9999; i++) {
for (int j = 0; j < 9999; j++) {
if (array[j] >= 128) {
sum += array[j];
}
}
}
}
public static void usingRandomClass() {
Random random = new Random();
for (int i = 0; i < 9999; i++) {
array[i] = random.nextInt(256);
}
for (int i = 0; i < 9999; i++) {
for (int j = 0; j < 9999; j++) {
if (array[j] >= 128) {
sum += array[j];
}
}
}
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
usingRandomClass();
long end = System.currentTimeMillis();
System.out.println("usingRandomClass " + (end - start));
start = System.currentTimeMillis();
usingMathsRandom();
end = System.currentTimeMillis();
System.out.println("usingMathsRandom " + (end - start));
}
}
It works for me when I define the complete border
property. (JSFiddle here)
.field_set{
border: 1px #F00 solid;
}?
the reason is the border-style
that is set to none
by default for fieldsets. You need to override that as well.
public void dateDifferenceExample() {
// Set the date for both of the calendar instance
GregorianCalendar calDate = new GregorianCalendar(2012, 10, 02,5,23,43);
GregorianCalendar cal2 = new GregorianCalendar(2015, 04, 02);
// Get the represented date in milliseconds
long millis1 = calDate.getTimeInMillis();
long millis2 = cal2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = millis2 - millis1;
// Calculate difference in seconds
long diffSeconds = diff / 1000;
// Calculate difference in minutes
long diffMinutes = diff / (60 * 1000);
// Calculate difference in hours
long diffHours = diff / (60 * 60 * 1000);
// Calculate difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);
Toast.makeText(getContext(), ""+diffSeconds, Toast.LENGTH_SHORT).show();
}
To reduce the lag i would recommend the follwing steps
my pc specs : 2 gb ram, processor: intel core2 duo
first kill all background process, if you have server or database running you could stop them first with following commands
sudo service apache2 stop
sudo service mysql stop
Then enable power saving mode in android studio by file>powersaving mode
It could disable background process, and then studio appears to go well
Along with the latest software (latest Eclipse and Java) and more RAM, you may need to
I dissent from both the answers. Don't create a reference at all, but use late binding:
Dim objExcelApp As Object
Dim wb As Object
Sub Initialize()
Set objExcelApp = CreateObject("Excel.Application")
End Sub
Sub ProcessDataWorkbook()
Set wb = objExcelApp.Workbooks.Open("path to my workbook")
Dim ws As Object
Set ws = wb.Sheets(1)
ws.Cells(1, 1).Value = "Hello"
ws.Cells(1, 2).Value = "World"
'Close the workbook
wb.Close
Set wb = Nothing
End Sub
You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().
This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there's a different version of Excel installed, or if it's installed in a different location.
Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.
I had a similar problem. The catalina.out logged this log Message
Apr 17, 2013 5:14:46 PM org.apache.catalina.core.StandardContext start SEVERE: Error listenerStart
Check the localhost.log in the tomcat log directory (in the same directory as catalina.out), to see the exception which caused this error.
Webview in Activity,Below code worked for me , Finish the activity the after load the Url in webview.in onbackpressed it go to the previous activity
webView = (WebView) findViewById(R.id.info_webView);
webView.loadUrl(value);
finish();
DataTable formerSlidesData = new DataTable();
DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
if (formerSlidesData.Rows.Count > 0)
{
DataRow rowa = formerSlidesData.Rows[0];
cabinet = Convert.ToInt32(rowa["cabinet"]);
box = Convert.ToInt32(rowa["box"]);
drawer = Convert.ToInt32(rowa["drawer"]);
}
We can force the checksum validation in maven with at least two options:
1.Adding the --strict-checksums
to our maven command.
2.Adding the following configuration to our maven settings file:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd">
<!--...-->
<profiles>
<profile>
<!--...-->
<repositories>
<repository>
<id>codehausSnapshots</id>
<name>Codehaus Snapshots</name>
<releases>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>fail</checksumPolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
<checksumPolicy>fail</checksumPolicy>
</snapshots>
<url>
<!--...-->
</url>
</repository>
</repositories>
<pluginRepositories>
<!--...-->
</pluginRepositories>
<!--...-->
</profile>
</profiles>
<!--...-->
</settings>
More details in this post: https://dzone.com/articles/maven-artifact-checksums-what
At runtime they behave a exactly the same.The bytecode may/not be same (For above Incase,it generates the same bytecode(complie above and check javaap -c;))
At runtime they behave a exactly the same.method(math::max);,it generates the same math (complie above and check javap -c;))
To give a bit more explanation, Python will automatically construct its search paths (as mentioned above and here) using the site.py
script (typically located in sys.prefix + lib/python<version>/site-packages
as well as lib/site-python
). One can obtain the value of sys.prefix:
python -c 'import sys; print(sys.prefix)'
The site.py script then adds a number of directories, dependent upon the platform, such as /usr/{lib,share}/python<version>/dist-packages
, /usr/local/lib/python<version>/dist-packages
to the search path and also searches these paths for <package>.pth
config files which contain specific additional search paths. For example easy-install maintains its collection of installed packages which are added to a system specific file e.g on Ubuntu it's /usr/local/lib/python2.7/dist-packages/easy-install.pth
. On a typical system there are a bunch of these .pth files around which can explain some unexpected paths in sys.path:
python -c 'import sys; print(sys.path)'
So one can create a .pth file and put in any of these directories (including the sitedir as mentioned above). This seems to be the way most packages get added to the sys.path as opposed to using the PYTHONPATH.
Note: On OSX there's a special additional search path added by site.py for 'framework builds' (but seems to work for normal command line use of python): /Library/Python/<version>/site-packages
(e.g. for Python2.7: /Library/Python/2.7/site-packages/
) which is where 3rd party packages are supposed to be installed (see the README in that dir). So one can add a path configuration file in there containing additional search paths e.g. create a file called /Library/Python/2.7/site-packages/pip-usr-local.pth
which contains /usr/local/lib/python2.7/site-packages/
and then the system python will add that search path.
Or just like this in Kotlin:
val tv = findViewById(R.id.textViewOne) as TextView
tv.setTypeface(null, Typeface.BOLD_ITALIC)
// OR
tv.setTypeface(null, Typeface.BOLD or Typeface.ITALIC)
// OR
tv.setTypeface(null, Typeface.BOLD)
// OR
tv.setTypeface(null, Typeface.ITALIC)
// AND
tv.paintFlags = tv.paintFlags or Paint.UNDERLINE_TEXT_FLAG
Or in Java:
TextView tv = (TextView)findViewById(R.id.textViewOne);
tv.setTypeface(null, Typeface.BOLD_ITALIC);
// OR
tv.setTypeface(null, Typeface.BOLD|Typeface.ITALIC);
// OR
tv.setTypeface(null, Typeface.BOLD);
// OR
tv.setTypeface(null, Typeface.ITALIC);
// AND
tv.setPaintFlags(tv.getPaintFlags()|Paint.UNDERLINE_TEXT_FLAG);
Keep it simple and in one line :)
I assume that each house is stored in its own table and has an 'id' field, e.g house id. So when you loop through the houses and display them, you could do something like this:
<a href="house.php?id=<?php echo $house_id;?>">
<?php echo $house_name;?>
</a>
Then in house.php, you would get the house id using $_GET['id']
, validate it using is_numeric()
and then display its info.
Typically by setting a default value for a parameter:
int func(int a, int b = -1) {
std::cout << "a = " << a;
if (b != -1)
std::cout << ", b = " << b;
std::cout << "\n";
}
int main() {
func(1, 2); // prints "a=1, b=2\n"
func(3); // prints "a=3\n"
return 0;
}
The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an id of “basicModal” will appear.
@ECHO OFF
:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/
:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"
:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m
:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m
PAUSE
I think you need to use Expr
with ->set()
(However THIS IS NOT SAFE and you shouldn't do it):
$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
->set('u.username', $qb->expr()->literal($username))
->set('u.email', $qb->expr()->literal($email))
->where('u.id = ?1')
->setParameter(1, $editId)
->getQuery();
$p = $q->execute();
It's much safer to make all your values parameters instead:
$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
->set('u.username', '?1')
->set('u.email', '?2')
->where('u.id = ?3')
->setParameter(1, $username)
->setParameter(2, $email)
->setParameter(3, $editId)
->getQuery();
$p = $q->execute();
You did not need
Options Indexes FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order Allow,Deny
Allow from all
Require all granted
the only thing what you need is...
Require all granted
...inside the directory section.
See Apache 2.4 upgrading side:
It's worth noting that retro-fitting unit tests into existing code is far more difficult than driving the creation of that code with tests in the first place. That's one of the big questions in dealing with legacy applications... how to unit test? This has been asked many times before (so you may be closed as a dupe question), and people usually end up here:
Moving existing code to Test Driven Development
I second the accepted answer's book recommendation, but beyond that there's more information linked in the answers there.
i dont know if the full resolution has been made for this yet. i know that from doing a 2 column page with fixed left side bar, to get a contact us form centered on my page i put the following:
form {
width: 100%;
margin-left: auto;
margin-right: auto;
display: inline-block;
}
this worked for me so thought id throw in my resolution to the same problem
What's happening is Chart.js multiplies the size of the canvas when it is called then attempts to scale it back down using CSS, the purpose being to provide higher resolution graphs for high-dpi devices.
The problem is it doesn't realize it has already done this, so when called successive times, it multiplies the already (doubled or whatever) size AGAIN until things start to break. (What's actually happening is it is checking whether it should add more pixels to the canvas by changing the DOM attribute for width and height, if it should, multiplying it by some factor, usually 2, then changing that, and then changing the css style attribute to maintain the same size on the page.)
For example, when you run it once and your canvas width and height are set to 300, it sets them to 600, then changes the style attribute to 300... but if you run it again, it sees that the DOM width and height are 600 (check the other answer to this question to see why) and then sets it to 1200 and the css width and height to 600.
Not the most elegant solution, but I solved this problem while maintaining the enhanced resolution for retina devices by simply setting the width and height of the canvas manually before each successive call to Chart.js
var ctx = document.getElementById("canvas").getContext("2d");
ctx.canvas.width = 300;
ctx.canvas.height = 300;
var myDoughnut = new Chart(ctx).Doughnut(doughnutData);
Today things have changed a little.
Now we avoid use ProgressDialog to show spinning progress:
If you want to put in your app a spinning progress you should use an Activity indicators:
http://developer.android.com/design/building-blocks/progress.html#activity
You can use xargs:
seq 10 | xargs
or
seq 10 | xargs echo -n
var myError = new Error('foo');
myError instanceof Error // true
var myString = "Whatever";
myString instanceof Error // false
Only problem with this is
myError instanceof Object // true
An alternative to this would be to use the constructor property.
myError.constructor === Object // false
myError.constructor === String // false
myError.constructor === Boolean // false
myError.constructor === Symbol // false
myError.constructor === Function // false
myError.constructor === Error // true
Although it should be noted that this match is very specific, for example:
myError.constructor === TypeError // false
Try this,
IFS=''
while read line
do
echo $line
done < file.txt
EDIT:
From man bash
IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with the read builtin command. The default value is
``<space><tab><newline>''
Adding to the existing answers, an alias could be created to show the diff and/or log prior to a merge. Many answers omit the fetch
to be done first before "previewing" the merge; this is an alias that combines these two steps into one (emulating something similar to mercurial's hg incoming
/ outgoing
)
So, building on "git log ..otherbranch
", you can add the following to ~/.gitconfig
:
...
[alias]
# fetch and show what would be merged (use option "-p" to see patch)
incoming = "!git remote update -p; git log ..@{u}"
For symmetry, the following alias can be used to show what is committed and would be pushed, prior to pushing:
# what would be pushed (currently committed)
outgoing = log @{u}..
And then you can run "git incoming
" to show a lot of changes, or "git incoming -p
" to show the patch (i.e., the "diff"), "git incoming --pretty=oneline
", for a terse summary, etc. You may then (optionally) run "git pull
" to actually merge. (Though, since you've already fetched, the merge could be done directly.)
Likewise, "git outgoing
" shows what would be pushed if you were to run "git push
".
One thing you can do is to set your axis range by yourself by using matplotlib.pyplot.axis.
matplotlib.pyplot.axis
from matplotlib import pyplot as plt
plt.axis([0, 10, 0, 20])
0,10 is for x axis range. 0,20 is for y axis range.
or you can also use matplotlib.pyplot.xlim or matplotlib.pyplot.ylim
matplotlib.pyplot.ylim
plt.ylim(-2, 2)
plt.xlim(0,10)
Just make sure you add box-sizing:border-box;
to your #myWorkContent
.
A recursive algorithm that parses through an XmlDocument
Here is an example - Recursively reading an xml document and using regex to get contents
Here is another recursive example - http://www.java2s.com/Tutorial/CSharp/0540__XML/LoopThroughXmlDocumentRecursively.html
All this might not help say when you use rails remote form button to simulate click to. I tried to port nice event simulation from prototype here: my snippets. Just did it and it works for me.
This can't be done with the normal printf
format specifiers. The closest you could get would be:
printf("%.6g", 359.013); // 359.013
printf("%.6g", 359.01); // 359.01
but the ".6" is the total numeric width so
printf("%.6g", 3.01357); // 3.01357
breaks it.
What you can do is to sprintf("%.20g")
the number to a string buffer then manipulate the string to only have N characters past the decimal point.
Assuming your number is in the variable num, the following function will remove all but the first N
decimals, then strip off the trailing zeros (and decimal point if they were all zeros).
char str[50];
sprintf (str,"%.20g",num); // Make the number.
morphNumericString (str, 3);
: :
void morphNumericString (char *s, int n) {
char *p;
int count;
p = strchr (s,'.'); // Find decimal point, if any.
if (p != NULL) {
count = n; // Adjust for more or less decimals.
while (count >= 0) { // Maximum decimals allowed.
count--;
if (*p == '\0') // If there's less than desired.
break;
p++; // Next character.
}
*p-- = '\0'; // Truncate string.
while (*p == '0') // Remove trailing zeros.
*p-- = '\0';
if (*p == '.') { // If all decimals were zeros, remove ".".
*p = '\0';
}
}
}
If you're not happy with the truncation aspect (which would turn 0.12399
into 0.123
rather than rounding it to 0.124
), you can actually use the rounding facilities already provided by printf
. You just need to analyse the number before-hand to dynamically create the widths, then use those to turn the number into a string:
#include <stdio.h>
void nDecimals (char *s, double d, int n) {
int sz; double d2;
// Allow for negative.
d2 = (d >= 0) ? d : -d;
sz = (d >= 0) ? 0 : 1;
// Add one for each whole digit (0.xx special case).
if (d2 < 1) sz++;
while (d2 >= 1) { d2 /= 10.0; sz++; }
// Adjust for decimal point and fractionals.
sz += 1 + n;
// Create format string then use it.
sprintf (s, "%*.*f", sz, n, d);
}
int main (void) {
char str[50];
double num[] = { 40, 359.01335, -359.00999,
359.01, 3.01357, 0.111111111, 1.1223344 };
for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {
nDecimals (str, num[i], 3);
printf ("%30.20f -> %s\n", num[i], str);
}
return 0;
}
The whole point of nDecimals()
in this case is to correctly work out the field widths, then format the number using a format string based on that. The test harness main()
shows this in action:
40.00000000000000000000 -> 40.000
359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.010
359.00999999999999090505 -> 359.010
3.01357000000000008200 -> 3.014
0.11111111099999999852 -> 0.111
1.12233439999999995429 -> 1.122
Once you have the correctly rounded value, you can once again pass that to morphNumericString()
to remove trailing zeros by simply changing:
nDecimals (str, num[i], 3);
into:
nDecimals (str, num[i], 3);
morphNumericString (str, 3);
(or calling morphNumericString
at the end of nDecimals
but, in that case, I'd probably just combine the two into one function), and you end up with:
40.00000000000000000000 -> 40
359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.01
359.00999999999999090505 -> 359.01
3.01357000000000008200 -> 3.014
0.11111111099999999852 -> 0.111
1.12233439999999995429 -> 1.122
First, you split the data using split
:
split(z,z$Group)
Than, for each chunk, select the row with max Score:
lapply(split(z,z$Group),function(chunk) chunk[which.max(chunk$Score),])
Finally reduce back to a data.frame do.call
ing rbind
:
do.call(rbind,lapply(split(z,z$Group),function(chunk) chunk[which.max(chunk$Score),]))
Result:
Group Score Info
1 1 3 c
2 2 4 d
One line, no magic spells, fast, result has good names =)
You should try this:
df_total = data.frame()
for (i in 1:7){
# vector output
model <- #some processing
# add vector to a dataframe
df <- data.frame(model)
df_total <- rbind(df_total,df)
}
I know this is a late answer, but I found this question because I had the same problem. I think I found the answer in this post on lexandera.com. The code below is basically a cut-and-paste from the site. It seems to do the trick.
final Context myApp = this;
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
@JavascriptInterface
@SuppressWarnings("unused")
public void processHTML(String html)
{
// process the html as needed by the app
}
}
final WebView browser = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);
/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
browser.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
});
/* load a web page */
browser.loadUrl("http://lexandera.com/files/jsexamples/gethtml.html");
This will work, make sure your control Event is assigned to this code, it has probably been lost, I also noticed that Double click will only work if the cell is not empty. Try double clicking on a cell with content, don't mess with the designer
private void dgvReport_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
//do something
}
delete de out directory and .ide folder work for me
<div
style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;"
unselectable="on"
onselectstart="return false;"
onmousedown="return false;">
Blabla
</div>
That's probably the best from the performance point of view, but it's rough:
String element = "el5";
String s;
int x = element.charAt(2)-'0';
It works if you assume your character is a digit, and only in languages always using Unicode, like Java...
In my point of view,
If you dont use Integrated security=SSPI,then you need to hardcode the username and password in the connection string which means "relatively insecure" why because, all the employees have the access even ex-employee could use the information maliciously.
Sipwiz is correct the only way to do this properly is the HTTP and DNS hybrid approach. My registrar is a re-seller for Tucows and they offer root domain forwarding as a free value added service.
If your domain is blah.com they will ask you where you would like the domain forwarded to, and you type in www.blah.com. They assign the A record to their apache server and automaticly add blah.com as a DNS vhost. The vhost responds with an HTTP 302 error redirecting them to the proper URL. It's simple to script/setup and can be handled by low end would otherwise be scrapped hardware.
Run the following command for an example: curl -v eclecticengineers.com
Our array of objects
var someData = [
{firstName: "Max", lastName: "Mustermann", age: 40},
{firstName: "Hagbard", lastName: "Celine", age: 44},
{firstName: "Karl", lastName: "Koch", age: 42},
];
with for...in
var employees = {
accounting: []
};
for(var i in someData) {
var item = someData[i];
employees.accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
}
or with Array.prototype.map()
, which is much cleaner:
var employees = {
accounting: []
};
someData.map(function(item) {
employees.accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
}
I think you have got it in that last attempt, you just need to grab the string.. in Chrome's console..
startdate = moment();
startdate.subtract(1, 'd');
startdate.format('DD-MM-YYYY');
"14-04-2015"
startdate = moment();
startdate.subtract(1, 'd');
myString = startdate.format('DD-MM-YYYY');
"14-04-2015"
myString
"14-04-2015"
You have more static resources that the cache has room for. You can do one of the following:
For more details see the documentation for these configuration options.
your answer is throwing errors because of this line
readings = int(readings)
I used Christian's Feb 12 solution and I'm also just beginning to learn PowerShell. As far as attachments, I was poking around with Get-Member learning how it works and noticed that Send() has two definitions... the second definition takes a System.Net.Mail.MailMessage object which allows for Attachments and many more powerful and useful features like Cc and Bcc. Here's an example that has attachments (to be mixed with his above example):
# append to Christian's code above --^
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
$emailMessage.To.Add($EmailTo)
$emailMessage.Subject = $Subject
$emailMessage.Body = $Body
$emailMessage.Attachments.Add("C:\Test.txt")
$SMTPClient.Send($emailMessage)
Enjoy!
I had a similar problem and since I couldn't find a sufficient solution, I also created a serialization library for javascript: https://github.com/wavesoft/jbb (as a matter of fact it's a bit more, since it's mainly intended for bundling resources)
It is close to Binary-JSON but it adds a couple of additional features, such as metadata for the objects being encoded and some extra optimizations like data de-duplication, cross-referencing to other bundles and structure-level compression.
However there is a catch: In order to keep the bundle size small there are no type information in the bundle. Such information are provided in a separate "profile" that describes your objects for encoding and decoding. For optimization reasons this information is given in a form of script.
But you can make your life easier using the gulp-jbb-profile
(https://github.com/wavesoft/gulp-jbb-profile) utility for generating the encodeing/decoding scripts from simple YAML object specifications like this:
# The 'Person' object has the 'age' and 'isOld'
# properties
Person:
properties:
- age
- isOld
For example you can have a look on the jbb-profile-three
profile.
When you have your profile ready, you can use JBB like this:
var JBBEncoder = require('jbb/encode');
var MyEncodeProfile = require('profile/profile-encode');
// Create a new bundle
var bundle = new JBBEncoder( 'path/to/bundle.jbb' );
// Add one or more profile(s) in order for JBB
// to understand your custom objects
bundle.addProfile(MyEncodeProfile);
// Encode your object(s) - They can be any valid
// javascript object, or objects described in
// the profiles you added previously.
var p1 = new Person(77);
bundle.encode( p1, 'person' );
var people = [
new Person(45),
new Person(77),
...
];
bundle.encode( people, 'people' );
// Close the bundle when you are done
bundle.close();
And you can read it back like this:
var JBBDecoder = require('jbb/decode');
var MyDecodeProfile = require('profile/profile-decode');
// Instantiate a new binary decoder
var binaryLoader = new JBBDecoder( 'path/to/bundle' );
// Add your decoding profile
binaryLoader.addProfile( MyDecodeProfile );
// Add one or more bundles to load
binaryLoader.add( 'bundle.jbb' );
// Load and callback when ready
binaryLoader.load(function( error, database ) {
// Your objects are in the database
// and ready to use!
var people = database['people'];
});
Excellent solution! I noticed when I tried to implement it that if I returned a value in the success clause, it came back as undefined. I had to store it in a variable and return that variable. This is the method I came up with:
function getWhatever() {
// strUrl is whatever URL you need to call
var strUrl = "", strReturn = "";
jQuery.ajax({
url: strUrl,
success: function(html) {
strReturn = html;
},
async:false
});
return strReturn;
}
If anyone still looking for a quick solution and don't want dependencies like jquery etc I wrote a mini lib that add expiration to local / session / custom storage, you can find it with source here:
seems the Ctrl+Break doesn't work on me, neither the Preference - User...
use keys, Alt ? t ? c
Just an update for Mysqli users :
$base= mysqli_connect($dbhost, $dbuser, $dbpass, $dbbase);
if (mysqli_connect_errno())
die('Could not connect: ' . mysql_error());
$return_arr = array();
if ($result = mysqli_query( $base, $sql )){
while ($row = mysqli_fetch_assoc($result)) {
$row_array['id'] = $row['id'];
$row_array['col1'] = $row['col1'];
$row_array['col2'] = $row['col2'];
array_push($return_arr,$row_array);
}
}
mysqli_close($base);
echo json_encode($return_arr);
Try using some shell magic: %%sh
%%sh pip install geocoder
let me know if it works, thanks
You can use the MailDefinition class.
This is how you use it:
MailDefinition md = new MailDefinition();
md.From = "[email protected]";
md.IsBodyHtml = true;
md.Subject = "Test of MailDefinition";
ListDictionary replacements = new ListDictionary();
replacements.Add("{name}", "Martin");
replacements.Add("{country}", "Denmark");
string body = "<div>Hello {name} You're from {country}.</div>";
MailMessage msg = md.CreateMailMessage("[email protected]", replacements, body, new System.Web.UI.Control());
Also, I've written a blog post on how to generate HTML e-mail body in C# using templates using the MailDefinition class.
If you specify the option 'openany' in the \documentclass declaration each chapter in the book (I'm guessing you're using the book class as chapters open on the next page in reports and articles don't have chapters) will open on a new page, not necessarily the next odd-numbered page.
Of course, that's not quite what you want. I think you want to set openany for chapters in the appendix. 'fraid I don't know how to do that, I suspect that you need to roll up your sleeves and wrestle with TeX itself
Set it with a px value. Changing the code like below should work
el.css('marginLeft', mrg + 'px');
I could get solution for such a similar problem with addition of a simple line
HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");
My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.
Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.
if you use .Values while creating the matrix X and Y vectors it will fix the problem.
y=dataset.iloc[:, 4].values
X=dataset.iloc[:, 0:4].values
when you use .Values it creates a Object representation of the created matrix will be returned with the axes removed. Check the below link for more information
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html
Personally, I use Emacs with hexl-mod.
Emacs is able to work with really huge files. You can use search/replace value easily. Finally, you can use 'ediff' to do some diffs.
If you were trying to do what I imagine you were trying to do, then you only have to treat scope like a regular JS object.
This is what I use for an API success response for JSON data array...
function(data){
$scope.subjects = [];
$.each(data, function(i,subject){
//Store array of data types
$scope.subjects.push(subject.name);
//Split data in to arrays
$scope[subject.name] = subject.data;
});
}
Now {{subjects}} will return an array of data subject names, and in my example there would be a scope attribute for {{jobs}}, {{customers}}, {{staff}}, etc. from $scope.jobs, $scope.customers, $scope.staff
Trying to connect to your local computer.try with the hostname "localhost" instead or perhaps ::/ - the last one is ipv6
Using simple html,
<div>
<object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
</object>
</div>
Or jquery,
<script>
$("#mydiv")
.html('<object data="http://your-website-domain"/>');
</script>
The XML (extensible Markup Language) is used often XHR because this is a standard broadcasting language, what can be used by any programming language, and supported both server and client side, so this is the most flexible solution. The XML can be separated for more parts so a specified group can develop the part of the program, without affecting the other parts. The XML format can also be determined by the XML DTD or XML Schema (XSL) and can be tested.
The JSON a data-exchange format which is getting more popular as the JavaScript applications possible format. Basically this is an object notation array. JSON has a very simple syntax so can be easily learned. And also the JavaScript support parsing JSON with the eval
function. On the other hand, the eval
function has got negatives. For example, the program can be very slow parsing JSON and because of security the eval
can be very risky. This not mean that the JSON is not good, just we have to be more careful.
My suggestion is that you should use JSON for applications with light data-exchange, like games. Because you don't have to really care about the data-processing, this is very simple and fast.
The XML is best for the bigger websites, for example shopping sites or something like this. The XML can be more secure and clear. You can create basic data-struct and schema to easily test the correction and separate it into parts easily.
I suggest you use XML because of the speed and the security, but JSON for lightweight stuff.
just override onCreateOptionsMenu like this in your MainPage.java
@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, menu);
return true;
}
Another simple way:
$("#selectedID")[0].selectedIndex = -1
Looks like there is more to be done for Rails 4.
Inside you Gemfile add.
gem 'bootstrap-sass', '~> 3.2.0.2'
Next you need to run
$bundle install
This is the part no one has mentioned
Open you config/application.rb file
add this right before the second to last end
config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif)
as seen here about a 20% down the page.
Next create a custom.css.scss file in this directory
app/assets/stylesheets
as seen here a little further down from the above task
Inside that file include
@import "bootstrap";
Now stop your server and restart and everything should work fine.
I tried to run bootstrap without using a gem but it didn't work for me.
Hope that helps someone out!
If you want to replace lot of values in single go, you can use 'library(car)'.
Example
library(car)
x <- rep(1:5,3)
xr <- recode(x, '3=1; 4=2')
x
## [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
xr
## [1] 1 2 1 2 5 1 2 1 2 5 1 2 1 2 5
From the documentation (any version):
It is your application’s responsibility to dismiss the keyboard at the time of your choosing. You might dismiss the keyboard in response to a specific user action, such as the user tapping a particular button in your user interface. You might also configure your text field delegate to dismiss the keyboard when the user presses the “return” key on the keyboard itself. To dismiss the keyboard, send the resignFirstResponder message to the text field that is currently the first responder. Doing so causes the text field object to end the current editing session (with the delegate object’s consent) and hide the keyboard.
So, you have to send resignFirstResponder somehow. But there is a possibility that textfield loses focus another way during processing of textFieldShouldReturn: message. This also will cause keyboard to disappear.
I know this question already has an accepted answer, but for me, a .NET beginner, there was a simple solution to what I was doing wrong and I thought I'd share.
I had been doing this:
@Html.HiddenFor(Model.Foo.Bar.ID)
What worked for me was changing to this:
@Html.HiddenFor(m => m.Foo.Bar.ID)
(where "m" is an arbitrary string to represent the model object)
select * from tbl where col like 'ABC%'
or col like 'XYZ%'
or col like 'PQR%';
This works in toad and powerbuilder. Don't know about the rest
Actually, the best solution for this question is to use checkout
commend
git checkout <branch> <path1>,<path2> ..
For example, assume you are in master, you want to the changes from dev1 on project1/Controller/WebController1.java
and project1/Service/WebService1.java
, you can use this:
git checkout dev1 project1/Controller/WebController1.java project1/Service/WebService1.java
That means the master branch only updates from dev1 on those two paths.
Try the following:
<script>
//Functions to open database and to create, insert data into tables
getSelectedRow = function(val)
{
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM Employ where number = ?;',[parseInt(val)], selectedRowValues, errorHandler);
});
};
selectedRowValues = function(transaction,results)
{
for(var i = 0; i < results.rows.length; i++)
{
var row = results.rows.item(i);
alert(row['number']);
alert(row['name']);
}
};
</script>
You don't have access to javascript variable names in SQL, you must pass the values to the Database.
In version r75 of three.js, you should use:
var loader = new THREE.TextureLoader();
loader.load('texture.png', function ( texture ) {
var geometry = new THREE.SphereGeometry(1000, 20, 20);
var material = new THREE.MeshBasicMaterial({map: texture, overdraw: 0.5});
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
});
Here's a quick two-liner that I use to quickly create a file if it doesn't exists.
if not os.path.exists(filename):
open(filename, 'w').close()
You can use white-space: nowrap;
to define this behaviour:
// HTML:
.nowrap {_x000D_
white-space: nowrap ;_x000D_
}
_x000D_
<p>_x000D_
<span class="nowrap">How do I wrap this line of text</span>_x000D_
<span class="nowrap">- asked by Peter 2 days ago</span>_x000D_
</p>
_x000D_
// CSS:
.nowrap {
white-space: nowrap ;
}
what is Intent ?
It is a kind of message or information that is passed to the components. It is used to launch an activity, display a web page, send sms, send email etc.
There are two types of intents in android:
Implicit Intent
Explicit Intent
Implicit intent is used to invoke the system components
Example
Intent i = newIntent(android.content.Intent.ACTION_VIEW,Uri.parse(“http://www.amazon.com”));
startActivity(i);
Explicit intent is used to invoke the activity class.
Example
Intent intent = newIntent (this, SecondActivity.class);
startActivity(intent);
you can read more
http://www.vogella.com/tutorials/AndroidIntent/article.html#intents_overview http://developer.android.com/reference/android/content/Intent.html
Make a div and use your image ( png with transparent background ) as the background of the div, then you can apply any text within that div to hover over the button. Something like this:
<div class="button" onclick="yourbuttonclickfunction();" >
Your Button Label Here
</div>
CSS:
.button {
height:20px;
width:40px;
background: url("yourimage.png");
}
I see that there is already some great advice and methods suggest for how to get the post back control. However I found another web page (Mahesh blog) with a method to retrieve post back control ID.
I will post it here with a little modification, including making it an extension class. Hopefully it is more useful in that way.
/// <summary>
/// Gets the ID of the post back control.
///
/// See: http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
/// </summary>
/// <param name = "page">The page.</param>
/// <returns></returns>
public static string GetPostBackControlId(this Page page)
{
if (!page.IsPostBack)
return string.Empty;
Control control = null;
// first we will check the "__EVENTTARGET" because if post back made by the controls
// which used "_doPostBack" function also available in Request.Form collection.
string controlName = page.Request.Params["__EVENTTARGET"];
if (!String.IsNullOrEmpty(controlName))
{
control = page.FindControl(controlName);
}
else
{
// if __EVENTTARGET is null, the control is a button type and we need to
// iterate over the form collection to find it
// ReSharper disable TooWideLocalVariableScope
string controlId;
Control foundControl;
// ReSharper restore TooWideLocalVariableScope
foreach (string ctl in page.Request.Form)
{
// handle ImageButton they having an additional "quasi-property"
// in their Id which identifies mouse x and y coordinates
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
controlId = ctl.Substring(0, ctl.Length - 2);
foundControl = page.FindControl(controlId);
}
else
{
foundControl = page.FindControl(ctl);
}
if (!(foundControl is IButtonControl)) continue;
control = foundControl;
break;
}
}
return control == null ? String.Empty : control.ID;
}
Update (2016-07-22): Type check for Button
and ImageButton
changed to look for IButtonControl
to allow postbacks from third party controls to be recognized.
Short answer: Add a constructor with no argument in base/parent/super class. i.e for example,
class Parent{
String name;
int age;
String occupation;
//empty constructor
public Parent(){
}
public Parent(String name, int age, String employment){
this.name = name;
this.age = age;
this.occupation = employment;
}
}
// You can have any additional constructors as you wish aka constructor overloading here in parent class.
If a super class does not have the no-argument constructor then you will get the compile-time error. Object does have such the constructor, so if Object is a only super class then there is no problem.
// then let's inherit
class Child extends Parent{
Child(String name, int age){
this.name = name;
this.age = age;
}
}
With super(), a super class no-argument constructor is called and with super(parameter list), a super class constructor with the matching parameter list is called.
1.THE USE OF {}:
It initialize the array with the values { }
2.The difference between String array=new String[]; and String array=new String[]{};
String array=new String[]; and String array=new String[]{}; both are invalid statement in java.
It will gives you an error that you are trying to assign String array to String datatype. More specifically error is like this Type mismatch: cannot convert from String[] to String
3.String array=new String[10]{}; got error why?
Wrong because you are defining an array of length 10 ([10]), then defining an array of length String[10]{} 0