I recently encountered this issue with .eot and .otf fonts producing the CSS3114 and CSS3111 errors in the console when loading. The solution that worked for me was to use only .woff and .woff2 formats with a .ttf format fallback. The .woff formats will be used before .ttf in most browsers and don't seem to trigger the font embedding permissions issue (css3114) and the font naming incorrect format issue (css3111). I found my solution in this extremely helpful article about the CSS3111 and CSS3114 issue, and also reading this article on using @font-face.
note: This solution does not require re-compiling, converting or editing any font files. It is a css-only solution. The font I tested with did have .eot, .otf, .woff, .woff2 and .svg versions generated for it, probably from the original .ttf source which did produce the 3114 error when i tried it, however the .woff and .woff2 files seemed to be immune to this issue.
This is what DID work for me with @font-face:
@font-face {
font-family: "Your Font Name";
font-weight: normal;
src: url('your-font-name.woff2') format('woff2'),
url('your-font-name.woff') format('woff'),
url('your-font-name.ttf') format('truetype');
}
This was what triggered the errors with @font-face in IE:
@font-face {
font-family: 'Your Font Name';
src: url('your-font-name.eot');
src: url('your-font-name.eot?#iefix') format('embedded-opentype'),
url('your-font-name.woff2') format('woff2'),
url('your-font-name.woff') format('woff'),
url('your-font-name.ttf') format('truetype'),
url('your-font-name.svg#svgFontName') format('svg');
}
Ok so I was having this issue where I tried several different options.
The font i'm using is Ubuntu-LI , I created a font folder in my working directory. under the folder fonts
I was able to apply it... eventually here is my working code
I wanted this to apply to my entire website so I put it at the top of the css doc. above all of the Div tags (not that it matters, just know that any individual fonts you assign post your script will take precedence)
@font-face{
font-family: "Ubuntu-LI";
src: url("/fonts/Ubuntu/(Ubuntu-LI.ttf"),
url("../fonts/Ubuntu/Ubuntu-LI.ttf");
}
*{
font-family:"Ubuntu-LI";
}
If i then wanted all of my H1 tags to be something else lets say sans sarif I would do something like
h1{
font-family: Sans-sarif;
}
From which case only my H1 tags would be the sans-sarif font and the rest of my page would be the Ubuntu-LI font
Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).
(I don't see anything obviously wrong with the code you have posted above)
Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?
we had similar header issue with Amazon (AWS) S3 presigned Post failing on some browsers.
point was to tell bucket CORS to expose header <ExposeHeader>Access-Control-Allow-Origin</ExposeHeader>
more details in this answer: https://stackoverflow.com/a/37465080/473040
First of all, you can't prevent people from downloading fonts except if it is yours and that usually takes months. And it makes no sense to prevent people from using fonts. A lot of fonts that you see on websites can be found on free platforms like the one I mentioned below.
But if you want to implement a font into your website read this: There is a pretty simple and free way to implement fonts into your website. I would recommend Google fonts because it is free and easy to use. For example, I'll use the Bangers font from Google.(https://fonts.google.com/specimen/Bangers?query=bangers&sidebar.open&selection.family=Bangers) This is how it would look like: HTML
<head>
<link href="https://fonts.googleapis.com/css2?family=Bangers&display=swap" rel="stylesheet">
</head>
CSS
body {
font-family: 'Bangers', cursive;
}
nowadays,2017-12-17. I don't find any description about Font-property-order‘s necessity in spec. And I test in chrome always works whatever the order is.
@font-face {
font-family: 'Font Awesome 5 Free';
font-weight: 900;
src: url('#{$fa-font-path}/fa-solid-900.eot');
src: url('#{$fa-font-path}/fa-solid-900.eot?#iefix') format('embedded-opentype'),
url('#{$fa-font-path}/fa-solid-900.woff2') format('woff2'),
url('#{$fa-font-path}/fa-solid-900.woff') format('woff'),
url('#{$fa-font-path}/fa-solid-900.ttf') format('truetype'),
url('#{$fa-font-path}/fa-solid-900.svg#fontawesome') format('svg');
}
@font-face {
font-family: 'Font Awesome 5 Free';
font-weight: 400;
src: url('#{$fa-font-path}/fa-regular-400.eot');
src: url('#{$fa-font-path}/fa-regular-400.eot?#iefix') format('embedded-opentype'),
url('#{$fa-font-path}/fa-regular-400.woff2') format('woff2'),
url('#{$fa-font-path}/fa-regular-400.woff') format('woff'),
url('#{$fa-font-path}/fa-regular-400.ttf') format('truetype'),
url('#{$fa-font-path}/fa-regular-400.svg#fontawesome') format('svg');
}
file:///
)Firefox comes with a very strict "file uri origin" (file:///
) policy by default: to have it to behave just as other browsers, go to about:config
, filter by fileuri
and toggle the following preference:
security.fileuri.strict_origin_policy
Set it to false and you should be able to load local font resources across different path levels.
As per my comment below, and you are experiencing this problem after deploying your site, you could try to add an additional header to see if your problem configures itself as a cross domain issue: it shouldn't, since you are specifying relative paths, but i would give it a try anyway: in your .htaccess file, specify you want to send an additional header for each .ttf/.otf/.eot file being requested:
<FilesMatch "\.(ttf|otf|eot)$">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
</FilesMatch>
Frankly, I wouldn't expect it to make any difference, but it's so simple it's worth trying: else try to use base64 encoding for your font typeface, ugly but it may works too.
A nice recap is available here
Woff is a compressed (zipped) form of the TrueType - OpenType font. It is small and can be delivered over the network like a graphic file. Most importantly, this way the font is preserved completely including rendering rule tables that very few people care about because they use only Latin script.
Take a look at [dead URL removed]. The font you see is an experimental web delivered smartfont (woff) that has thousands of combined characters making complex shapes. The underlying text is simple Latin code of romanized Singhala. (Copy and paste to Notepad and see).
Only woff can do this because nobody has this font and yet it is seen anywhere (Mac, Win, Linux and even on smartphones by all browsers except by IE. IE does not have full support for Open Types).
If your Rails version is between > 3.1.0
and < 4
, place your fonts in any of the these folders:
app/assets/fonts
lib/assets/fonts
vendor/assets/fonts
For Rails versions > 4
, you must place your fonts in the app/assets/fonts
folder.
Note: To place fonts outside of these designated folders, use the following configuration:
config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/
For Rails versions > 4.2
, it is recommended to add this configuration to config/initializers/assets.rb
.
However, you can also add it to either config/application.rb
, or to config/production.rb
Declare your font in your CSS file:
@font-face {
font-family: 'Icomoon';
src:url('icomoon.eot');
src:url('icomoon.eot?#iefix') format('embedded-opentype'),
url('icomoon.svg#icomoon') format('svg'),
url('icomoon.woff') format('woff'),
url('icomoon.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
Make sure your font is named exactly the same as in the URL portion of the declaration. Capital letters and punctuation marks matter. In this case, the font should have the name icomoon
.
If you are using Sass or Less with Rails > 3.1.0
(your CSS file has .scss
or .less
extension), then change the url(...)
in the font declaration to font-url(...)
.
Otherwise, your CSS file should have the extension .css.erb
, and the font declaration should be url('<%= asset_path(...) %>')
.
If you are using Rails > 3.2.1
, you can use font_path(...)
instead of asset_path(...)
. This helper does exactly the same thing but it's more clear.
Finally, use your font in your CSS like you declared it in the font-family
part. If it was declared capitalized, you can use it like this:
font-family: 'Icomoon';
From the Google Font Directory examples:
@font-face {
font-family: 'Tangerine';
font-style: normal;
font-weight: normal;
src: local('Tangerine'), url('http://example.com/tangerine.ttf') format('truetype');
}
body {
font-family: 'Tangerine', serif;
font-size: 48px;
}
This works cross browser with .ttf, I believe it may work with .otf. (Wikipedia says .otf is mostly backwards compatible with .ttf) If not, you can convert the .otf to .ttf
Here are some good sites:
Good primer:
Other Info:
Recently I was working on a game compatible with CocoonJS with DOM limited to the canvas element - here is my approach:
Using fillText with a font that has not been loaded yet will execute properly but with no visual feedback - so the canvas plane will stay intact - all you have to do is periodically check the canvas for any changes (for example looping through getImageData searching for any non transparent pixel) that will happen when the font loads properly.
I have explained this technique a little bit more in my recent article http://rezoner.net/preloading-font-face-using-canvas,686
? works really well. The HTML code is ✖
.
An alternative is ✕
: ?
If you want to check for local files first do:
@font-face {
font-family: 'Green Sans Web';
src:
local('Green Web'),
local('GreenWeb-Regular'),
url('GreenWeb.ttf');
}
There is a more elaborate description of what to do here.
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Thin.otf);
font-weight: 200;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Light.otf);
font-weight: 300;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Regular.otf);
font-weight: normal;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Bold.otf);
font-weight: bold;
}
h3, h4, h5, h6 {
font-size:2em;
margin:0;
padding:0;
font-family:Kaffeesatz;
font-weight:normal;
}
h6 { font-weight:200; }
h5 { font-weight:300; }
h4 { font-weight:normal; }
h3 { font-weight:bold; }
It looks like it only works in Internet Explorer, but a quick Google search for "html embed fonts" yields http://www.spoono.com/html/tutorials/tutorial.php?id=19
If you want to stay platform-agnostic (and you should!) you'll have to use images, or else just use a standard font.
You can use multiple font faces quite easily. Below is an example of how I used it in the past:
<!--[if (IE)]><!-->
<style type="text/css" media="screen">
@font-face {
font-family: "Century Schoolbook";
src: url(/fonts/century-schoolbook.eot);
}
@font-face {
font-family: "Chalkduster";
src: url(/fonts/chalkduster.eot);
}
</style>
<!--<![endif]-->
<!--[if !(IE)]><!-->
<style type="text/css" media="screen">
@font-face {
font-family: "Century Schoolbook";
src: url(/fonts/century-schoolbook.ttf);
}
@font-face {
font-family: "Chalkduster";
src: url(/fonts/chalkduster.ttf);
}
</style>
<!--<![endif]-->
It is worth noting that fonts can be funny across different Browsers. Font face on earlier browsers works, but you need to use eot files instead of ttf.
That is why I include my fonts in the head of the html file as I can then use conditional IE tags to use eot or ttf files accordingly.
If you need to convert ttf to eot for this purpose there is a brilliant website you can do this for free online, which can be found at http://ttf2eot.sebastiankippe.com/.
Hope that helps.
This worked for me and also worked with bootstrap tables
<style>
.table td, .table th {
font-size: 10px;
}
</style>
There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml
. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml
mediatype.
Check this link.. It will definitely solve your problem.. There are plenty of solutions to make cross domain GET Ajax calls BUT POST REQUEST FOR CROSS DOMAIN IS SOLVED HERE. It took me 3 days to figure it out.
I have network throttling disabled but started to get this error today on a 75mb/s business connection...
To fix it in my build of Chrome 60.0.3112.90 (Official Build) (64-bit) I opened the DevTools then navigated to the DevTools Settings then ticked 'Log XMLHttpRequests', unticked 'User messages only' and 'Hide network messages'
If still not works after adding MIME types, please check whether "Anonymous Authentication" is enable in Authentication section in the site and make sure to select "Application pool identity" as per the given screen shot.
Instead of forcing an F5 keypress when you're just trying to get the page to postback, you can call a postback based on a JS event (even mousemove or timer_tick if you want it to fire all the time). Use the code at http://weblogs.asp.net/mnolton/archive/2003/06/04/8260.aspx as a reference.
function remove_prefix($text, $prefix) {
if(0 === strpos($text, $prefix))
$text = substr($text, strlen($prefix)).'';
return $text;
}
@Eddie has given a perfect answer of the question asked. But I would like to draw attention to using an more efficient approach of Pub/Sub.
As this answer suggests,
The $broadcast/$on approach is not terribly efficient as it broadcasts to all the scopes(Either in one direction or both direction of Scope hierarchy). While the Pub/Sub approach is much more direct. Only subscribers get the events, so it isn't going to every scope in the system to make it work.
you can use angular-PubSub
angular module. once you add PubSub
module to your app dependency, you can use PubSub
service to subscribe and unsubscribe events/topics.
Easy to subscribe:
// Subscribe to event
var sub = PubSub.subscribe('event-name', function(topic, data){
});
Easy to publish
PubSub.publish('event-name', {
prop1: value1,
prop2: value2
});
To unsubscribe, use PubSub.unsubscribe(sub);
OR PubSub.unsubscribe('event-name');
.
NOTE Don't forget to unsubscribe to avoid memory leaks.
I try the below way and it work for me:
1. open cmd.exe
2. takeown /R /F *.*
3. icacls * /T /grant [username]:(D)
4. del *.* /S /Q
So that the files can become my own access and it assign to "Delete" and then I can delete the files and folders.
Example:
git tag -a v1.2 9fceb02 -m "Message here"
Where 9fceb02
is the beginning part of the commit id.
You can then push the tag using git push origin v1.2
.
You can do git log
to show all the commit id's in your current branch.
There is also a good chapter on tagging in the Pro Git book.
Warning: This creates tags with the current date (and that value is what will show on a GitHub releases page, for example). If you want the tag to be dated with the commit date, please look at another answer.
keep the currently selected drop down value with chosen jquery in a global variable before writing the drop down 'on change' action function. If you want to set previous value in the function you can use the global variable.
//global variable
var previousValue=$("#dropDownList").val();
$("#dropDownList").change(function () {
BootstrapDialog.confirm(' Are you sure you want to continue?',
function (result) {
if (result) {
return true;
} else {
$("#dropDownList").val(previousValue).trigger('chosen:updated');
return false;
}
});
});
You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:
1.) change type of ID to int
instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea
First option requires to change every table that has a reference to this table, BUT it's worth it.
in my case this worked perfectly
<img style="border-radius: 50%;height: 50px;width: 80px;" src="<?php echo asset("storage/TeacherImages/{$studydata->teacher->profilePic}")?>">
this code is used to display image from folder
To put HTML/Word in an Excel Shape and locate it on an Excel Cell:
In this way, even HTML with tables and other stuff does not get split over multiple cells.
private void btnPutHTMLIntoExcelShape_Click(object sender, EventArgs e)
{
var fFile = new FileInfo(@"C:\Temp\temp.html");
StreamWriter SW = fFile.CreateText();
SW.Write(hecNote.DocumentHtml);
SW.Close();
Word.Application wrdApplication;
Word.Document wrdDocument;
wrdApplication = new Word.Application();
wrdApplication.Visible = true;
wrdDocument = wrdApplication.Documents.Add(@"C:\Temp\temp.html");
wrdDocument.ActiveWindow.Selection.WholeStory();
wrdDocument.ActiveWindow.Selection.Copy();
Excel.Application excApplication;
Excel.Workbook excWorkbook;
Excel._Worksheet excWorksheet;
Excel.Range excRange = null;
excApplication = new Excel.Application();
excApplication.Visible = true;
excWorkbook = excApplication.Workbooks.Add(Type.Missing);
excWorksheet = (Excel.Worksheet)excWorkbook.Worksheets.get_Item(1);
excWorksheet.Name = "Work";
excRange = excWorksheet.get_Range("A1");
excRange.Select();
excWorksheet.PasteSpecial("Microsoft Word Document Object");
Excel.Shape O = excWorksheet.Shapes.Item(1);
this.Text = $"{O.Height} x {O.Width}";
((Excel.Range)excWorksheet.Rows[1, Type.Missing]).RowHeight = O.Height;
}
There are a lot of sources for selenium - here is good one for simple use Selenium, and here is a example snippet too Selenium Examples
You can find a lot of good sources to use selenium, it's not too hard to get it set up and start using it.
if(MyGuid!=Guild.Empty)
{
//Valid Guild
}
else {
// Invalid Guild
}
In addition to Nick Craver's answer, for this to work properly on IE 8
you need to add a additional click handler to the checkbox:
// needed for IE 8 compatibility
if ($.browser.msie)
$("#myCheckbox").click(function() { $(this).trigger('change'); });
$("#myCheckbox").change( function() {
alert($(this).is(":checked"));
});
//Trigger by:
$("#myCheckbox").trigger('click').trigger('change');
Otherwise the callback will only be triggered when the checkbox loses focus, as IE 8
keeps focus on checkboxes and radios when they are clicked.
Haven't tested on IE 9
though.
I had the same issue and I installed this cordova plugin and problem solved.
cordova plugin add cordova-android-support-gradle-release --save
Including the implementation file (test.c
) causes it to be prepended to your main.c and complied there and then again separately. So, the function test
has two definitions -- one in the object code of main.c
and once in that of test.c
, which gives you a ODR violation. You need to create a header file containing the declaration of test
and include it in main.c
:
/* test.h */
#ifndef TEST_H
#define TEST_H
void test(); /* declaration */
#endif /* TEST_H */
WHy bother with all of the fancy selectors? If you're using those id="" attributes properly, then 'test2' must be the only tag with that id on the page, then the .checked boolean property will tell you if it's checked or not:
if ($('test2').checked) {
....
}
You've also not set any values for those radio buttons, so no matter which button you select, you'll just get a blank "testGroup=" submitted to the server.
You can simply use Apache Commons Lang:
result = ObjectUtils.compare(firstComparable, secondComparable)
This is what I did:
HTML
<div id="divProgress"></div>
<div id="divStepTitle">
<span class="spanStep">Step 1</span> <span class="spanStep">Step 2</span> <span class="spanStep">Step 3</span>
</div>
<input type="button" id="btnPrev" name="btnPrev" value="Prev" />
<input type="button" id="btnNext" name="btnNext" value="Next" />
CSS
#divProgress
{
width: 600px;
}
#divStepTitle
{
width: 600px;
}
.spanStep
{
text-align: center;
width: 200px;
}
Javascript/jQuery
var progress = 0;
$(function({
//set step progress bar
$("#divProgress").progressbar();
//event handler for prev and next button
$("#btnPrev, #btnNext").click(function(){
step($(this));
});
});
function step(obj)
{
//switch to prev/next page
if (obj.val() == "Prev")
{
//set new value for progress bar
progress -= 20;
$("#divProgress").progressbar({ value: progress });
//do extra step for showing previous page
}
else if (obj.val() == "Next")
{
//set new value for progress bar
progress += 20;
$("#divProgress").progressbar({ value: progress });
//do extra step for showing next page
}
}
I have not seen any option in Microsoft SQL Server Management Studio 2012 to-date that will do that.
I am sure you can write something in T-SQL given the time.
Check out TOAD from QUEST - now owned by DELL.
http://www.toadworld.com/products/toad-for-oracle/f/10/t/9778.aspx
Select your rows.
Rt -click -> Export Dataset.
Choose Insert Statement format
Be sure to check “selected rows only”
Nice thing about toad, it works with both SQL server and Oracle. If you have to work with both, it is a good investment.
Post.find().sort({date:-1}, function(err, posts){
});
Should work as well
EDIT:
You can also try using this if you get the error sort() only takes 1 Argument
:
Post.find({}, {
'_id': 0, // select keys to return here
}, {sort: '-date'}, function(err, posts) {
// use it here
});
HTC One m7 running fresh Cyanogenmod 11.
Phone is connected USB and tethering my data connection.
Then I get this surprise:
cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb shell
error: insufficient permissions for device
cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
???????????? no permissions
SOLUTION: Turn tethering OFF on phone.
cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
HT36AW908858 device
First Declare Permission in Android Manifest:-
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
MainActivityForDownloadImages.java
public class MainActivityForDownloadImages extends AppCompatActivity {
// String urls = "https://stimg.cardekho.com/images/carexteriorimages/930x620/Kia/Kia-Seltos/6232/1562746799300/front-left-side-47.jpg";
String urls = "https://images5.alphacoders.com/609/609173.jpg";
Button button;
public final Context context = this;
ProgressDialog progressDialog ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_for_download_images);
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
progressDialog = new ProgressDialog(context);
button = findViewById(R.id.downloadImagebtn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// initialize the progress dialog like in the first example
// this is how you fire the downloader
Intent intent = new Intent(context, DownloadService.class);
intent.putExtra("url", urls);
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
}
}
}
private class DownloadReceiver extends ResultReceiver {
public DownloadReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress"); //get the progress
progressDialog.setProgress(progress);
progressDialog.setMessage("Images Is Downloading");
progressDialog.show();
if (progress == 100) {
progressDialog.dismiss();
}
}
}
}
}
DownloadService.java
public class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
String folder_main = "ImagesFolder";
public DownloadService() {
super("DownloadService");
}
@Override
protected void onHandleIntent(Intent intent) {
String urlToDownload = intent.getStringExtra("url");
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
//create url and connect
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream());
File outerFolder = new File(Environment.getExternalStorageDirectory(), folder_main);
File inerDire = new File(outerFolder.getAbsoluteFile(), System.currentTimeMillis() + ".jpg");
if (!outerFolder.exists()) {
outerFolder.mkdirs();
}
inerDire.createNewFile();
FileOutputStream output = new FileOutputStream(inerDire);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress", (int) (total * 100 / fileLength));
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
// close streams
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress", 100);
receiver.send(UPDATE_PROGRESS, resultData);
}
}
There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:
url: 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',
to this line:
url: '/path/to/phpscript.php',
and then in the php script (if you have permission to use the file_get_contents() function):
<?php
header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
?>
Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.
Edit: If you want to cache the result in php, here's the php file you would use:
<?php
$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
$contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
file_put_contents($cacheName, $contents);
}
$xml = simplexml_load_file($cacheName);
header('Content-type: application/xml');
echo $xml;
?>
Caching code take from here.
Solution:
CREATE TRIGGER `IdTrigger` BEFORE INSERT ON `payments`
FOR EACH ROW
BEGIN
SELECT AUTO_INCREMENT Into @xId
FROM information_schema.tables
WHERE
Table_SCHEMA ="DataBaseName" AND
table_name = "payments";
SET NEW.`payment_code` = CONCAT("sahf4d2fdd45",@xId);
END;
"DataBaseName" is the name of our Data Base
The standard error is just the standard deviation divided by the square root of the sample size. So you can easily make your own function:
> std <- function(x) sd(x)/sqrt(length(x))
> std(c(1,2,3,4))
[1] 0.6454972
You might want to check a few things:
You production server allows remote connections. (possible that someone turned this off, especially if you have a DBA)
Check your connection string. Sometimes if you are using an ip address or server name this will cause this error. Try both.
It really depends on the situation, for me its in fpm as I'm using PHP5-FPM. A solution to your problem could be a universal php.ini and then using a symbolic link created like:
ln -s /etc/php5/php.ini php.ini
Then any modifications you make will be in one general .ini file. This is probably not really the best solution though, you might want to look into modifying some configuration so that you literally use one file, on one location. Not multiple locations hacked together.
pass the data using javascript ajax from get methods
**//javascript function
function addnewcustomer(){
//This function run when button click
//get the value from input box using getElementById
var new_cust_name = document.getElementById("new_customer").value;
var new_cust_cont = document.getElementById("new_contact_number").value;
var new_cust_email = document.getElementById("new_email").value;
var new_cust_gender = document.getElementById("new_gender").value;
var new_cust_cityname = document.getElementById("new_cityname").value;
var new_cust_pincode = document.getElementById("new_pincode").value;
var new_cust_state = document.getElementById("new_state").value;
var new_cust_contry = document.getElementById("new_contry").value;
//create json or if we know python that is call dictionary.
var data = {"cust_name":new_cust_name, "cust_cont":new_cust_cont, "cust_email":new_cust_email, "cust_gender":new_cust_gender, "cust_cityname":new_cust_cityname, "cust_pincode":new_cust_pincode, "cust_state":new_cust_state, "cust_contry":new_cust_contry};
//apply stringfy method on json
data = JSON.stringify(data);
//insert data into database using javascript ajax
var send_data = new XMLHttpRequest();
send_data.open("GET", "http://localhost:8000/invoice_system/addnewcustomer/?customerinfo="+data,true);
send_data.send();
send_data.onreadystatechange = function(){
if(send_data.readyState==4 && send_data.status==200){
alert(send_data.responseText);
}
}
}
django views
def addNewCustomer(request):
#if method is get then condition is true and controller check the further line
if request.method == "GET":
#this line catch the json from the javascript ajax.
cust_info = request.GET.get("customerinfo")
#fill the value in variable which is coming from ajax.
#it is a json so first we will get the value from using json.loads method.
#cust_name is a key which is pass by javascript json.
#as we know json is a key value pair. the cust_name is a key which pass by javascript json
cust_name = json.loads(cust_info)['cust_name']
cust_cont = json.loads(cust_info)['cust_cont']
cust_email = json.loads(cust_info)['cust_email']
cust_gender = json.loads(cust_info)['cust_gender']
cust_cityname = json.loads(cust_info)['cust_cityname']
cust_pincode = json.loads(cust_info)['cust_pincode']
cust_state = json.loads(cust_info)['cust_state']
cust_contry = json.loads(cust_info)['cust_contry']
#it print the value of cust_name variable on server
print(cust_name)
print(cust_cont)
print(cust_email)
print(cust_gender)
print(cust_cityname)
print(cust_pincode)
print(cust_state)
print(cust_contry)
return HttpResponse("Yes I am reach here.")**
Alternative:
library(stringr)
a = c("capitalise this", "and this")
a
[1] "capitalise this" "and this"
str_to_title(a)
[1] "Capitalise This" "And This"
This data is JSON! You can deserialize it using the built-in json
module if you're on Python 2.6+, otherwise you can use the excellent third-party simplejson
module.
import json # or `import simplejson as json` if on Python < 2.6
json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string) # obj now contains a dict of the data
You can minimize the command prompt on during the run but you'll need two additional scripts: windowMode and getCmdPid.bat:
@echo off
call getCmdPid
call windowMode -pid %errorlevel% -mode minimized
cd /d C:\leads\ssh
call C:\Ruby192\bin\setrbvars.bat
ruby C:\leads\ssh\put_leads.rb
SQL 2008
Radim Köhler's answer works, but here is a shorter version:
select top 20 * from
(
select *,
ROW_NUMBER() OVER (ORDER BY columnid) AS ROW_NUM
from tablename
) x
where ROW_NUM>10
SELECT * FROM (SELECT colA, colB FROM tableA UNION SELECT colA, colB FROM tableB) as tableC WHERE tableC.colA > 1
If we're using a union that contains the same field name in 2 tables, then we need to give a name to the sub query as tableC(in above query). Finally, the WHERE
condition should be WHERE tableC.colA > 1
handle = open(path.rstrip("/") + "/" + filename.lstrip("/"), 'wb')
ftp.retrbinary('RETR %s' % filename, handle.write)
in my case this is the solution to fix it. When you create a project select MinGW GCC from the Toolchains panel.
Once the project is created, select project file, press ctrl + b to build the project. Then hit run and the the output should be printed on the console.
There is no library function for that. You have to code by your own.
for _, value := range myconfig {
if value.Key == "key1" {
// logic
}
}
Working code: https://play.golang.org/p/IJIhYWROP_
package main
import (
"encoding/json"
"fmt"
)
func main() {
type Config struct {
Key string
Value string
}
var respbody = []byte(`[
{"Key":"Key1", "Value":"Value1"},
{"Key":"Key2", "Value":"Value2"}
]`)
var myconfig []Config
err := json.Unmarshal(respbody, &myconfig)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v\n", myconfig)
for _, v := range myconfig {
if v.Key == "Key1" {
fmt.Println("Value: ", v.Value)
}
}
}
You can use this:
MessageBoxResult result = MessageBox.Show("Do you want to close this window?",
"Confirmation",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
Application.Current.Shutdown();
}
For more information, visit MessageBox in WPF.
In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager
then find Xml Tools
plugin. Tick the box and click Install
Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now
).
Following dialog will open:
Click on ...
. Point to XSD file and I am pretty sure you'll be able to handle things from here.
Hope this saves you some time.
EDIT:
Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1
plugin manager is back under a different guise... Plugin Admin
so now you can simply update notepad++ and have it back.
You could use the JPA LOCATE function.
LOCATE(searchString, candidateString [, startIndex]): Returns the first index of searchString in candidateString. Positions are 1-based. If the string is not found, returns 0.
FYI: The documentation on my top google hit had the parameters reversed.
SELECT
e
FROM
entity e
WHERE
(0 < LOCATE(:searchStr, e.property))
I was struggling with this too and finally got it to work.
routes.php
Route::get('people', 'PeopleController@index');
Route::get('people/{lastName}', 'PeopleController@show');
Route::get('people/{lastName}/{firstName}', 'PeopleController@show');
Route::post('people', 'PeopleController@processForm');
PeopleController.php
namespace App\Http\Controllers ;
use DB ;
use Illuminate\Http\Request ;
use App\Http\Requests ;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
public function processForm() {
$lastName = Input::get('lastName') ;
$firstName = Input::get('firstName') ;
return Redirect::to('people/'.$lastName.'/'.$firstName) ;
}
public function show($lastName,$firstName) {
$qry = 'SELECT * FROM tableFoo WHERE LastName LIKE "'.$lastName.'" AND GivenNames LIKE "'.$firstName.'%" ' ;
$ppl = DB::select($qry);
return view('people.show', ['ppl' => $ppl] ) ;
}
people/show.blade.php
<form method="post" action="/people">
<input type="text" name="firstName" placeholder="First name">
<input type="text" name="lastName" placeholder="Last name">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" value="Search">
</form>
Notes:
I needed to pass two input fields into the URI.
I'm not using Eloquent yet, if you are, adjust the database logic accordingly.
And I'm not done securing the user entered data, so chill.
Pay attention to the "_token" hidden form field and all the "use" includes, they are needed.
PS: Here's another syntax that seems to work, and does not need the
use Illuminate\Support\Facades\Input;
.
public function processForm(Request $request) {
$lastName = addslashes($request->lastName) ;
$firstName = addslashes($request->firstName) ;
//add more logic to validate and secure user entered data before turning it loose in a query
return Redirect::to('people/'.$lastName.'/'.$firstName) ;
}
For many S3 API packages (I recently had this problem the npm s3 package) you can run into issues where the region is assumed to be US Standard, and lookup by name will require you to explicitly define the region if you choose to host a bucket outside of that region.
I believe you want to find the current region of A1 and surrounding cells - not necessarily all cells on the sheet. If so - simply use... Range("A1").CurrentRegion
If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator
.
This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator")
can be overriden via command line options and isn't as type safe as java.io.File.separator
.
The last one, java.nio.file.FileSystems.getDefault().getSeparator();
was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.
So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.
There is a typo in your SQL. Fixed version is below:
SELECT GETVARIABLE('SYSIBM.VERSION') FROM SYSIBM.SYSDUMMY1;
I ran this on the IBM Mainframe under Z/OS in QMF and got the following results. We are currently running DB2 Version 8 and upgrading to Ver 10.
DSN08015 -- Format seems to be DSNVVMMM
-- PPP IS PRODUCT STRING 'DSN'
-- VV IS VERSION NUMBER E.G. 08
-- MMM IS MAINTENANCE LEVEL E.G. 015
If you deal with .xlsm
file instead of .xls
you can use the old method. I was trying to modify vbaProject.bin
in .xlsm
several times using DBP->DBx
method by it didn't work, also changing value of DBP
didn't. So I was very suprised that following worked :
1. Save .xlsm
as .xls
.
2. Use DBP->DBx
method on .xls
.
3. Unfortunately some erros may occur when using modified .xls
file, I had to save .xls
as .xlsx
and add modules, then save as .xlsm
.
Let's take a normal list (implemented by the ArrayList class) and make it synchronized. This is shown in the SynchronizedListExample class. We pass the Collections.synchronizedList method a new ArrayList of Strings. The method returns a synchronized List of Strings. //Here is SynchronizedArrayList class
package com.mnas.technology.automation.utility;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
/**
*
* @author manoj.kumar
* @email [email protected]
*
*/
public class SynchronizedArrayList {
static Logger log = Logger.getLogger(SynchronizedArrayList.class.getName());
public static void main(String[] args) {
List<String> synchronizedList = Collections.synchronizedList(new ArrayList<String>());
synchronizedList.add("Aditya");
synchronizedList.add("Siddharth");
synchronizedList.add("Manoj");
// when iterating over a synchronized list, we need to synchronize access to the synchronized list
synchronized (synchronizedList) {
Iterator<String> iterator = synchronizedList.iterator();
while (iterator.hasNext()) {
log.info("Synchronized Array List Items: " + iterator.next());
}
}
}
}
Notice that when iterating over the list, this access is still done using a synchronized block that locks on the synchronizedList object. In general, iterating over a synchronized collection should be done in a synchronized block
Hey, this one is kind of ugly but it's one line only:
imgTitle.Source = new BitmapImage(new Uri(@"pack://application:,,,/YourAssembly;component/your_image.png"));
Simple way to start activity in Adopter's button onClickListener:
Intent myIntent = new Intent(view.getContext(),Event_Member_list.class); myIntent.putExtra("intVariableName", eventsList.get(position).getEvent_id());
view.getContext().startActivity(myIntent);
It can be done and with rather simple php if this is your button
<input type="submit" name="submit>
and this is your php code
if(isset($_POST["submit"])) { php code here }
the code get's called when submit get's posted which happens when the button is clicked.
The best way is to use IN
statement :
DELETE from tablename WHERE id IN (1,2,3,...,254);
You can also use BETWEEN
if you have consecutive IDs :
DELETE from tablename WHERE id BETWEEN 1 AND 254;
You can of course limit for some IDs using other WHERE clause :
DELETE from tablename WHERE id BETWEEN 1 AND 254 AND id<>10;
One other thing to check is whether your current user is authorised to connect to the X display. In my case, root was not allowed to do that and matplotlib was complaining with the same error.
user@debian:~$ xauth list
debian/unix:10 MIT-MAGIC-COOKIE-1 ae921efd0026c6fc9d62a8963acdcca0
root@debian:~# xauth add debian/unix:10 MIT-MAGIC-COOKIE-1 ae921efd0026c6fc9d62a8963acdcca0
root@debian:~# xterm
source: http://www.debian-administration.org/articles/494 https://debian-administration.org/article/494/Getting_X11_forwarding_through_ssh_working_after_running_su
Use NPM module fs-extra, which gives you everything in fs, plus everything is Promisified. As a bonus, there's a fs.remove() method available.
Follow all the steps.
Step 1: initialize git
$ git init
Step 2: Check files are exist or not.
$git ls
Step 3 : Add the file
$git add filename
Step 4: Add comment to show
$git commit -m "your comment"
Step 5: Link to your repository
$git remote add origin "copy repository link and paste here"
Step 6: Push on Git
$ git push -u origin master
Worked for me in 30 seconds, short and sweet:
Your interior <div>
elements should likely both be float:left
. Divs size to 100% the size of their container width automatically. Try using display:inline-block
instead of width:auto
on the container div. Or possibly float:left
the container and also apply overflow:auto
. Depends on what you're after exactly.
use the object to call...
<a href="#" onclick='$("#myModal").modal("show");'>Try This</a>
or if you using ajax to show that modal after get result, this is work for me...
$.ajax({ url: "YourUrl",
type: "POST", data: "x=1&y=2&z=3",
cache: false, success: function(result){
// Your Function here
$("#myModal").modal("show");
}
});
Font Squirrel has a wonderful web font generator.
I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.
Quite logical the difference between PUT & PATCH w.r.t sending full & partial data for replacing/updating respectively. However, just couple of points as below
Selection(1, 1).Select
will select only the top left cell of your current selection.
By default Kubernetes looks in the public Docker registry to find images. If your image doesn't exist there it won't be able to pull it.
You can run a local Kubernetes registry with the registry cluster addon.
Then tag your images with localhost:5000
:
docker tag aii localhost:5000/dev/aii
Push the image to the Kubernetes registry:
docker push localhost:5000/dev/aii
And change run-aii.yaml to use the localhost:5000/dev/aii
image instead of aii
. Now Kubernetes should be able to pull the image.
Alternatively, you can run a private Docker registry through one of the providers that offers this (AWS ECR, GCR, etc.), but if this is for local development it will be quicker and easier to get setup with a local Kubernetes Docker registry.
Here is how to display the date as (year/month/day) :
from datetime import datetime
now = datetime.now()
print '%s/%s/%s' % (now.year, now.month, now.day)
Similar to that discussed below for IntelliJ 13 & 14, but with an extra level in the Settings/Preferences panel: Settings > Build, Execution, Deployment > Compiler > Java Compiler.
In IntelliJ 13 and 14, check the Settings > Compiler > Java Compiler UI to ensure you're not targeting a different bytecode version in your module.
If you are defining your function:
function test() {};
Then, this is equivalent to:
window.test = function() {} /* (in the browser) */
So spyOn(window, 'test')
should work.
If that is not, you should also be able to:
test = jasmine.createSpy();
If none of those are working, something else is going on with your setup.
I don't think your fakeElement
technique works because of what is going on behind the scenes. The original globalMethod still points to the same code. What spying does is proxy it, but only in the context of an object. If you can get your test code to call through the fakeElement it would work, but then you'd be able to give up global fns.
I changed my project to use Androidx, so I used the migration tool but some files(many files), didn't change automatically. I opened each file (activities, enums, fragments) and I found so many errors. I corrected them but the compile still show me incomprehensible errors. After looking for a solution I found this answer that someone said:
go to Analyze >> Inspect code
Whole Project:
It took some time and then showed me the result below:
As I corrected the errors I thought were important, I was running the build until the remaining errors were no longer affecting the build.
My Android Studio details
Get all the outdated packages and create a batch file with the following commands pip install xxx --upgrade for each outdated packages
native markdown doesn't support text alignment without html
+ css
.
Prim's is better for more dense graphs, and in this we also do not have to pay much attention to cycles by adding an edge, as we are primarily dealing with nodes. Prim's is faster than Kruskal's in the case of complex graphs.
This can be solved with the mentioned depends_on
directive since it's implemented now (2016):
version: '2'
services:
nginx:
image: nginx
ports:
- "42080:80"
volumes:
- ./config/docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
depends_on:
- php
php:
build: config/docker/php
ports:
- "42022:22"
volumes:
- .:/var/www/html
env_file: config/docker/php/.env.development
depends_on:
- mongo
mongo:
image: mongo
ports:
- "42017:27017"
volumes:
- /var/mongodata/wa-api:/data/db
command: --smallfiles
Successfully tested with:
$ docker-compose version
docker-compose version 1.8.0, build f3628c7
Find more details in the documentation.
There is also a very interesting article dedicated to this topic: Controlling startup order in Compose
It's a little memory-inefficient but if you're using the data anyway, I use this frequently:
$rows = $q->fetchAll();
$num_rows = count($rows);
Here is another version of regex to match any of the following date formats and allow leading zeros to be omitted:
Regex: ^[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2}$
Matches:
1/1/11 or 1.1.11 or 1-1-11 : true
01/01/11 or 01.01.11 or 01-01-11 : true
01/01/2011 or 01.01.2011 or 01-01-2011 : true
01/1/2011 or 01.1.2011 or 01-1-2011 : true
1/11/2011 or 1.11.2011 or 1-11-2011 : true
1/11/11 or 1.11.11 or 1-11-11 : true
11/1/11 or 11.1.11 or 11-1-11 : true
Both are correct.
You probably have some coding standard in your company - just see to follow it through. If you don't have - you should :)
I use this small method to read Arduino serial monitor with Python
import serial
ser = serial.Serial("COM11", 9600)
while True:
cc=str(ser.readline())
print(cc[2:][:-5])
I tried the solution priyanka.sarkar mentioned and the didn't quite get it working as the OP asked. Here's the solution I ended up with:
SELECT ID,
SUBSTRING((
SELECT ',' + T2.SomeColumn
FROM @T T2
WHERE WHERE T1.id = T2.id
FOR XML PATH('')), 2, 1000000)
FROM @T T1
GROUP BY ID
Try this to reload jqGrid with new data
jQuery("#grid").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');
you are importing java.util
package. That's why its giving error. there is a random()
in java.util
package too. Please remove the import statement importing java.util
package. then your program will use random()
method for java.lang
by default and then your program will work. remember to cast it i.e
int x = (int)(Math.random()*100);
I have struggled with the matplotlib trimming methods, so I've now just made a function to do this via a bash
call to ImageMagick
's mogrify command, which works well and gets all extra white space off the figure's edge. This requires that you are using UNIX/Linux, are using the bash
shell, and have ImageMagick
installed.
Just throw a call to this after your savefig()
call.
def autocrop_img(filename):
'''Call ImageMagick mogrify from bash to autocrop image'''
import subprocess
import os
cwd, img_name = os.path.split(filename)
bashcmd = 'mogrify -trim %s' % img_name
process = subprocess.Popen(bashcmd.split(), stdout=subprocess.PIPE, cwd=cwd)
It's best if you worked with DataSet
s and/or DataTable
s. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:
ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);
.. which will produce a beautiful excelsheet with a nice table!
Now to serve your file, assuming you have an ExcelPackage
object as in your code above called pck
..
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html
SELECT column1, CONVERT(column2 USING utf8)
FROM my_table
WHERE my_condition;
In Designer, activate the centralWidget and assign a layout, e.g. horizontal or vertical layout. Then your QFormLayout will automatically resize.
Always make sure, that all widgets have a layout! Otherwise, automatic resizing will break with that widget!
Controls insist on being too large, and won't resize, in QtDesigner
DateTime.new(2012, 1, 15).to_time.to_i
Also, you can use the following techniques to provision your service globally, before actual controllers are executed: https://stackoverflow.com/a/27050497/1056679. Just resolve your data globally and then pass it to your service in run
block for example.
The issue is because you have a bean of type SuggestionService created through @Component annotation and also through the XML config . As explained by JB Nizet, this will lead to the creation of a bean with name 'suggestionService' created via @Component and another with name 'SuggestionService' created through XML .
When you refer SuggestionService by @Autowired, in your controller, Spring autowires "by type" by default and find two beans of type 'SuggestionService'
You could do the following
Remove @Component from your Service and depend on mapping via XML - Easiest
Remove SuggestionService from XML and autowire the dependencies - use util:map to inject the indexSearchers map.
Use @Resource instead of @Autowired to pick the bean by its name .
@Resource(name="suggestionService")
private SuggestionService service;
or
@Resource(name="SuggestionService")
private SuggestionService service;
both should work.The third is a dirty fix and it's best to resolve the bean conflict through other ways.
Place the following HTML redirect code between the and tags of your HTML code.
<meta HTTP-EQUIV="REFRESH" content="3; url=http://www.yourdomain.com/index.html">
The above HTML redirect code will redirect your visitors to another web page instantly. The content="3; may be changed to the number of seconds you want the browser to wait before redirecting. 4, 5, 8, 10 or 15 seconds, etc.
I found this on exceljet.net and works for me:
=LEFT(B4,FIND(" ",B4)-1)
Note that setTimeout
and setInterval
are very different functions:
setTimeout
will execute the code once, after the timeout.setInterval
will execute the code forever, in intervals of the provided timeout.Both functions return a timer ID which you can use to abort the timeout. All you have to do is store that value in a variable and use it as argument to clearTimeout(tid)
or clearInterval(tid)
respectively.
So, depending on what you want to do, you have two valid choices:
// set timeout
var tid = setTimeout(mycode, 2000);
function mycode() {
// do some stuff...
tid = setTimeout(mycode, 2000); // repeat myself
}
function abortTimer() { // to be called when you want to stop the timer
clearTimeout(tid);
}
or
// set interval
var tid = setInterval(mycode, 2000);
function mycode() {
// do some stuff...
// no need to recall the function (it's an interval, it'll loop forever)
}
function abortTimer() { // to be called when you want to stop the timer
clearInterval(tid);
}
Both are very common ways of achieving the same.
Here's a regex designed to match typical phone numbers:
^(((\+?\(91\))|0|((00|\+)?91))-?)?[7-9]\d{9}$
You probably redefined your "sum" function to be an integer data type. So it is rightly telling you that an integer is not something you can pass a range.
To fix this, restart your interpreter.
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data1 = range(0, 1000, 3)
>>> data2 = range(0, 1000, 5)
>>> data3 = list(set(data1 + data2)) # makes new list without duplicates
>>> total = sum(data3) # calculate sum of data3 list's elements
>>> print total
233168
If you shadow the sum
builtin, you can get the error you are seeing
>>> sum = 0
>>> total = sum(data3) # calculate sum of data3 list's elements
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Also, note that sum
will work fine on the set
there is no need to convert it to a list
So I was looking all over for a way to remove all files in a directory except for some directories, and files, I wanted to keep around. After much searching I devised a way to do it using find.
find -E . -regex './(dir1|dir2|dir3)' -and -type d -prune -o -print -exec rm -rf {} \;
Essentially it uses regex to select the directories to exclude from the results then removes the remaining files. Just wanted to put it out here in case someone else needed it.
Two commands:
id
prints the user id along with the groups.
Format: uid=usernumber(username) ...
whoami
gives the current user name
You would do something like this to get the path "Data\ich_will.mp3" inside your application environments folder.
string fileName = "ich_will.mp3";
string path = Path.Combine(Environment.CurrentDirectory, @"Data\", fileName);
In my case it would return the following:
C:\MyProjects\Music\MusicApp\bin\Debug\Data\ich_will.mp3
I use Path.Combine
and Environment.CurrentDirectory
in my example. These are very useful and allows you to build a path based on the current location of your application. Path.Combine
combines two or more strings to create a location, and Environment.CurrentDirectory
provides you with the working directory of your application.
The working directory is not necessarily the same path as where your executable
is located, but in most cases it should be, unless specified otherwise.
This can be done by creating a simple primary foreign key relationship and setting the foreign key column to unique in the following manner:
CREATE TABLE [Employee] (
[ID] INT PRIMARY KEY
, [Name] VARCHAR(50)
);
CREATE TABLE [Salary] (
[EmployeeID] INT UNIQUE NOT NULL
, [SalaryAmount] INT
);
ALTER TABLE [Salary]
ADD CONSTRAINT FK_Salary_Employee FOREIGN KEY([EmployeeID])
REFERENCES [Employee]([ID]);
INSERT INTO [Employee] (
[ID]
, [Name]
)
VALUES
(1, 'Ram')
, (2, 'Rahim')
, (3, 'Pankaj')
, (4, 'Mohan');
INSERT INTO [Salary] (
[EmployeeID]
, [SalaryAmount]
)
VALUES
(1, 2000)
, (2, 3000)
, (3, 2500)
, (4, 3000);
Check to see if everything is fine
SELECT * FROM [Employee];
SELECT * FROM [Salary];
Now Generally in Primary Foreign Relationship (One to many),
you could enter multiple times EmployeeID
,
but here an error will be thrown
INSERT INTO [Salary] (
[EmployeeID]
, [SalaryAmount]
)
VALUES
(1, 3000);
The above statement will show error as
Violation of UNIQUE KEY constraint 'UQ__Salary__7AD04FF0C044141D'. Cannot insert duplicate key in object 'dbo.Salary'. The duplicate key value is (1).
For identifying NaN
values use boolean indexing
:
print(df[df['x'].isnull()])
Then for removing all non-numeric values use to_numeric
with parameter errors='coerce'
- to replace non-numeric values to NaN
s:
df['x'] = pd.to_numeric(df['x'], errors='coerce')
And for remove all rows with NaN
s in column x
use dropna
:
df = df.dropna(subset=['x'])
Last convert values to int
s:
df['x'] = df['x'].astype(int)
I'm guessing this will help.
When passed as functions arguments, arrays act the same way as pointers. So you don't need to reference them. Simply type:
int x[]
or
int x[a]
. Both ways will work. I guess its the same thing Konrad Rudolf was saying, figured as much.
It happens when you have a file with the same name as Makefile target name in the directory where the Makefile is present.
Content roots are folders holding your project code while source roots are defined as same too. The only difference i came to understand was that the code in source roots is built before the code in the content root.
Unchecking them wouldn't affect the runtime till the point you're not making separate modules in your package which are manually connected to Django. That means if any of your files do not hold the 'from django import...' or any of the function isn't called via django, unchecking these 2 options will result in a malfunction.
Update - the problem only arises when using Virtual Environmanet, and only when controlling the project via the provided terminal. Cause the terminal still works via the default system pyhtonpath and not the virtual env. while the python django control panel works fine.
#include <math.h>
printf ("%d", (int) pow (3, 4));
This is how I often do when I don't have to deal with IE
<tr>
<th scope="col" style="width: calc(1 * 100% / 12)">#</th>
<th scope="col" style="width: calc(4 * 100% / 12)">Website</th>
<th scope="col" style="width: calc(3 * 100% / 12)">Username</th>
<th scope="col" style="width: calc(3 * 100% / 12)">Password</th>
<th scope="col" style="width: calc(1 * 100% / 12)">Action</th>
</tr>
That way you can have a familiar 12-col grid.
Sticky session means that when a request comes into a site from a client all further requests go to the same server initial client request accessed. I believe that session affinity is a synonym for sticky session.
You can
There are Two ways (both requiring device root) :
1- First way, open the device in adb window command
, and then run the following:
adb shell >
pm disable-user --user 0 com.android.systemui >
and to get it back just do the same but change disable
to enable
.
2- second way, add the following line to the end of your device's build.prop file :
qemu.hw.mainkeys = 1
then to get it back just remove it.
and if you don't know how to edit build.prop file:
This is 2 years old, but none of them helped me.
I uninstalled my NodeJS v12.8.1 (Current) and installed a brand new v10.16.3 (LTS) and my ng build --prod
worked.
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
Must say I agree with that the most elegant solution to this is using boost::lexical_cast. You can then catch the bad_lexical_cast that might occure, and do something when it fails, instead of getting 0.0 which atof gives.
#include <boost/lexical_cast.hpp>
#include <string>
int main()
{
std::string str = "3.14";
double strVal;
try {
strVal = boost::lexical_cast<double>(str);
} catch(bad_lexical_cast&) {
//Do your errormagic
}
return 0;
}
Here is a simplified running example of Seattle Ninja's solution.
var slideSource = document.getElementById('slideSource');_x000D_
_x000D_
document.getElementById('handle').onclick = function () {_x000D_
slideSource.classList.toggle('fade');_x000D_
}
_x000D_
#slideSource {_x000D_
opacity: 1;_x000D_
transition: opacity 1s; _x000D_
}_x000D_
_x000D_
#slideSource.fade {_x000D_
opacity: 0;_x000D_
}
_x000D_
<button id="handle">Fade</button> _x000D_
<div id="slideSource">Whatever you want here - images or text</div>
_x000D_
I tend to create a static class containing basic functions for cases like these. They allow me write expressions like
var myValues myItems.Select(x => x.Value).Where(Predicates.IsNotNull);
And the collection of predicate functions:
public static class Predicates
{
public static bool IsNull<T>(T value) where T : class
{
return value == null;
}
public static bool IsNotNull<T>(T value) where T : class
{
return value != null;
}
public static bool IsNull<T>(T? nullableValue) where T : struct
{
return !nullableValue.HasValue;
}
public static bool IsNotNull<T>(T? nullableValue) where T : struct
{
return nullableValue.HasValue;
}
public static bool HasValue<T>(T? nullableValue) where T : struct
{
return nullableValue.HasValue;
}
public static bool HasNoValue<T>(T? nullableValue) where T : struct
{
return !nullableValue.HasValue;
}
}
If you wanna find just the word like 'are' in "How are you?" and not like 'are' in 'hare'
$word=" are ";
$str="How are you?";
if(strpos($word,$str) !== false){
echo 1;
}
Please note that installation of psycopg2
via pip or setup.py requires to have Visual Studio 2008 (more precisely executable file vcvarsall.bat). If you don't have admin rights to install it or set the appropriate PATH variable on Windows, you can download already compiled library from here.
Generate a migration and use change_column_default
, is succinct and reversible:
class SetDefaultAgeInPeople < ActiveRecord::Migration[5.2]
def change
change_column_default :people, :age, { from: nil, to: 0 }
end
end
main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
custom.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="255dp"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Video1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#339966"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="video1"
android:textColor="#606060" />
</LinearLayout>
</LinearLayout>
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
main.java:
package com.example.sample;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ListView l1;
String[] t1={"video1","video2"};
String[] d1={"lesson1","lesson2"};
int[] i1 ={R.drawable.ic_launcher,R.drawable.ic_launcher};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
l1=(ListView)findViewById(R.id.list);
l1.setAdapter(new dataListAdapter(t1,d1,i1));
}
class dataListAdapter extends BaseAdapter {
String[] Title, Detail;
int[] imge;
dataListAdapter() {
Title = null;
Detail = null;
imge=null;
}
public dataListAdapter(String[] text, String[] text1,int[] text3) {
Title = text;
Detail = text1;
imge = text3;
}
public int getCount() {
// TODO Auto-generated method stub
return Title.length;
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.custom, parent, false);
TextView title, detail;
ImageView i1;
title = (TextView) row.findViewById(R.id.title);
detail = (TextView) row.findViewById(R.id.detail);
i1=(ImageView)row.findViewById(R.id.img);
title.setText(Title[position]);
detail.setText(Detail[position]);
i1.setImageResource(imge[position]);
return (row);
}
}
}
Try this.
Array.from(element.parentNode.children).indexOf(element)
element.parentNode.children
? Returns the brothers of element
, including that element.
Array.from
? Casts the constructor of children
to an Array
object
indexOf
? You can apply indexOf
because you now have an Array
object.
This worked for me
1- Go to ~/.android/ and remove “adbkey”
2- Disconnect USB connection
3- adb kill-server
4- Revoke USB debugging authorizations (in developer option)
5- Reconnect the device to the Ma
6- adb devices
The answer did not work for me. I dont know how it got so many votes. Though it helped in pointing me in a direction.
This is the answer that worked for me:
foreach (var x in jobj)
{
var key = ((JProperty) (x)).Name;
var jvalue = ((JProperty)(x)).Value ;
}
Even though --files
is no longer supported, you can use an env variable to provide a list of files:
// karma.conf.js
function getSpecs(specList) {
if (specList) {
return specList.split(',')
} else {
return ['**/*_spec.js'] // whatever your default glob is
}
}
module.exports = function(config) {
config.set({
//...
files: ['app.js'].concat(getSpecs(process.env.KARMA_SPECS))
});
});
Then in CLI:
$ env KARMA_SPECS="spec1.js,spec2.js" karma start karma.conf.js --single-run
If you only need to only to disable updating updated_at just add this method to your model.
public function setUpdatedAtAttribute($value)
{
// to Disable updated_at
}
This will override the parent setUpdatedAtAttribute() method. created_at will work as usual. Same way you can write a method to disable updating created_at only.
The term for T&&
when used with type deduction (such as for perfect forwarding) is known colloquially as a forwarding reference. The term "universal reference" was coined by Scott Meyers in this article, but was later changed.
That is because it may be either r-value or l-value.
Examples are:
// template
template<class T> foo(T&& t) { ... }
// auto
auto&& t = ...;
// typedef
typedef ... T;
T&& t = ...;
// decltype
decltype(...)&& t = ...;
More discussion can be found in the answer for: Syntax for universal references
$this->db->where_in('id', ['20','15','22','42','86']);
Reference: where_in
Is it acceptable & safe to run
pip install
undersudo
?
It's not safe and it's being frowned upon – see What are the risks of running 'sudo pip'?
To install Python package in your home directory you don't need root privileges. See description of --user
option to pip.
Here is a working JavaScript only implementation which correctly handles checkboxes, radio buttons, and sliders (probably other input types as well, but I've only tested these).
function setOrPush(target, val) {
var result = val;
if (target) {
result = [target];
result.push(val);
}
return result;
}
function getFormResults(formElement) {
var formElements = formElement.elements;
var formParams = {};
var i = 0;
var elem = null;
for (i = 0; i < formElements.length; i += 1) {
elem = formElements[i];
switch (elem.type) {
case 'submit':
break;
case 'radio':
if (elem.checked) {
formParams[elem.name] = elem.value;
}
break;
case 'checkbox':
if (elem.checked) {
formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);
}
break;
default:
formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);
}
}
return formParams;
}
function setOrPush(target, val) {_x000D_
var result = val;_x000D_
if (target) {_x000D_
result = [target];_x000D_
result.push(val);_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
function getFormResults(formElement) {_x000D_
var formElements = formElement.elements;_x000D_
var formParams = {};_x000D_
var i = 0;_x000D_
var elem = null;_x000D_
for (i = 0; i < formElements.length; i += 1) {_x000D_
elem = formElements[i];_x000D_
switch (elem.type) {_x000D_
case 'submit':_x000D_
break;_x000D_
case 'radio':_x000D_
if (elem.checked) {_x000D_
formParams[elem.name] = elem.value;_x000D_
}_x000D_
break;_x000D_
case 'checkbox':_x000D_
if (elem.checked) {_x000D_
formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);_x000D_
}_x000D_
break;_x000D_
default:_x000D_
formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);_x000D_
}_x000D_
}_x000D_
return formParams;_x000D_
}_x000D_
_x000D_
//_x000D_
// Boilerplate for running the snippet/form_x000D_
//_x000D_
_x000D_
function ok() {_x000D_
var params = getFormResults(document.getElementById('main_form'));_x000D_
document.getElementById('results_wrapper').innerHTML = JSON.stringify(params, null, ' ');_x000D_
}_x000D_
_x000D_
(function() {_x000D_
var main_form = document.getElementById('main_form');_x000D_
main_form.addEventListener('submit', function(event) {_x000D_
event.preventDefault();_x000D_
ok();_x000D_
}, false);_x000D_
})();
_x000D_
<form id="main_form">_x000D_
<div id="questions_wrapper">_x000D_
<p>what is a?</p>_x000D_
<div>_x000D_
<input type="radio" required="" name="q_0" value="a" id="a_0">_x000D_
<label for="a_0">a</label>_x000D_
<input type="radio" required="" name="q_0" value="b" id="a_1">_x000D_
<label for="a_1">b</label>_x000D_
<input type="radio" required="" name="q_0" value="c" id="a_2">_x000D_
<label for="a_2">c</label>_x000D_
<input type="radio" required="" name="q_0" value="d" id="a_3">_x000D_
<label for="a_3">d</label>_x000D_
</div>_x000D_
<div class="question range">_x000D_
<label for="a_13">A?</label>_x000D_
<input type="range" required="" name="q_3" id="a_13" min="0" max="10" step="1" list="q_3_dl">_x000D_
<datalist id="q_3_dl">_x000D_
<option value="0"></option>_x000D_
<option value="1"></option>_x000D_
<option value="2"></option>_x000D_
<option value="3"></option>_x000D_
<option value="4"></option>_x000D_
<option value="5"></option>_x000D_
<option value="6"></option>_x000D_
<option value="7"></option>_x000D_
<option value="8"></option>_x000D_
<option value="9"></option>_x000D_
<option value="10"></option>_x000D_
</datalist>_x000D_
</div>_x000D_
<p>A and/or B?</p>_x000D_
<div>_x000D_
<input type="checkbox" name="q_4" value="A" id="a_14">_x000D_
<label for="a_14">A</label>_x000D_
<input type="checkbox" name="q_4" value="B" id="a_15">_x000D_
<label for="a_15">B</label>_x000D_
</div>_x000D_
</div>_x000D_
<button id="btn" type="submit">OK</button>_x000D_
</form>_x000D_
<div id="results_wrapper"></div>
_x000D_
If you're looking for a more complete implementation, then take a look at this section of the project I made this for. I'll update this question eventually with the complete solution I came up with, but maybe this will be helpful to someone.
It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==
, the following should work:
byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);
This will output: YWJjZGVmPT0=
which is abcdef==
encoded in Base64.
Edit:
To decode a Base64 string, simply use Convert.FromBase64String()
. E.g.
string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);
At this point, bytes
will be a byte[]
(not a string
). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);
This will output the original input string, abcdef==
in this case.
As for me, using VSCode and Angular 5, only had to add "node" to types in tsconfig.app.json. Save, and restart the server.
{_x000D_
"compilerOptions": {_x000D_
.._x000D_
"types": [_x000D_
"node"_x000D_
]_x000D_
}_x000D_
.._x000D_
}
_x000D_
One curious thing, is that this problem "cannot find require (", does not happen when excuting with ts-node
First, Identify the user you are logged in as:
select user();
select current_user();
The result for the first command is what you attempted to login as, the second is what you actually connected as. Confirm that you are logged in as root@localhost
in mysql.
Grant_priv
to root@localhost
. Here is how you can check.
mysql> SELECT host,user,password,Grant_priv,Super_priv FROM mysql.user;
+-----------+------------------+-------------------------------------------+------------+------------+
| host | user | password | Grant_priv | Super_priv |
+-----------+------------------+-------------------------------------------+------------+------------+
| localhost | root | ***************************************** | N | Y |
| localhost | debian-sys-maint | ***************************************** | Y | Y |
| localhost | staging | ***************************************** | N | N |
+-----------+------------------+-------------------------------------------+------------+------------+
You can see that the Grant_priv is set to N for root@localhost. This needs to be Y. Below is how to fixed this:
UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;
GRANT ALL ON *.* TO 'root'@'localhost';
I logged back in, it was fine.
It is possible to set environment variables on Mac OS X 10.10 Yosemite with 3 files + 2 commands.
Main file with environment variables definition:
$ ls -la /etc/environment
-r-xr-xr-x 1 root wheel 369 Oct 21 04:42 /etc/environment
$ cat /etc/environment
#!/bin/sh
set -e
syslog -s -l warn "Set environment variables with /etc/environment $(whoami) - start"
launchctl setenv JAVA_HOME /usr/local/jdk1.7
launchctl setenv MAVEN_HOME /opt/local/share/java/maven3
if [ -x /usr/libexec/path_helper ]; then
export PATH=""
eval `/usr/libexec/path_helper -s`
launchctl setenv PATH $PATH
fi
osascript -e 'tell app "Dock" to quit'
syslog -s -l warn "Set environment variables with /etc/environment $(whoami) - complete"
Service definition to load environment variables for user applications (terminal, IDE, ...):
$ ls -la /Library/LaunchAgents/environment.user.plist
-rw------- 1 root wheel 504 Oct 21 04:37 /Library/LaunchAgents/environment.user.plist
$ sudo cat /Library/LaunchAgents/environment.user.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>environment.user</string>
<key>ProgramArguments</key>
<array>
<string>/etc/environment</string>
</array>
<key>KeepAlive</key>
<false/>
<key>RunAtLoad</key>
<true/>
<key>WatchPaths</key>
<array>
<string>/etc/environment</string>
</array>
</dict>
</plist>
The same service definition for root user applications:
$ ls -la /Library/LaunchDaemons/environment.plist
-rw------- 1 root wheel 499 Oct 21 04:38 /Library/LaunchDaemons/environment.plist
$ sudo cat /Library/LaunchDaemons/environment.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>environment</string>
<key>ProgramArguments</key>
<array>
<string>/etc/environment</string>
</array>
<key>KeepAlive</key>
<false/>
<key>RunAtLoad</key>
<true/>
<key>WatchPaths</key>
<array>
<string>/etc/environment</string>
</array>
</dict>
</plist>
And finally we should register these services:
$ launchctl load -w /Library/LaunchAgents/environment.user.plist
$ sudo launchctl load -w /Library/LaunchDaemons/environment.plist
What we get:
Issues / problems:
In order your env variables were correctly taken by applications after system reboot you will need:
This happens due to Apple denies explicit ordering of loaded services, so env variables are registered in parallel with processing of the "reopen queue".
But actually, I reboot my system only several times per year (on big updates), so it is not a big deal.
Use mktime()
:
<?php
$monthNum = 5;
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
echo $monthName; // Output: May
?>
See the PHP manual : http://php.net/mktime
I found that when I created a scene via the three.js editor, I not only had to use the correct answer's code (above), to set up the renderer with an alpha value and the clear color, I had to go into the app.json file and find the "Scene" Object's "background" attribute and set it to:
"background: null"
.
The export from Three.js editor had it originally set to "background": 0
The usual method I have seen is X.Y.Z, which generally corresponds to major.minor.patch:
Other variations use build numbers as an additional identifier. So you may have a large number for X.Y.Z.build if you have many revisions that are tested between releases. I use a couple of packages that are identified by year/month or year/release. Thus, a release in the month of September of 2010 might be 2010.9 or 2010.3 for the 3rd release of this year.
There are many variants to versioning. It all boils down to personal preference.
For the "1.3v1.1", that may be two different internal products, something that would be a shared library / codebase that is rev'd differently from the main product; that may indicate version 1.3 for the main product, and version 1.1 of the internal library / package.
Assuming employee numbers are in the first column and their names are in the second:
=VLOOKUP(A1, Sheet2!A:B, 2,false)
@echo off
xcopy /s C:\yourfile C:\anotherfile\
This is how it is done! Simple, right?
A solution using recursion:
def brute(string, length, charset):
if len(string) == length:
return
for char in charset:
temp = string + char
print(temp)
brute(temp, length, charset)
Usage:
brute("", 4, "rce")
Best solution for expand/collapse view's:
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
View view = buttonView.getId() == R.id.tb_search ? fSearch : layoutSettings;
transform(view, 200, isChecked
? ViewGroup.LayoutParams.WRAP_CONTENT
: 0);
}
public static void transform(final View v, int duration, int targetHeight) {
int prevHeight = v.getHeight();
v.setVisibility(View.VISIBLE);
ValueAnimator animator;
if (targetHeight == ViewGroup.LayoutParams.WRAP_CONTENT) {
v.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
animator = ValueAnimator.ofInt(prevHeight, v.getMeasuredHeight());
} else {
animator = ValueAnimator.ofInt(prevHeight, targetHeight);
}
animator.addUpdateListener(animation -> {
v.getLayoutParams().height = (animation.getAnimatedFraction() == 1.0f)
? targetHeight
: (int) animation.getAnimatedValue();
v.requestLayout();
});
animator.setInterpolator(new LinearInterpolator());
animator.setDuration(duration);
animator.start();
}
What you posted has a syntax error, but it makes no difference as you cannot pass HTTP headers via $.post()
.
Provided you're on jQuery version >= 1.5, switch to $.ajax()
and pass the headers
(docs) option. (If you're on an older version of jQuery, I will show you how to do it via the beforeSend
option.)
$.ajax({
url: 'https://url.com',
type: 'post',
data: {
access_token: 'XXXXXXXXXXXXXXXXXXX'
},
headers: {
Header_Name_One: 'Header Value One', //If your header name has spaces or any other char not appropriate
"Header Name Two": 'Header Value Two' //for object property name, use quoted notation shown in second
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Just use the str().lower()
method, unless high-performance is important - in which case write that sorting method as a C extension.
"How to write a Python Extension" seems like a decent intro..
More interestingly, This guide compares using the ctypes library vs writing an external C module (the ctype is quite-substantially slower than the C extension).
As Mark C points out, you can use the MSXML Base64 encoding functionality as described here.
I prefer late binding because it's easier to deploy, so here's the same function that will work without any VBA references:
Function EncodeBase64(text As String) As String
Dim arrData() As Byte
arrData = StrConv(text, vbFromUnicode)
Dim objXML As Variant
Dim objNode As Variant
Set objXML = CreateObject("MSXML2.DOMDocument")
Set objNode = objXML.createElement("b64")
objNode.dataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeBase64 = objNode.text
Set objNode = Nothing
Set objXML = Nothing
End Function
Some files are write-protected that even git cannot over write it. Change the folder permission to allow writing e.g. sudo chmod 775 foldername
And then execute
git pull
again
If your intention was to find a way to represent null in an enumeration of singleton objects, then it's a bad idea to (de)reference null (it C++11, nullptr).
Why not declare static singleton object that represents NULL within the class as follows and add a cast-to-pointer operator that returns nullptr ?
Edit: Corrected several mistypes and added if-statement in main() to test for the cast-to-pointer operator actually working (which I forgot to.. my bad) - March 10 2015 -
// Error.h
class Error {
public:
static Error& NOT_FOUND;
static Error& UNKNOWN;
static Error& NONE; // singleton object that represents null
public:
static vector<shared_ptr<Error>> _instances;
static Error& NewInstance(const string& name, bool isNull = false);
private:
bool _isNull;
Error(const string& name, bool isNull = false) : _name(name), _isNull(isNull) {};
Error() {};
Error(const Error& src) {};
Error& operator=(const Error& src) {};
public:
operator Error*() { return _isNull ? nullptr : this; }
};
// Error.cpp
vector<shared_ptr<Error>> Error::_instances;
Error& Error::NewInstance(const string& name, bool isNull = false)
{
shared_ptr<Error> pNewInst(new Error(name, isNull)).
Error::_instances.push_back(pNewInst);
return *pNewInst.get();
}
Error& Error::NOT_FOUND = Error::NewInstance("NOT_FOUND");
//Error& Error::NOT_FOUND = Error::NewInstance("UNKNOWN"); Edit: fixed
//Error& Error::NOT_FOUND = Error::NewInstance("NONE", true); Edit: fixed
Error& Error::UNKNOWN = Error::NewInstance("UNKNOWN");
Error& Error::NONE = Error::NewInstance("NONE");
// Main.cpp
#include "Error.h"
Error& getError() {
return Error::UNKNOWN;
}
// Edit: To see the overload of "Error*()" in Error.h actually working
Error& getErrorNone() {
return Error::NONE;
}
int main(void) {
if(getError() != Error::NONE) {
return EXIT_FAILURE;
}
// Edit: To see the overload of "Error*()" in Error.h actually working
if(getErrorNone() != nullptr) {
return EXIT_FAILURE;
}
}
something
{
something1
something2
}
something3
In Python
Something
something1
something2
something3
Below, code snippet, will help you in understanding the mutex-lock-unlock concept. Attempt dry-run on the code. (further by varying the wait-time and process-time, you can build you understanding).
Code for your reference:
#include <stdio.h>
#include <pthread.h>
void in_progress_feedback(int);
int global = 0;
pthread_mutex_t mutex;
void *compute(void *arg) {
pthread_t ptid = pthread_self();
printf("ptid : %08x \n", (int)ptid);
int i;
int lock_ret = 1;
do{
lock_ret = pthread_mutex_trylock(&mutex);
if(lock_ret){
printf("lock failed(%08x :: %d)..attempt again after 2secs..\n", (int)ptid, lock_ret);
sleep(2); //wait time here..
}else{ //ret =0 is successful lock
printf("lock success(%08x :: %d)..\n", (int)ptid, lock_ret);
break;
}
} while(lock_ret);
for (i = 0; i < 10*10 ; i++)
global++;
//do some stuff here
in_progress_feedback(10); //processing-time here..
lock_ret = pthread_mutex_unlock(&mutex);
printf("unlocked(%08x :: %d)..!\n", (int)ptid, lock_ret);
return NULL;
}
void in_progress_feedback(int prog_delay){
int i=0;
for(;i<prog_delay;i++){
printf(". ");
sleep(1);
fflush(stdout);
}
printf("\n");
fflush(stdout);
}
int main(void)
{
pthread_t tid0,tid1;
pthread_mutex_init(&mutex, NULL);
pthread_create(&tid0, NULL, compute, NULL);
pthread_create(&tid1, NULL, compute, NULL);
pthread_join(tid0, NULL);
pthread_join(tid1, NULL);
printf("global = %d\n", global);
pthread_mutex_destroy(&mutex);
return 0;
}
Add which colors you want to colors
and then set colorByPoint
to true
.
colors: [
'#4572A7',
'#AA4643',
'#89A54E',
'#80699B',
'#3D96AE',
'#DB843D',
'#92A8CD',
'#A47D7C',
'#B5CA92'
],
plotOptions: {
column: {
colorByPoint: true
}
}
Reference:
To Remove RED EXCLAMATION mark on project,
I have deleted all JAR files using BUILD Path--> LIBRARY --> ADD EXTERNAL JARs
and remove all
or selected JAR
.
Reinstall again.
This action resolve my issue with Red exclamation mark.
0 values of basic types (1)(2)map to false
.
Other values map to true
.
This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.
It's a common error to assume that as function return values, false
indicates failure. But in particular from main
it's false
that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.
There's no need to cast to bool
for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x
, works nicely. One can read !!
as a “convert to bool
” operator, much as -->
can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)
1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false
; any other value is converted to true
. For direct-initialization (8.5), a prvalue of type std::nullptr_t
can be converted to a prvalue of type bool
; the resulting value is false
.”
2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool
, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”
The answer given by this is correct to me : https://github.com/flutter/flutter/issues/15408#issuecomment-373424994
After cloning the repo, don't cd ./flutter before running the commad. the pwd represent the current directory where you were before cloning the repo. The full command is:
export PATH=`pwd`/flutter/bin:$PATH
You can make life easier by adding it to your bashrc or zshrc
Move flutter to home dir
$ mv flutter ~
Add the path to your ~/.zshrc
path+=('/home/username/flutter/bin')
export PATH
Source it source ~/.zshrc
It's too late but somewhat may useful to others
The matching wildcard is strict, but no declaration can be found for element 'context:component-scan
which Means you have Missed some Declarations or The Required Declarations Not Found in Your XML
In my case i forgot to add the follwoing
After Adding this the Problem Gone away
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
I can't find toByteArray()
as @atrioom said, so I use StringWriter
, please try:
public void writeListToJsonArray() throws IOException {
//your list
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final StringWriter sw =new StringWriter();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, list);
System.out.println(sw.toString());//use toString() to convert to JSON
sw.close();
}
Or just use ObjectMapper#writeValueAsString
:
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(list));
It is Widget.ProgressBar.Horizontal
on my phone, if I set android:indeterminate="true"
I needed something like that and the solution I gave with the help of jquery is this:
<textarea class="textlimited" data-textcounterid="counter1" maxlength="30">text</textarea>
<span class='textcounter' id="counter1"></span>
With this script:
// the selector below will catch the keyup events of elements decorated with class textlimited and have a maxlength
$('.textlimited[maxlength]').keyup(function(){
//get the fields limit
var maxLength = $(this).attr("maxlength");
// check if the limit is passed
if(this.value.length > maxLength){
return false;
}
// find the counter element by the id specified in the source input element
var counterElement = $(".textcounter#" + $(this).data("textcounterid"));
// update counter 's text
counterElement.html((maxLength - this.value.length) + " chars left");
});
? live demo Here
Caching.
There are other more in depth benefits of REST which revolve around evolve-ability via loose coupling and hypertext, but caching mechanisms are the main reason you should care about RESTful HTTP.
If you're using Ubuntu, you can put a shell script in one of these folders: /etc/cron.daily
, /etc/cron.hourly
, /etc/cron.monthly
or /etc/cron.weekly
.
For more detail, check out this post: https://askubuntu.com/questions/2368/how-do-i-set-up-a-cron-job
<HTML>
<HEAD>
<TITLE>Sum</TITLE>
<script type="text/javascript">
function sum()
{
var num1 = document.myform.number1.value;
var num2 = document.myform.number2.value;
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('add').value = sum;
}
</script>
</HEAD>
<BODY>
<FORM NAME="myform">
<INPUT TYPE="text" NAME="number1" VALUE=""/> +
<INPUT TYPE="text" NAME="number2" VALUE=""/>
<INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
<INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
</FORM>
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE>Sum</TITLE>
<script type="text/javascript">
function sum()
{
var num1 = document.myform.number1.value;
var num2 = document.myform.number2.value;
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('add').innerHTML = sum;
}
</script>
</HEAD>
<BODY>
<FORM NAME="myform">
<INPUT TYPE="text" NAME="number1" VALUE=""/> +
<INPUT TYPE="text" NAME="number2" VALUE=""/>
<INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
<DIV ID="add"></DIV>
</FORM>
</BODY>
</HTML>
It might be helpful to know that printf does padding for you, using %-10s as the format string will pad the input right in a field 10 characters long
printf("|%-10s|", "Hello");
will output
|Hello |
In this case the - symbol means "Left align", the 10 means "Ten characters in field" and the s means you are aligning a string.
Printf style formatting is available in many languages and has plenty of references on the web. Here is one of many pages explaining the formatting flags. As usual WikiPedia's printf page is of help too (mostly a history lesson of how widely printf has spread).
You can use a JS and SCSS/Fontawesome combination for the Prev/Next buttons.
In your JS (this includes screenreader only/accessibility classes with Zurb Foundation):
$('.whatever-carousel').owlCarousel({
... ...
navText: ["<span class='show-for-sr'>Previous</span>","<span class='show-for-sr'>Next</span>"]
... ...
})
In your SCSS this:
.owl-theme {
.owl-nav {
.owl-prev,
.owl-next {
font-family: FontAwesome;
//border-radius: 50%;
//padding: whatever-to-get-a-circle;
transition: all, .2s, ease;
}
.owl-prev {
&::before {
content: "\f104";
}
}
.owl-next {
&::before {
content: "\f105";
}
}
}
}
For the FontAwesome font-family I happen to use the embed code in the document header:
<script src="//use.fontawesome.com/123456whatever.js"></script>
There are various ways to include FA, strokes/folks, but I find this is pretty fast and as I'm using webpack I can just about live with that 1 extra js server call.
And to update this - there's also this JS option for slightly more complex arrows, still with accessibility in mind:
$('.whatever-carousel').owlCarousel({
navText: ["<span class=\"fa-stack fa-lg\" aria-hidden=\"true\"><span class=\"show-for-sr\">Previous</span><i class=\"fa fa-circle fa-stack-2x\"></i><i class=\"fa fa-chevron-left fa-stack-1x fa-inverse\" aria-hidden=\"true\"></i></span>","<span class=\"fa-stack fa-lg\" aria-hidden=\"true\"><span class=\"show-for-sr\">Next</span><i class=\"fa fa-circle fa-stack-2x\"></i><i class=\"fa fa-chevron-right fa-stack-1x fa-inverse\" aria-hidden=\"true\"></i></span>"]
})
Loads of escaping there, use single quotes instead if preferred.
And in the SCSS just comment out the ::before attrs:
.owl-prev {
//&::before { content: "\f104"; }
}
.owl-next {
//&::before { content: "\f105"; }
}
Closing a window that was opened by the user through JavaScript is considered to be a security risk, thus not all browsers will allow this (which is why all solutions are hacks/workarounds). Browsers that are steadily maintained remove these types of hacks, and solutions that work one day may be broken the next.
This was addressed here by rvighne in a similar question on the subject.
use table
<table align="center" width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><label for="First_Name">First Name:</label></td>
<td><input name="first_name" id="First_Name" type="text" /></td>
<td><label for="last_name">Last Name:</label></td> <td>
<input name="last_name" id="Last_Name" type="text" /></td>
</tr>
<tr>
<td colspan="2"><label for="Email">Email:</label></td>
<td colspan="2"><input name="email" id="Email" type="email" /></td>
</tr>
<tr>
<td colspan="4"><input type="submit" value="Submit"/></td>
</tr>
</table>
Use empty
(it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"
If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"
Update: as per the comments, the Map
turns out to actually be a List
(please work on your naming conventions). To check if a List
contains an item the "normal" EL way, use JSTL fn:contains
(although not explicitly documented, it works for List
as well).
styleClass="#{empty obj.validationErrorMap ? ' ' :
(fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"
Dispose(true);
GC.SuppressFinalize(this);
If object has finalizer, .net put a reference in finalization queue.
Since we have call Dispose(ture)
, it clear object, so we don't need finalization queue to do this job.
So call GC.SuppressFinalize(this)
remove reference in finalization queue.
You may be looking for
for _ in itertools.repeat(None, times): ...
this is THE fastest way to iterate times
times in Python.
To begin with, your problem is that you use the method `compareTo() which is case sensitive. That means that the Capital letters are sorted apart from the lower case. The reason is that it translated in Unicode where the capital letters are presented with numbers which are less than the presented number of lower case. Thus you should use `compareToIgnoreCase()` as many also mentioned in previous posts.
This is my full example approach of how you can do it effecively
After you create an object of the Comparator you can pass it in this version of `sort()` which defined in java.util.Arrays.
static<T>void sort(T[]array,Comparator<?super T>comp)
take a close look at super. This makes sure that the array which is passed into is combatible with the type of comparator.
The magic part of this way is that you can easily sort the array of strings in Reverse order you can easily do by:
return strB.compareToIgnoreCase(strA);
import java.util.Comparator;
public class IgnoreCaseComp implements Comparator<String> {
@Override
public int compare(String strA, String strB) {
return strA.compareToIgnoreCase(strB);
}
}
import java.util.Arrays;
public class IgnoreCaseSort {
public static void main(String[] args) {
String strs[] = {" Hello ", " This ", "is ", "Sorting ", "Example"};
System.out.print("Initial order: ");
for (String s : strs) {
System.out.print(s + " ");
}
System.out.println("\n");
IgnoreCaseComp icc = new IgnoreCaseComp();
Arrays.sort(strs, icc);
System.out.print("Case-insesitive sorted order: ");
for (String s : strs) {
System.out.print(s + " ");
}
System.out.println("\n");
Arrays.sort(strs);
System.out.print("Default, case-sensitive sorted order: ");
for (String s : strs) {
System.out.print(s + " ");
}
System.out.println("\n");
}
}
run:
Initial order: Hello This is Sorting Example
Case-insesitive sorted order: Hello This Example is Sorting
Default, case-sensitive sorted order: Hello This Example Sorting is
BUILD SUCCESSFUL (total time: 0 seconds)
The method compareToIgnoreCase()
, although it works well with many occasions(just like compare string in english),it will wont work well with all languages and locations. This automatically makes it an unfit choice for use. To make sure that it will be suppoorted everywhere you should use compare()
from java.text.Collator.
You can find a collator for your location by calling the method getInstance()
. After that you should set this Collator's strength property. This can be done with the setStrength()
method together with Collator.PRIMARY
as parameter. With this alternative choise the IgnocaseComp can be written just like below. This version of code will generate the same output independently of the location
import java.text.Collator;
import java.util.Comparator;
//this comparator uses one Collator to determine
//the right sort usage with no sensitive type
//of the 2 given strings
public class IgnoreCaseComp implements Comparator<String> {
Collator col;
IgnoreCaseComp() {
//default locale
col = Collator.getInstance();
//this will consider only PRIMARY difference ("a" vs "b")
col.setStrength(Collator.PRIMARY);
}
@Override
public int compare(String strA, String strB) {
return col.compare(strA, strB);
}
}
You're in replace mode. Press the Insert
key on your keyboard to switch back to insert mode. Many applications that handle text have this in common.
Corrected a few things and added an alternative select - delete as appropriate.
DELIMITER |
CREATE PROCEDURE getNearestCities
(
IN p_cityID INT -- should this be int unsigned ?
)
BEGIN
DECLARE cityLat FLOAT; -- should these be decimals ?
DECLARE cityLng FLOAT;
-- method 1
SELECT lat,lng into cityLat, cityLng FROM cities WHERE cities.cityID = p_cityID;
SELECT
b.*,
HAVERSINE(cityLat,cityLng, b.lat, b.lng) AS dist
FROM
cities b
ORDER BY
dist
LIMIT 10;
-- method 2
SELECT
b.*,
HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
FROM
cities AS a
JOIN cities AS b on a.cityID = p_cityID
ORDER BY
dist
LIMIT 10;
END |
delimiter ;
In csh (as opposed to bash) you can do exactly what you want.
alias print 'lpr \!^ -Pps5'
print memo.txt
The notation \!^
causes the argument to be inserted in the command at this point.
The !
character is preceeded by a \
to prevent it being interpreted as a history command.
You can also pass multiple arguments:
alias print 'lpr \!* -Pps5'
print part1.ps glossary.ps figure.ps
(Examples taken from http://unixhelp.ed.ac.uk/shell/alias_csh2.1.html .)
<li class="list-group-item active"><h5>Feaured Image</h5></li>
<li class="list-group-item">
<div class="input-group mb-3">
<div class="custom-file ">
<input type="file" class="custom-file-input" name="thumbnail" id="thumbnail">
<label class="custom-file-label" for="thumbnail">Choose file</label>
</div>
</div>
<div class="img-thumbnail text-center">
<img src="@if(isset($product)) {{asset('storage/'.$product->thumbnail)}} @else {{asset('images/no-thumbnail.jpeg')}} @endif" id="imgthumbnail" class="img-fluid" alt="">
</div>
</li>
<script>
$(function(){
$('#thumbnail').on('change', function() {
var file = $(this).get(0).files;
var reader = new FileReader();
reader.readAsDataURL(file[0]);
reader.addEventListener("load", function(e) {
var image = e.target.result;
$("#imgthumbnail").attr('src', image);
});
});
}
</script>
Sourcetree 3.x has an option to accept gitLab. See here. I now use Sourcetree 3.0.15. In Settings, put your remote gitLab host and url, etc. If your existing git client version is not supported any more, the easiest way is perhaps to use Sourcetree embedded Git by Tools->Options->Git, in Git Version near the bottom, choose Embedded. A download may happen.
If you are working a lot with graphs and ggplot, you might be tired to add the theme() each time. If you don't want to change the default theme as suggested earlier, you may find easier to create your own personal theme.
personal_theme = theme(plot.title =
element_text(hjust = 0.5))
Say you have multiple graphs, p1, p2 and p3, just add personal_theme to them.
p1 + personal_theme
p2 + personal_theme
p3 + personal_theme
dat <- data.frame(
time = factor(c("Lunch","Dinner"),
levels=c("Lunch","Dinner")),
total_bill = c(14.89, 17.23)
)
p1 = ggplot(data=dat, aes(x=time, y=total_bill,
fill=time)) +
geom_bar(colour="black", fill="#DD8888",
width=.8, stat="identity") +
guides(fill=FALSE) +
xlab("Time of day") + ylab("Total bill") +
ggtitle("Average bill for 2 people")
p1 + personal_theme
Just use the event-handler. Something like this should work:
$('.js-my-element').bind('contextmenu', function(e) {
e.preventDefault();
alert('The eventhandler will make sure, that the contextmenu dosn't appear.');
});
a core dump is usually only made when the Windows kernel crashes (aka blue screen). A servicecrash will most of the times only leave some logging behind (in the event viewer probably).
If it is the bluescreen crash dump you are looking for, look in C:\Windows\Minidump or C:\windows\MEMORY.DMP
You are correct in that it's not "right" to add files to the tags folder.
You've correctly guessed that copy
is the operation to use; it lets Subversion keep track of the history of these files, and also (I assume) store them much more efficiently.
In my experience, it's best to do copies ("snapshots") of entire projects, i.e. all files from the root check-out location. That way the snapshot can stand on its own, as a true representation of the entire project's state at a particular point in time.
This part of "the book" shows how the command is typically used.
Another case that could cause this error is
>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index
Using the actual shape will fix it.
>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>
This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_table;
gid | datepose | pvc | modifiedpvc
-----+----------+-----+-------------
1 | 1961 | 01 | 00
2 | 1949 | | 01
3 | 1990 | 02 | 00
1 | 1981 | | 02
1 | | 03 | 00
1 | | | 03
(6 rows)
When I tried to compute w^T * x
using numpy, it was super confusing for me as well. In fact, I couldn't implement it myself. So, this is one of the few gotchas in NumPy that we need to acquaint ourselves with.
As far as 1D array is concerned, there is no distinction between a row vector and column vector. They are exactly the same.
Look at the following examples, where we get the same result in all cases, which is not true in (the theoretical sense of) linear algebra:
In [37]: w
Out[37]: array([0, 1, 2, 3, 4])
In [38]: x
Out[38]: array([1, 2, 3, 4, 5])
In [39]: np.dot(w, x)
Out[39]: 40
In [40]: np.dot(w.transpose(), x)
Out[40]: 40
In [41]: np.dot(w.transpose(), x.transpose())
Out[41]: 40
In [42]: np.dot(w, x.transpose())
Out[42]: 40
With that information, now let's try to compute the squared length of the vector |w|^2
.
For this, we need to transform w
to 2D array.
In [51]: wt = w[:, np.newaxis]
In [52]: wt
Out[52]:
array([[0],
[1],
[2],
[3],
[4]])
Now, let's compute the squared length (or squared magnitude) of the vector w
:
In [53]: np.dot(w, wt)
Out[53]: array([30])
Note that we used w
, wt
instead of wt
, w
(like in theoretical linear algebra) because of shape mismatch with the use of np.dot(wt, w). So, we have the squared length of the vector as [30]
. Maybe this is one of the ways to distinguish (numpy's interpretation of) row and column vector?
And finally, did I mention that I figured out the way to implement w^T * x
? Yes, I did :
In [58]: wt
Out[58]:
array([[0],
[1],
[2],
[3],
[4]])
In [59]: x
Out[59]: array([1, 2, 3, 4, 5])
In [60]: np.dot(x, wt)
Out[60]: array([40])
So, in NumPy, the order of the operands is reversed, as evidenced above, contrary to what we studied in theoretical linear algebra.
P.S. : potential gotchas in numpy
netcat
(nc.exe
) is the right tool. I have a feeling that any tool that does what you want it to do will have exactly the same problem with your antivirus software. Just flag this program as "OK" in your antivirus software (how you do this will depend on what type of antivirus software you use).
Of course you will also need to configure your sysadmin to accept that you're not trying to do anything illegal...
If a node is so unhealthy that the master can't get status from it -- Kubernetes may not be able to restart the node. And if health checks aren't working, what hope do you have of accessing the node by SSH?
In this case, you may have to hard-reboot -- or, if your hardware is in the cloud, let your provider do it.
For example, the AWS EC2 Dashboard allows you to right-click an instance to pull up an "Instance State" menu -- from which you can reboot/terminate an unresponsive node.
Before doing this, you might choose to kubectl cordon node
for good measure. And you may find kubectl delete node
to be an important part of the process for getting things back to normal -- if the node doesn't automatically rejoin the cluster after a reboot.
Why would a node become unresponsive? Probably some resource has been exhausted in a way that prevents the host operating system from handling new requests in a timely manner. This could be disk, or network -- but the more insidious case is out-of-memory (OOM), which Linux handles poorly.
To help Kubernetes manage node memory safely, it's a good idea to do both of the following:
requests
and limits
for memory.The idea here is to avoid the complications associated with memory overcommit, because memory is incompressible, and both Linux and Kubernetes' OOM killers may not trigger before the node has already become unhealthy and unreachable.
You can use the toolchain file mechanism of cmake for this purpose, see e.g. here. You write a toolchain file for each compiler containing the corresponding definitions. At config time, you run e.g
cmake -DCMAKE_TOOLCHAIN_FILE=/path/to/clang-toolchain.cmake ..
and all the compiler information will be set during the project() call from the toolchain file. Though in the documentation is mentionend only in the context of cross-compiling, it works as well for different compilers on the same system.
You also can use casting.
example:
string s;
int value = 3;
s.push_back((char)('0' + value));
Thanx, Alexander!
And to set the fancy-close button above the youtube's flash-content add 'wmode' to 'swf' parameters:
'swf': {'allowfullscreen':'true', 'wmode':'transparent'}
From man ping
:
-D Print timestamp (unix time + microseconds as in gettimeofday) before each line.
It will produce something like this:
[1337577886.346622] 64 bytes from 4.2.2.2: icmp_req=1 ttl=243 time=47.1 ms
Then timestamp could be parsed out from the ping
response and converted to the required format with date
.
import os
import sys
lib_path = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'lib'))
sys.path.append(lib_path)
import mymodule
I was trying to do this on Drupal 7 with the " fb_likebox" module (https://drupal.org/project/fb_likebox). To get it to be responsive. Turns out I had to write my own Contrib module Variation and stripe out the width setting option. (the default height option didn't matter for me). Once I removed the width, I added the <div id="likebox-wrapper">
in the fb_likebox.tpl.php.
Here's my CSS to style it:
`#likebox-wrapper * {
width: 100% !important;
background: url('../images/block.png') repeat 0 0;
color: #fbfbfb;
-webkit-border-radius: 7px;
-moz-border-radius: 7px;
-o-border-radius: 7px;
border-radius: 7px;
border: 1px solid #DDD;}`
I'm not sure if PyQt does have a script like this, but after you install PySide there is a script in pythons script directory "uic.py". You can use this script to convert a .ui file to a .py file:
python uic.py input.ui -o output.py -x
You have to check which Python you are using. I had the same problem because the Python I was using was not the same one that brew was using. In your command line:
which python
which brew
cd /usr/local/lib/python2.7/site-packages
ls
//you can see PyQt4 and sip are hereusr/local/lib/python2.7/site-packages
to your python path.open ~/.bash_profile
//you will open your bash_profile file in your editor'export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH'
to your bash file and save itpython
import PyQt4
// it is ok nowIf you want to open a specific browser (e.g. Chrome and Chromium) with command line options like full screen or kiosk mode and also want to be able to kill it later on, then this might work for you:
from threading import Timer
from time import sleep
import subprocess
import platform
# Hint 1: to enable F11 use --start-fullscreen instead of --kiosk, otherwise Alt+F4 to close the browser
# Hint 2: fullscreen will only work if chrome is not already running
platform_browser = {
'Windows': r'"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk http://stackoverflow.com',
'Linux' : ['/usr/bin/chromium-browser', '--kiosk', 'http://stackoverflow.com']
}
browser = None
def open_browser():
global browser
platform_name = platform.system()
if platform_name in platform_browser:
browser = subprocess.Popen(platform_browser[platform_name])
else:
print(":-(")
Timer(1, open_browser).start() # delayed start, give e.g. your own web server time to launch
sleep(20) # start e.g. your python web server here instead
browser.kill()
LENGTH()
returns the length of the string measured in bytes.
CHAR_LENGTH()
returns the length of the string measured in characters.
This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:
select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1
As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC
in UTF-8) even though it's only one character.
This is not exactly showing you which rows are locked, but this may helpful to you.
You can check which statements are blocked by running this:
select cmd,* from sys.sysprocesses
where blocked > 0
It will also tell you what each block is waiting on. So you can trace that all the way up to see which statement caused the first block that caused the other blocks.
Edit to add comment from @MikeBlandford:
The blocked column indicates the spid of the blocking process. You can run kill {spid} to fix it.
Update: JavaFX 8u40 includes simple Dialogs and Alerts!, check out this blog post which explains how to use the official JavaFX Dialogs!
My problem was not related to skype as i didn't had it installed. The solution I found was that 2 .dll files(msvcp110.dll, msvcr110.dll) were missing from the directory :
C:\wamp\bin\apache\apache2.4.9\bin
So I copied these 2 files to all these locations just in case and restarted wamp it worked
C:\wamp
C:\wamp\bin\apache\apache2.4.9\bin
C:\wamp\bin\apache\apache2.4.9
C:\wamp\bin\mysql\mysql5.6.17
C:\wamp\bin\php\php5.5.12
I hope this helps someone out.
The recent simplest after modification in current map markers and clusterer algorithm:
Modification on: https://developers.google.com/maps/documentation/javascript/marker-clustering[![enter image description here]1]1
<!DOCTYPE Html>
<html>
<head>
<meta Content-Security-Policy="default-src 'self'; script-src 'self' 'unsafe-eval' https://*/;">
<link type="text/css" href="http://www.mapsmarker.com/wp-content/uploads/leaflet-maps-marker-icons/bar_coktail.png">
<link rel="icon" href="data:,">
<title>App</title>
</head>
<style type="text/css">
#map {
height: 500
}
</style>
<body>
<div id='map' style="width:100%; height:400px"></div>
<script type='text/javascript'>
function initMap() {
maps = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(12.9824855, 77.637094),
zoom: 5,
disableDefaultUI: false,
mapTypeId: google.maps.MapTypeId.HYBRID
});
var labels='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var markerImage = 'http://www.mapsmarker.com/wp-content/uploads/leaflet-maps-marker-icons/bar_coktail.png';
marker = locations.map(function (location, i) {
return new google.maps.Marker({
position: new google.maps.LatLng(location.lat, location.lng),
map: maps,
title: "Map",
label: labels[i % labels.length],
icon: markerImage
});
});
var markerCluster = new MarkerClusterer(maps, marker, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
}
var locations = [
{ lat: 12.9824855, lng: 77.637094},
{ lat: 11.9824855, lng: 77.154312 },
{ lat: 12.8824855, lng: 77.637094},
{ lat: 10.8824855, lng: 77.054312 },
{ lat: 12.9824855, lng: 77.637094},
{ lat: 11.9824855, lng: 77.154312 },
{ lat: 12.8824855, lng: 77.637094},
{ lat: 13.8824855, lng: 77.054312 },
{ lat: 14.9824855, lng: 54.637094},
{ lat: 15.9824855, lng: 54.154312 },
{ lat: 16.8824855, lng: 53.637094},
{ lat: 17.8824855, lng: 52.054312 },
{ lat: 18.9824855, lng: 51.637094},
{ lat: 19.9824855, lng: 69.154312 },
{ lat: 20.8824855, lng: 68.637094},
{ lat: 21.8824855, lng: 67.054312 },
{ lat: 12.9824855, lng: 76.637094},
{ lat: 11.9824855, lng: 75.154312 },
{ lat: 12.8824855, lng: 74.637094},
{ lat: 10.8824855, lng: 74.054312 },
{ lat: 12.9824855, lng: 73.637094},
{ lat: 3.9824855, lng: 72.154312 },
{ lat: 2.8824855, lng: 71.637094},
{ lat: 1.8824855, lng: 70.054312 }
];
</script>
<script src="https://unpkg.com/@google/[email protected]/dist/markerclustererplus.min.js">
</script>
<script src="https:maps.googleapis.com/maps/api/js?key=AIzaSyDWu6_Io9xA1oerfOxE77YAv31etN4u3Dw&callback=initMap">
</script>
<script type='text/javascript'></script>
In a servlet based artifact, such as @WebServlet
, @WebFilter
and @WebListener
, you can grab a "plain vanilla" JSF @ManagedBean @RequestScoped
by:
Bean bean = (Bean) request.getAttribute("beanName");
and @ManagedBean @SessionScoped
by:
Bean bean = (Bean) request.getSession().getAttribute("beanName");
and @ManagedBean @ApplicationScoped
by:
Bean bean = (Bean) getServletContext().getAttribute("beanName");
Note that this prerequires that the bean is already autocreated by JSF beforehand. Else these will return null
. You'd then need to manually create the bean and use setAttribute("beanName", bean)
.
If you're able to use CDI @Named
instead of the since JSF 2.3 deprecated @ManagedBean
, then it's even more easy, particularly because you don't anymore need to manually create the beans:
@Inject
private Bean bean;
Note that this won't work when you're using @Named @ViewScoped
because the bean can only be identified by JSF view state and that's only available when the FacesServlet
has been invoked. So in a filter which runs before that, accessing an @Inject
ed @ViewScoped
will always throw ContextNotActiveException
.
Only when you're inside @ManagedBean
, then you can use @ManagedProperty
:
@ManagedProperty("#{bean}")
private Bean bean;
Note that this doesn't work inside a @Named
or @WebServlet
or any other artifact. It really works inside @ManagedBean
only.
If you're not inside a @ManagedBean
, but the FacesContext
is readily available (i.e. FacesContext#getCurrentInstance()
doesn't return null
), you can also use Application#evaluateExpressionGet()
:
FacesContext context = FacesContext.getCurrentInstance();
Bean bean = context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);
which can be convenienced as follows:
@SuppressWarnings("unchecked")
public static <T> T findBean(String beanName) {
FacesContext context = FacesContext.getCurrentInstance();
return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
}
and can be used as follows:
Bean bean = findBean("bean");
Sometimes depend and by git version and if you forget to do git add .
.
To check about your change on repository use always git status
that show all untracked and changed files. Because git diff
show only added files.
Due to the above mentioned problems, I prefer table value functions.
If you have this:
CREATE VIEW [dbo].[MyView] AS SELECT A, B FROM dbo.Something
create this:
CREATE FUNCTION MyFunction() RETURNS TABLE AS RETURN (SELECT * FROM [dbo].[MyView])
Then you simply import the function rather than the view.
If you know the key name simply do like this:
delete array['key_name']
Additional easy option:
interface simpleInt {
id: number;
label: string;
key: any;
}
type simpleType = simpleInt[];
When you use android:background
, you are replacing much of the styling and look and feel of a button with a blank color.
Update: As of the version 23.0.0 release of AppCompat, there is a new Widget.AppCompat.Button.Colored
style which uses your theme's colorButtonNormal
for the disabled color and colorAccent
for the enabled color.
This allows you apply it to your button directly via
<Button
...
style="@style/Widget.AppCompat.Button.Colored" />
If you need a custom colorButtonNormal
or colorAccent
, you can use a ThemeOverlay
as explained in this pro-tip and android:theme
on the button.
Previous Answer
You can use a drawable in your v21 directory for your background such as:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?attr/colorControlHighlight">
<item android:drawable="?attr/colorPrimary"/>
</ripple>
This will ensure your background color is ?attr/colorPrimary
and has the default ripple animation using the default ?attr/colorControlHighlight
(which you can also set in your theme if you'd like).
Note: you'll have to create a custom selector for less than v21:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/primaryPressed" android:state_pressed="true"/>
<item android:drawable="@color/primaryFocused" android:state_focused="true"/>
<item android:drawable="@color/primary"/>
</selector>
Assuming you have some colors you'd like for the default, pressed, and focused state. Personally, I took a screenshot of a ripple midway through being selected and pulled the primary/focused state out of that.
You need to make sure you specify the classpath in the MANIFEST.MF file. If you are using Maven to do the packaging, you can configure the following plugins:
1. maven-depedency-plugin:
2. maven-jar-plugin:
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>${version.plugin.maven-dependency-plugin}</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>true</overWriteSnapshots>
<includeScope>runtime</includeScope>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>${version.plugin.maven-jar-plugin}</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
The resulting manifest file will be packaged in the executable jar under META-INF and will look like this:
Manifest-Version: 1.0
Implementation-Title: myexecjar
Implementation-Version: 1.0.0-SNAPSHOT
Built-By: razvanone
Class-Path: lib/first.jar lib/second.jar
Build-Jdk: your-buildjdk-version
Created-By: Maven Integration for Eclipse
Main-Class: ro.razvanone.MyMainClass
The Windows script would look like this:
@echo on
echo "Starting up the myexecjar application..."
java -jar myexecjar-1.0.0-SNAPSHOT.jar
This should be complete config for building an executable jar using Maven :)
And this option?
list_name<-list()
for(i in 1:100){
paste("orca",i,sep="")->list_name[[i]]
}
It works perfectly. In the example you put, first line is missing, and then gives you the error message.
Install Cygwin, which includes Bash among many other GNU and Unix utilities (without whom its unlikely that bash will be very useful anyway).
Another option is MinGW's MSYS which includes bash and a smaller set of the more important utilities such as awk. Personally I would have preferred Cygwin because it includes such heavy lifting tools as Perl and Python which I find I cannot live without, while MSYS skimps on these and assumes you are going to install them yourself.
Updated: If anyone is interested in this answer and is running MS-Windows 10, please note that MS-Windows 10 has a "Windows Subsystem For Linux" feature which - once enabled - allows you to install a user-mode image of Ubuntu and then run Bash on that. This provides 100% compatibility with Ubuntu for debugging and running Bash scripts, but this setup is completely standalone from Windows and you cannot use Bash scripts to interact with Windows features (such as processes and APIs) except for limited access to files through the DrvFS feature.
A more public way is by calling get_form in Admin classes. It also works for non-database fields too. For example here i have a field called '_terminal_list' on the form that can be used in special cases for choosing several terminal items from get_list(request), then filtering based on request.user:
class ChangeKeyValueForm(forms.ModelForm):
_terminal_list = forms.ModelMultipleChoiceField(
queryset=Terminal.objects.all() )
class Meta:
model = ChangeKeyValue
fields = ['_terminal_list', 'param_path', 'param_value', 'scheduled_time', ]
class ChangeKeyValueAdmin(admin.ModelAdmin):
form = ChangeKeyValueForm
list_display = ('terminal','task_list', 'plugin','last_update_time')
list_per_page =16
def get_form(self, request, obj = None, **kwargs):
form = super(ChangeKeyValueAdmin, self).get_form(request, **kwargs)
qs, filterargs = Terminal.get_list(request)
form.base_fields['_terminal_list'].queryset = qs
return form
Answer is actually answered, but I would like to give you a "cheat sheet" for creating a delegate:
DELEGATE SCRIPT
CLASS A - Where delegate is calling function
@protocol <#Protocol Name#> <NSObject>
-(void)delegateMethod;
@end
@interface <#Some ViewController#> : <#UIViewController#>
@property (nonatomic, assign) id <<#Protocol Name#>> delegate;
@end
@implementation <#Some ViewController#>
-(void)someMethod {
[self.delegate methodName];
}
@end
CLASS B - Where delegate is called
@interface <#Other ViewController#> (<#Delegate Name#>) {}
@end
@implementation <#Other ViewController#>
-(void)otherMethod {
CLASSA *classA = [[CLASSA alloc] init];
[classA setDelegate:self];
}
-delegateMethod() {
}
@end
Use strstr(const char *s , const char *t)
and include<string.h>
You can write your own function which behaves same as strstr
and you can modify according to your requirement also
char * str_str(const char *s, const char *t)
{
int i, j, k;
for (i = 0; s[i] != '\0'; i++)
{
for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++);
if (k > 0 && t[k] == '\0')
return (&s[i]);
}
return NULL;
}
If you don't know its key it means it doesn't matter.
You could place the value as the key, it means it will instantly find the value. Better than using searching in all elements over and over again.
$messages=array();
$messages[312] = 312;
$messages[401] = 401;
$messages[1599] = 1599;
$messages[3] = 3;
unset($messages[3]); // no search needed
Try this one
var NewDate = Convert.ToDateTime(DateTime.Now.ToString("dd/MMM/yyyy")+" "+"10:15 PM")/*Add your time here*/;
You can set the minlength
option to some big value or you can do it by css like this,
.ui-autocomplete { height: 200px; overflow-y: scroll; overflow-x: hidden;}
In most use-cases, using a StringBuilder
(as already answered) is a good way to do this. However, if performance matters, this may be a good alternative.
/**
* Insert the 'insert' String at the index 'position' into the 'target' String.
*
* ````
* insertAt("AC", 0, "") -> "AC"
* insertAt("AC", 1, "xxx") -> "AxxxC"
* insertAt("AB", 2, "C") -> "ABC
* ````
*/
public static String insertAt(final String target, final int position, final String insert) {
final int targetLen = target.length();
if (position < 0 || position > targetLen) {
throw new IllegalArgumentException("position=" + position);
}
if (insert.isEmpty()) {
return target;
}
if (position == 0) {
return insert.concat(target);
} else if (position == targetLen) {
return target.concat(insert);
}
final int insertLen = insert.length();
final char[] buffer = new char[targetLen + insertLen];
target.getChars(0, position, buffer, 0);
insert.getChars(0, insertLen, buffer, position);
target.getChars(position, targetLen, buffer, position + insertLen);
return new String(buffer);
}