This was resolved. It turns out our IT Staff was correct. Both TLS 1.1 and TLS 1.2 were installed on the server. However, the issue was that our sites are running as ASP.NET 4.0 and you have to have ASP.NET 4.5 to run TLS 1.1 or TLS 1.2. So, to resolve the issue, our IT Staff had to re-enable TLS 1.0 to allow a connection with PayTrace.
So in short, the error message, "the client and server cannot communicate, because they do not possess a common algorithm", was caused because there was no SSL Protocol available on the server to communicate with PayTrace's servers.
UPDATE: Please do not enable TLS 1.0 on your servers, this was a temporary fix and is not longer applicable since there are now better work-arounds that ensure strong security practices. Please see accepted answer for a solution. FYI, I'm going to keep this answer on the site as it provides information on what the problem was, please do not down-vote.
Seems like you have your path right. But what is your working directory? on command prompt run:
javac -version
this should show your java version. if it doesnt, you have not set java in path correctly.
navigate to C:
cd \
Then:
javac -sourcepath users\AccName\Desktop -d users\AccName\Desktop first.java
-sourcepath is the complete path to your .java file, -d is the path/directory you want your .class files to be, then finally the file you want compiled (first.java).
Try this simple solution to convert file to base64 string
String base64String = imageFileToByte(file);
public String imageFileToByte(File file){
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.DEFAULT);
}
You will find below some code for reading unencrypted RSA keys encoded in the following formats:
-----BEGIN RSA PRIVATE KEY-----
)-----BEGIN PRIVATE KEY-----
) It works with Java 7+ (and after 9) and doesn't use third-party libraries (like BouncyCastle) or internal Java APIs (like DerInputStream
or DerValue
).
private static final String PKCS_1_PEM_HEADER = "-----BEGIN RSA PRIVATE KEY-----";
private static final String PKCS_1_PEM_FOOTER = "-----END RSA PRIVATE KEY-----";
private static final String PKCS_8_PEM_HEADER = "-----BEGIN PRIVATE KEY-----";
private static final String PKCS_8_PEM_FOOTER = "-----END PRIVATE KEY-----";
public static PrivateKey loadKey(String keyFilePath) throws GeneralSecurityException, IOException {
byte[] keyDataBytes = Files.readAllBytes(Paths.get(keyFilePath));
String keyDataString = new String(keyDataBytes, StandardCharsets.UTF_8);
if (keyDataString.contains(PKCS_1_PEM_HEADER)) {
// OpenSSL / PKCS#1 Base64 PEM encoded file
keyDataString = keyDataString.replace(PKCS_1_PEM_HEADER, "");
keyDataString = keyDataString.replace(PKCS_1_PEM_FOOTER, "");
return readPkcs1PrivateKey(Base64.decodeBase64(keyDataString));
}
if (keyDataString.contains(PKCS_8_PEM_HEADER)) {
// PKCS#8 Base64 PEM encoded file
keyDataString = keyDataString.replace(PKCS_8_PEM_HEADER, "");
keyDataString = keyDataString.replace(PKCS_8_PEM_FOOTER, "");
return readPkcs8PrivateKey(Base64.decodeBase64(keyDataString));
}
// We assume it's a PKCS#8 DER encoded binary file
return readPkcs8PrivateKey(Files.readAllBytes(Paths.get(keyFilePath)));
}
private static PrivateKey readPkcs8PrivateKey(byte[] pkcs8Bytes) throws GeneralSecurityException {
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "SunRsaSign");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8Bytes);
try {
return keyFactory.generatePrivate(keySpec);
} catch (InvalidKeySpecException e) {
throw new IllegalArgumentException("Unexpected key format!", e);
}
}
private static PrivateKey readPkcs1PrivateKey(byte[] pkcs1Bytes) throws GeneralSecurityException {
// We can't use Java internal APIs to parse ASN.1 structures, so we build a PKCS#8 key Java can understand
int pkcs1Length = pkcs1Bytes.length;
int totalLength = pkcs1Length + 22;
byte[] pkcs8Header = new byte[] {
0x30, (byte) 0x82, (byte) ((totalLength >> 8) & 0xff), (byte) (totalLength & 0xff), // Sequence + total length
0x2, 0x1, 0x0, // Integer (0)
0x30, 0xD, 0x6, 0x9, 0x2A, (byte) 0x86, 0x48, (byte) 0x86, (byte) 0xF7, 0xD, 0x1, 0x1, 0x1, 0x5, 0x0, // Sequence: 1.2.840.113549.1.1.1, NULL
0x4, (byte) 0x82, (byte) ((pkcs1Length >> 8) & 0xff), (byte) (pkcs1Length & 0xff) // Octet string + length
};
byte[] pkcs8bytes = join(pkcs8Header, pkcs1Bytes);
return readPkcs8PrivateKey(pkcs8bytes);
}
private static byte[] join(byte[] byteArray1, byte[] byteArray2){
byte[] bytes = new byte[byteArray1.length + byteArray2.length];
System.arraycopy(byteArray1, 0, bytes, 0, byteArray1.length);
System.arraycopy(byteArray2, 0, bytes, byteArray1.length, byteArray2.length);
return bytes;
}
Since the currently proposed implementations which do implement a sorted list by breaking the Collection API, have an own implementation of a tree or something similar, I was curios how an implementation based on the TreeMap would perform. (Especialy since the TreeSet does base on TreeMap, too)
If someone is interested in that, too, he or she can feel free to look into it:
Its part of the core library, you can add it via Maven dependency of course. (Apache License)
Currently the implementation seems to compare quite well on the same level than the guava SortedMultiSet and to the TreeList of the Apache Commons library.
But I would be happy if more than only me would test the implementation to be sure I did not miss something important.
Best regards!
Combining a few of the answers above plus one other additional item solved the problem for me.
You can also use the pipeline
stage to perform checks on a sub-docunment array
Here's the example using python
(sorry I'm snake people).
db.products.aggregate([
{ '$lookup': {
'from': 'products',
'let': { 'pid': '$products' },
'pipeline': [
{ '$match': { '$expr': { '$in': ['$_id', '$$pid'] } } }
// Add additional stages here
],
'as':'productObjects'
}
])
The catch here is to match all objects in the ObjectId
array
(foreign _id
that is in local
field/prop products
).
You can also clean up or project the foreign records with additional stage
s, as indicated by the comment above.
For specific month and year use date() as natural language as following
$first_date = date('d-m-Y',strtotime('first day of april 2010'));
$last_date = date('d-m-Y',strtotime('last day of april 2010'));
// Isn't it simple way?
but for Current month
$first_date = date('d-m-Y',strtotime('first day of this month'));
$last_date = date('d-m-Y',strtotime('last day of this month'));
This will create a dropdown menu from an array and automatically assign its respective value.
<?php
$names = array('tn'=>'Tunisia','us'=>'United States','fr'=>'France');
echo '<select name="countries">';
foreach($names AS $let=>$word){
echo '<option value="'.$let.'">'.$word.'</option>';
}
echo '</select>';
?>
<select name="countries">
<?php
$countries = array('tn'=> "Tunisia", "us"=>'United States',"fr"=>'France');
foreach($countries as $select=>$country_name){
echo '<option value="' . $select . '">' . $country_name . '</option>';
}
?>
</select>
<?php
$my_array = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France'
);
echo '<select name="countries">';
echo '<option value="none">Select...</option>';
foreach ($my_array as $k => $v) {
echo '<option value="' . $k . '">' . $v . '</option>';
}
echo '</select>';
?>
Has your problem been resolved? What is your target SDK? Try adding android;maxSDKVersion="21"
to <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Since inline events are executed as functions you can simply use arguments.
<p id="p" onclick="doSomething.apply(this, arguments)">
and
function doSomething(e) {
if (!e) e = window.event;
// 'e' is the event.
// 'this' is the P element
}
The 'event' that is mentioned in the accepted answer is actually the name of the argument passed to the function. It has nothing to do with the global event.
@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.
.box {_x000D_
width: 500px;_x000D_
height: 100px;_x000D_
border: solid 5px #000;_x000D_
border-color: transparent transparent #000 transparent;_x000D_
border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
The argument to split is a regular expression. "." matches anything so your delimiter to split on is anything.
You could unregister the control with
regsvr32 /u badboy.ocx
at the command line. Though i would suggest testing these things in a vmware.
Add this to your web config and change the catalog name which is your database name:
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True;"/></connectionStrings>
Reference System.Configuration assembly in your project.
Here is how you retrieve connection string from the config file:
System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Simply change 'itunes' to 'phobos' in the app link.
http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=300136119&mt=8
Now it will open the App Store directly
I had many users controls but one refused to show in the Toolbox, even though I rebuilt the solution and it was checked in the Choose Items... dialog.
Solution:
Note this also requires you have the AutoToolboxPopulate option enabled. As @DaveF answer suggests.
Alternate Solution: I'm not sure if this works, and I couldn't try it since I already resolved my issue, but if you unchecked the user control from the Choose Items... dialog, hit OK, then opened it back up and checked the user control. That might also work.
There are two cases in which this error is raised.
Using param to name the parameters allows you to ignore the order of the parameters:
ParamEx.ps1
# Show how to handle command line parameters in Windows PowerShell
param(
[string]$FileName,
[string]$Bogus
)
write-output 'This is param FileName:'+$FileName
write-output 'This is param Bogus:'+$Bogus
ParaEx.bat
rem Notice that named params mean the order of params can be ignored
powershell -File .\ParamEx.ps1 -Bogus FooBar -FileName "c:\windows\notepad.exe"
Tip: generate error.
declare @Day int, @Config_Node varchar(50)
set @Config_Node = 'value to trace'
set @Day = @Config_Node
You will get this message:
Conversion failed when converting the varchar value 'value to trace' to data type int.
var elArray = [];
var elObjeto = {};
elArray.constructor == Array //TRUE
elArray.constructor == Object//TALSE
elObjeto.constructor == Array//FALSE
elObjeto.constructor == Object//TRUE
Try converting the entry to a string first. As long as the database column type is a date it will be formated as a date.
self.date || self.exif_date_time_original.to_s
use app.set & app.get
Setting data
router.get(
"/facebook/callback",
passport.authenticate("facebook"),
(req, res) => {
req.app.set('user', res.req.user)
return res.redirect("/sign");
}
);
Getting data
router.get("/sign", (req, res) => {
console.log('sign', req.app.get('user'))
});
Sounds like the recommended way to do it is to have your server read the Origin header from the client, compare that to the list of domains you would like to allow, and if it matches, echo the value of the Origin
header back to the client as the Access-Control-Allow-Origin
header in the response.
With .htaccess
you can do it like this:
# ----------------------------------------------------------------------
# Allow loading of external fonts
# ----------------------------------------------------------------------
<FilesMatch "\.(ttf|otf|eot|woff|woff2)$">
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com|otherdomain.example|dev02.otherdomain.example)$" AccessControlAllowOrigin=$0
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header merge Vary Origin
</IfModule>
</FilesMatch>
A simple jquery solution for those who don't need a pure css solution:
$(".letter").hover(function() {_x000D_
$(this).closest("#word").toggleClass("hovered")_x000D_
});
_x000D_
.hovered {_x000D_
background-color: lightblue;_x000D_
}_x000D_
_x000D_
.letter {_x000D_
margin: 20px;_x000D_
background: lightgray;_x000D_
}_x000D_
_x000D_
.letter:hover {_x000D_
background: grey;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="word">_x000D_
<div class="letter">T</div>_x000D_
<div class="letter">E</div>_x000D_
<div class="letter">S</div>_x000D_
<div class="letter">T</div>_x000D_
</div>
_x000D_
There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.
getdate()
or getutcdate()
.
Do you want to print the entire list or you want to iterate through each element of the list? Either way to print anything meaningful your Dog
class need to override the toString()
method (as mentioned in other answers) from the Object
class to return a valid result.
public class Print {
public static void main(final String[] args) {
List<Dog> list = new ArrayList<Dog>();
Dog e = new Dog("Tommy");
list.add(e);
list.add(new Dog("tiger"));
System.out.println(list);
for(Dog d:list) {
System.out.println(d);
// prints [Tommy, tiger]
}
}
private static class Dog {
private final String name;
public Dog(final String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
}
The output of this code is:
[Tommy, tiger]
Tommy
tiger
Edit: After updating to appcompat-v7:22.1.1 and using AppCompatActivity
instead of ActionBarActivity
my styles.xml looks like:
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
</style>
Note: This means I am using a Toolbar
provided by the framework (NOT included in an XML file).
This worked for me:
styles.xml file:
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="windowActionBar">false</item>
<item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
</style>
Update: A quote from Gabriele Mariotti's blog.
With the new Toolbar you can apply a style and a theme. They are different! The style is local to the Toolbar view, for example the background color. The app:theme is instead global to all ui elements inflated in the Toolbar, for example the color of the title and icons.
Tested on Angular 11. I need an extra object 'typeSelected'. Pay attention I'm not using [(ngValue)] as other answers do :
HTML
<mat-select formControlName="type" [(value)]="typeSelected" [compareWith]="typeComparation">
<mat-option *ngFor="let myType of allSurveysTypes" [value]="myType">
{{myType.title}}
</mat-option>
</mat-select>
CODE
// declaration
typeSelected: SurveyType;
...
// assigning variable 'type' of object 'survey' to 'typeSelected'
this.typeSelected = survey?.type;
...
// function to compare SurveyType objects
typeComparation = ( option, value ) => {
if (option && value) {
return option.id === value.id;
}
}
If the anonymous type causes trouble for you, you can create a simple data class:
public class PermissionsAndPages
{
public ObjectPermissions Permissions {get;set}
public Pages Pages {get;set}
}
and then in your query:
select new PermissionsAndPages { Permissions = op, Page = pg };
Then you can pass this around:
return queryResult.SingleOrDefault(); // as PermissionsAndPages
As @Danial Martine said iOS won't show a notification banner/alert. That's by design. But if really have to do it then there is one way . I have also achieve this by same.
1.Download the parse frame work from Parse FrameWork
2.Import #import <Parse/Parse.h>
3.Add following code to your didReceiveRemoteNotification Method
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
[PFPush handlePush:userInfo];
}
PFPush will take care how to handle the remote notification . If App is in foreground this shows the alert otherwise it shows the notification at the top.
something like import sys; sys.exit(0)
?
I think the problem was the two single quotes missing.
This is the sql I run to the MSSMS:
WHERE checktime >= '2019-01-24 15:01:36.000' AND checktime <= '2019-01-25 16:01:36.000'
As you can see there are two single quotes, so your codes must be:
string sqlFormattedDate = "'" + myDateTime.Date.ToString("yyyy-MM-dd") + " " + myDateTime.TimeOfDay.ToString("HH:mm:ss") + "'";
Use single quotes for every string in MSSQL or even in MySQL. I hope this helps.
DISCLAIMER: Please read comments below carefully, and I assume you've already read the accepted answer. As I said nearly 5 years ago:
if anyone has any comments to add for situations when this is NOT an adequate or optimal solution then please comment below
Right click on the database name.
Select Tasks ? Shrink ? Database
Then click OK!
I usually open the Windows Explorer directory containing the database files, so I can immediately see the effect.
I was actually quite surprised this worked! Normally I've used DBCC before, but I just tried that and it didn't shrink anything, so I tried the GUI (2005) and it worked great - freeing up 17 GB in 10 seconds
In Full recovery mode this might not work, so you have to either back up the log first, or change to Simple recovery, then shrink the file. [thanks @onupdatecascade for this]
--
PS: I appreciate what some have commented regarding the dangers of this, but in my environment I didn't have any issues doing this myself especially since I always do a full backup first. So please take into consideration what your environment is, and how this affects your backup strategy and job security before continuing. All I was doing was pointing people to a feature provided by Microsoft!
An alternative that also has the added benefit of easily logging its output:
hexs = "13 00 00 00 08 00"
logging.debug(hexs)
key = bytearray.fromhex(hexs)
allows you to do easy substitutions like so:
hexs = "13 00 00 00 08 {:02X}".format(someByte)
logging.debug(hexs)
key = bytearray.fromhex(hexs)
Use two view types in the your RVAdapter
. One for expanded layout and other for collapsed.
And the magic happens with setting android:animateLayoutChanges="true"
for RecyclerView
Checkout the effect achieved using this at 0:42 in this video
Width can be set to specific column as below: By percentages:
<asp:BoundField HeaderText="UserInfo" DataField="UserInfo"
SortExpression="UserInfo" ItemStyle-Width="100%"></asp:BoundField>
OR
By pixel:
<asp:BoundField HeaderText="UserInfo" DataField="UserInfo"
SortExpression="UserInfo" ItemStyle-Width="500px"></asp:BoundField>
This is a nice way of sorting a table:
$(document).ready(function () {_x000D_
$('th').each(function (col) {_x000D_
$(this).hover(_x000D_
function () {_x000D_
$(this).addClass('focus');_x000D_
},_x000D_
function () {_x000D_
$(this).removeClass('focus');_x000D_
}_x000D_
);_x000D_
$(this).click(function () {_x000D_
if ($(this).is('.asc')) {_x000D_
$(this).removeClass('asc');_x000D_
$(this).addClass('desc selected');_x000D_
sortOrder = -1;_x000D_
} else {_x000D_
$(this).addClass('asc selected');_x000D_
$(this).removeClass('desc');_x000D_
sortOrder = 1;_x000D_
}_x000D_
$(this).siblings().removeClass('asc selected');_x000D_
$(this).siblings().removeClass('desc selected');_x000D_
var arrData = $('table').find('tbody >tr:has(td)').get();_x000D_
arrData.sort(function (a, b) {_x000D_
var val1 = $(a).children('td').eq(col).text().toUpperCase();_x000D_
var val2 = $(b).children('td').eq(col).text().toUpperCase();_x000D_
if ($.isNumeric(val1) && $.isNumeric(val2))_x000D_
return sortOrder == 1 ? val1 - val2 : val2 - val1;_x000D_
else_x000D_
return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0;_x000D_
});_x000D_
$.each(arrData, function (index, row) {_x000D_
$('tbody').append(row);_x000D_
});_x000D_
});_x000D_
});_x000D_
});
_x000D_
table, th, td {_x000D_
border: 1px solid black;_x000D_
}_x000D_
th {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table>_x000D_
<tr><th>id</th><th>name</th><th>age</th></tr>_x000D_
<tr><td>1</td><td>Julian</td><td>31</td></tr>_x000D_
<tr><td>2</td><td>Bert</td><td>12</td></tr>_x000D_
<tr><td>3</td><td>Xavier</td><td>25</td></tr>_x000D_
<tr><td>4</td><td>Mindy</td><td>32</td></tr>_x000D_
<tr><td>5</td><td>David</td><td>40</td></tr>_x000D_
</table>
_x000D_
The fiddle can be found here:
https://jsfiddle.net/e3s84Luw/
The explanation can be found here: https://www.learningjquery.com/2017/03/how-to-sort-html-table-using-jquery-code
There are two solutions posted on that page. The one with lower votes I would recommend if possible.
If you are using HTML5 then it is perfectly valid to put a div
inside of a
. As long as the div doesn't also contain some other specific elements like other link tags.
<a href="Music.html">
<div id="music" class="nav">
Music I Like
</div>
</a>
The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative
to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index
at all from that example.
div { position: relative; }
.hyperspan {
position:absolute;
width:100%;
height:100%;
left:0;
top:0;
}
<div id="music" class="nav">Music I Like
<a href="http://www.google.com">
<span class="hyperspan"></span>
</a>
</div>
When you give absolute
positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative
to the parent div you tell the span to only be as big as that.
I was able to get a great solution to this problem with iScroll, with the feel of momentum scrolling and everything https://github.com/cubiq/iscroll The github doc is great, and I mostly followed it. Here's the details of my implementation.
HTML: I wrapped the scrollable area of my content in some divs that iScroll can use:
<div id="wrapper">
<div id="scroller">
... my scrollable content
</div>
</div>
CSS: I used the Modernizr class for "touch" to target my style changes only to touch devices (because I only instantiated iScroll on touch).
.touch #wrapper {
position: absolute;
z-index: 1;
top: 0;
bottom: 0;
left: 0;
right: 0;
overflow: hidden;
}
.touch #scroller {
position: absolute;
z-index: 1;
width: 100%;
}
JS: I included iscroll-probe.js from the iScroll download, and then initialized the scroller as below, where updatePosition is my function that reacts to the new scroll position.
# coffeescript
if Modernizr.touch
myScroller = new IScroll('#wrapper', probeType: 3)
myScroller.on 'scroll', updatePosition
myScroller.on 'scrollEnd', updatePosition
You have to use myScroller to get the current position now, instead of looking at the scroll offset. Here is a function taken from http://markdalgleish.com/presentations/embracingtouch/ (a super helpful article, but a little out of date now)
function getScroll(elem, iscroll) {
var x, y;
if (Modernizr.touch && iscroll) {
x = iscroll.x * -1;
y = iscroll.y * -1;
} else {
x = elem.scrollTop;
y = elem.scrollLeft;
}
return {x: x, y: y};
}
The only other gotcha was occasionally I would lose part of my page that I was trying to scroll to, and it would refuse to scroll. I had to add in some calls to myScroller.refresh() whenever I changed the contents of the #wrapper, and that solved the problem.
EDIT: Another gotcha was that iScroll eats all the "click" events. I turned on the option to have iScroll emit a "tap" event and handled those instead of "click" events. Thankfully I didn't need much clicking in the scroll area, so this wasn't a big deal.
If you are using ASP.NET MVC Core 3 or newer, IHostingEnvironment
has been deprecated and replaced with IWebHostEnvironment
public Startup(IWebHostEnvironment webHostEnvironment)
{
var webRootPath = webHostEnvironment.WebRootPath;
}
I guess it will be a string. But the input parameters will be sent to the database & appropriate cast/conversions will be applied prior to creating an actual SQL statement.
To give you an example, it might try and see if the CAST/Conversion works.
If it works, it could create a final statement out of it.
SELECT * From MyTable WHERE param = CAST('10; DROP TABLE Other' AS varchar(30))
Try an example with a SQL statement accepting a numeric parameter.
Now, try passing a string variable (with numeric content that is acceptable as numeric parameter). Does it raise any error?
Now, try passing a string variable (with content that is not acceptable as numeric parameter). See what happens?
Eclipse 3.5 for Java Developer is the best option for you and 3.6 version is good but not at all because of compatibility issues.
The preference for present-tense, imperative-style commit messages comes from Git itself. From Documentation/SubmittingPatches in the Git repo:
Describe your changes in imperative mood, e.g. "make xyzzy do frotz" instead of "[This patch] makes xyzzy do frotz" or "[I] changed xyzzy to do frotz", as if you are giving orders to the codebase to change its behavior.
So you'll see a lot of Git commit messages written in that style. If you're working on a team or on open source software, it is helpful if everyone sticks to that style for consistency. Even if you're working on a private project, and you're the only one who will ever see your git history, it's helpful to use the imperative mood because it establishes good habits that will be appreciated when you're working with others.
Radio button without panel
public class RadioButton2 : RadioButton
{
public string GroupName { get; set; }
}
private void RadioButton2_Clicked(object sender, EventArgs e)
{
RadioButton2 rb = (sender as RadioButton2);
if (!rb.Checked)
{
foreach (var c in Controls)
{
if (c is RadioButton2 && (c as RadioButton2).GroupName == rb.GroupName)
{
(c as RadioButton2).Checked = false;
}
}
rb.Checked = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
//a group
RadioButton2 rb1 = new RadioButton2();
rb1.Text = "radio1";
rb1.AutoSize = true;
rb1.AutoCheck = false;
rb1.Top = 50;
rb1.Left = 50;
rb1.GroupName = "a";
rb1.Click += RadioButton2_Clicked;
Controls.Add(rb1);
RadioButton2 rb2 = new RadioButton2();
rb2.Text = "radio2";
rb2.AutoSize = true;
rb2.AutoCheck = false;
rb2.Top = 50;
rb2.Left = 100;
rb2.GroupName = "a";
rb2.Click += RadioButton2_Clicked;
Controls.Add(rb2);
//b group
RadioButton2 rb3 = new RadioButton2();
rb3.Text = "radio3";
rb3.AutoSize = true;
rb3.AutoCheck = false;
rb3.Top = 80;
rb3.Left = 50;
rb3.GroupName = "b";
rb3.Click += RadioButton2_Clicked;
Controls.Add(rb3);
RadioButton2 rb4 = new RadioButton2();
rb4.Text = "radio4";
rb4.AutoSize = true;
rb4.AutoCheck = false;
rb4.Top = 80;
rb4.Left = 100;
rb4.GroupName = "b";
rb4.Click += RadioButton2_Clicked;
Controls.Add(rb4);
}
You can simply save your data in a variable and use find(to get single object of records) or filter(to get single array of records) method of JavaScript.
For example :-
let data = {
"list": [
{"name":"my Name","id":12,"type":"car owner"},
{"name":"my Name2","id":13,"type":"car owner2"},
{"name":"my Name4","id":14,"type":"car owner3"},
{"name":"my Name4","id":15,"type":"car owner5"}
]}
and now use below command onkeyup or enter
to get single object
data.list.find( record => record.name === "my Name")
to get single array object
data.list.filter( record => record.name === "my Name")
I need to decrypt a password. The password is crypted with password_hash function.
$password = 'examplepassword'; $crypted = password_hash($password, PASSWORD_DEFAULT);
Its not clear to me if you need password_verify
, or you are trying to gain unauthorized access to the application or database. Other have talked about password_verify
, so here's how you could gain unauthorized access. Its what bad guys often do when they try to gain access to a system.
First, create a list of plain text passwords. A plain text list can be found in a number of places due to the massive data breaches from companies like Adobe. Sort the list and then take the top 10,000 or 100,000 or so.
Second, create a list of digested passwords. Simply encrypt or hash the password. Based on your code above, it does not look like a salt is being used (or its a fixed salt). This makes the attack very easy.
Third, for each digested password in the list, perform a select in an attempt to find a user who is using the password:
$sql_script = 'select * from USERS where password="'.$digested_password.'"'
Fourth, profit.
So, rather than picking a user and trying to reverse their password, the bad guy picks a common password and tries to find a user who is using it. Odds are on the bad guy's side...
Because the bad guy does these things, it would behove you to not let users choose common passwords. In this case, take a look at ProCheck, EnFilter or Hyppocrates (et al). They are filtering libraries that reject bad passwords. ProCheck achieves very high compression, and can digest multi-million word password lists into a 30KB data file.
If you're looking to turn the items in a list into a big long string, do this: String.Join("", myList)
. Some older versions of the framework don't allow you to pass an IEnumerable as the second parameter, so you may need to convert your list to an array by calling .ToArray().
Some people don't like this, and it's more of a .NET convention than Java, but you can name your interfaces with a capital I prefix, for example:
IProductRepository - interface
ProductRepository, SqlProductRepository, etc. - implementations
The people opposed to this naming convention might argue that you shouldn't care whether you're working with an interface or an object in your code, but I find it easier to read and understand on-the-fly.
I wouldn't name the implementation class with a "Class" suffix. That may lead to confusion, because you can actually work with "class" (i.e. Type) objects in your code, but in your case, you're not working with the class object, you're just working with a plain-old object.
Why not just git reset --soft <branch_name>
?
Demonstration:
mkdir myrepo; cd myrepo; git init
touch poem; git add poem; git commit -m 'add poem' # first commit
git branch original
echo bananas > poem; git commit -am 'change poem' # second commit
echo are tasty >> poem # unstaged change
git reset --soft original
Result:
$ git diff --cached
diff --git a/poem b/poem
index e69de29..9baf85e 100644
--- a/poem
+++ b/poem
@@ -0,0 +1 @@
+bananas
$ git diff
diff --git a/poem b/poem
index 9baf85e..ac01489 100644
--- a/poem
+++ b/poem
@@ -1 +1,2 @@
bananas
+are tasty
One thing to note though, is that the current branch changes to original
. You’re still left in the previous branch after the process, but can easily git checkout original
, because it’s the same state. If you do not want to lose the previous HEAD
, you should note the commit reference and do git branch -f <previous_branch> <commit>
after that.
OS X doesn't use bash 4 yet, nor does it have /usr/bin/timeout, so here's a function that works on OS X without home-brew or macports that is similar to /usr/bin/timeout (based on Tino's answer). Parameter validation, help, usage, and support for other signals are an exercise for reader.
# implement /usr/bin/timeout only if it doesn't exist
[ -n "$(type -p timeout 2>&1)" ] || function timeout { (
set -m +b
sleep "$1" &
SPID=${!}
("${@:2}"; RETVAL=$?; kill ${SPID}; exit $RETVAL) &
CPID=${!}
wait %1
SLEEPRETVAL=$?
if [ $SLEEPRETVAL -eq 0 ] && kill ${CPID} >/dev/null 2>&1 ; then
RETVAL=124
# When you need to make sure it dies
#(sleep 1; kill -9 ${CPID} >/dev/null 2>&1)&
wait %2
else
wait %2
RETVAL=$?
fi
return $RETVAL
) }
In Android Studio:
I removed git clone and just retain the url only and it worked!!
If you want to keep reference:
Array.prototype.push.apply(destinationArray, sourceArray);
Procedure 1 : Control Layouts rendering by using _ViewStart file in the root directory of the Views folder
This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.
@{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
string cLayout = "";
if (controller == "Webmaster") {
cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
else {
cLayout = "~/Views/Shared/_Layout.cshtml";
}
Layout = cLayout;
}
Procedure 2 : Set Layout by Returning from ActionResult
One the the great feature of ASP.NET MVC is that, we can override the default layout rendering by returning the layout from the ActionResult. So, this is also a way to render different Layout in your ASP.NET MVC application. Following code sample show how it can be done.
public ActionResult Index()
{
SampleModel model = new SampleModel();
//Any Logic
return View("Index", "_WebmasterLayout", model);
}
Procedure 3 : View - wise Layout (By defining Layout within each view on the top)
ASP.NET MVC provides us such a great feature & faxibility to override the default layout rendering by defining the layout on the view. To implement this we can write our code in following manner in each View.
@{
Layout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
Procedure 4 : Placing _ViewStart file in each of the directories
This is a very useful way to set different Layouts for each Controller in your ASP.NET MVC application. If we want to set default Layout for each directories than we can do this by putting _ViewStart file in each of the directories with the required Layout information as shown below:
@{
Layout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
@Jacob Dalton has mentioned this in a comment, but nobody seems to have mentioned in an answer that vim has to be compiled with clipboard support for any of the suggestions mentioned here to work. Mine wasn't configured that way on Mac OS X by default and I had to rebuild vim. Use this the command to find out whether you have it or not vim --version | grep 'clipboard'
. +clipboard
means you're good and the suggestions here will work for you, while -clipboard
means you have to recompile and rebuild vim.
Apparently some POST requests looks like a "GET" to the server (like Heroku...)
So I use this strategy and it works for me:
@RequestMapping(value = "/salvar", method = { RequestMethod.GET, RequestMethod.POST })
You can use the following little trick:
set word=table
set str="jump over the chair"
call set str=%%str:chair=%word%%%
echo %str%
The call
there causes another layer of variable expansion, making it necessary to quote the original %
signs but it all works out in the end.
If it's all the same, perhaps using single-quotes is better since it doesn't require holding down the shift key. Fewer keystrokes == less chance of RSI.
1 - Treat functions as objects.
2 - The apply method is similar to __call __ in Python, which allows you to use an instance of a given class as a function.
If I have open a package in BIDS ("Business Intelligence Development Studio", the tool you use to design the packages), and do not select any item in it, I have a "Properties" pane in the bottom right containing - among others, the MaximumErrorCount
property. If you do not see it, maybe it is minimized and you have to open it (have a look at tabs in the right).
If you cannot find it this way, try the menu: View/Properties Window.
Or try the F4 key.
Composition is just as it sounds - you create an object by plugging in parts.
EDIT the rest of this answer is erroneously based on the following premise.
This is accomplished with Interfaces.
For example, using the Car
example above,
Car implements iDrivable, iUsesFuel, iProtectsOccupants
Motorbike implements iDrivable, iUsesFuel, iShortcutThroughTraffic
House implements iProtectsOccupants
Generator implements iUsesFuel
So with a few standard theoretical components you can build up your object. It's then your job to fill in how a House
protects its occupants, and how a Car
protects its occupants.
Inheritance is like the other way around. You start off with a complete (or semi-complete) object and you replace or Override the various bits you want to change.
For example, MotorVehicle
may come with a Fuelable
method and Drive
method. You may leave the Fuel method as it is because it's the same to fill up a motorbike and a car, but you may override the Drive
method because the Motorbike drives very differently to a Car
.
With inheritance, some classes are completely implemented already, and others have methods that you are forced to override. With Composition nothing's given to you. (but you can Implement the interfaces by calling methods in other classes if you happen to have something laying around).
Composition is seen as more flexible, because if you have a method such as iUsesFuel, you can have a method somewhere else (another class, another project) that just worries about dealing with objects that can be fueled, regardless of whether it's a car, boat, stove, barbecue, etc. Interfaces mandate that classes that say they implement that interface actually have the methods that that interface is all about. For example,
iFuelable Interface:
void AddSomeFuel()
void UseSomeFuel()
int percentageFull()
then you can have a method somewhere else
private void FillHerUp(iFuelable : objectToFill) {
Do while (objectToFill.percentageFull() <= 100) {
objectToFill.AddSomeFuel();
}
Strange example, but it's shows that this method doesn't care what it's filling up, because the object implements iUsesFuel
, it can be filled. End of story.
If you used Inheritance instead, you would need different FillHerUp
methods to deal with MotorVehicles
and Barbecues
, unless you had some rather weird "ObjectThatUsesFuel" base object from which to inherit.
I think this is enough to get you on a nice path:
Sub a()
Dim btn As Button
Application.ScreenUpdating = False
ActiveSheet.Buttons.Delete
Dim t As Range
For i = 2 To 6 Step 2
Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
With btn
.OnAction = "btnS"
.Caption = "Btn " & i
.Name = "Btn" & i
End With
Next i
Application.ScreenUpdating = True
End Sub
Sub btnS()
MsgBox Application.Caller
End Sub
It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.
The Set
interface does not provide any ordering guarantees.
Its sub-interface SortedSet
represents a set that is sorted according to some criterion. In Java 6, there are two standard containers that implement SortedSet
. They are TreeSet
and ConcurrentSkipListSet
.
In addition to the SortedSet
interface, there is also the LinkedHashSet
class. It remembers the order in which the elements were inserted into the set, and returns its elements in that order.
Always you can do it manually. Those are the steps:
git clone github_url
node_modules
folder for e.g. node_modules/browser-sync
Now it should work for you. To be sure it will not break in the future when you do npm i
, continue the upcoming two steps:
package.json
file in it's folder.package.json
and set the same version for where it's appear in the dependencies
part of your package.json
While it's not recommened to do it manually. Sometimes it's good to understand how things are working under the hood, to be able to fix things. I found myself doing it from time to time.
You can just AND the results together if they are stored as TRUE / FALSE values:
=AND(A1:D2)
Or if stored as text, use an array formula - enter the below and press Ctrl+Shift+Enter instead of Enter.
=AND(EXACT(A1:D2,"TRUE"))
It seems they offer a js
option for the format parameter, which will return JSONP. You can retrieve JSONP like so:
function getJSONP(url, success) {
var ud = '_' + +new Date,
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0]
|| document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
success && success(data);
};
script.src = url.replace('callback=?', 'callback=' + ud);
head.appendChild(script);
}
getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
console.log(data);
});
The reason is that php cannot find the correct path of mysql.sock
.
Please make sure that your mysql is running first.
Then, please confirm that which path is the mysql.sock
located, for example /tmp/mysql.sock
then add this path string to php.ini:
Finally, restart Apache.
Here is another one to add to the list ;-)
(attempt a file creation in system location)
CD.>"%SystemRoot%\System32\Drivers\etc\_"
MODE CON COLS=80 LINES=25
IF EXIST "%SystemRoot%\System32\Drivers\etc\_" (
DEL "%SystemRoot%\System32\Drivers\etc\_"
ECHO Has Admin privileges
) ELSE (
ECHO No Admin privileges
)
The MODE CON
reinitializes the screen and surpresses any text/errors when not having the permission to write to the system location.
When speaking with remote machines, Ansible by default assumes you are using SSH keys. SSH keys are encouraged but password authentication can also be used where needed by supplying the option --ask-pass. If using sudo features and when sudo requires a password, also supply --ask-become-pass (previously --ask-sudo-pass which has been deprecated).
Never used the feature but the docs say you can.
Or, if you want a more general approach - i.e. for nesting up to "levelN":
void Main()
{
XElement rootElement = XElement.Load(@"c:\events\test.xml");
Console.WriteLine(GetOutline(0, rootElement));
}
private string GetOutline(int indentLevel, XElement element)
{
StringBuilder result = new StringBuilder();
if (element.Attribute("name") != null)
{
result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
}
foreach (XElement childElement in element.Elements())
{
result.Append(GetOutline(indentLevel + 1, childElement));
}
return result.ToString();
}
Possibly a little bit of a necromancing post here, but...
here's a function that follows up to 10 redirects, and detects infinite redirect loops. also parses result into JSON
Note - uses a callback helper (shown at the end of this post)
( TLDR; full working demo in context here or remixed-version here)
function getJSON(url,cb){
var callback=errBack(cb);
//var callback=errBack(cb,undefined,false);//replace previous line with this to turn off logging
if (typeof url!=='string') {
return callback.error("getJSON:expecting url as string");
}
if (typeof cb!=='function') {
return callback.error("getJSON:expecting cb as function");
}
var redirs = [url],
fetch = function(u){
callback.info("hitting:"+u);
https.get(u, function(res){
var body = [];
callback.info({statusCode:res.statusCode});
if ([301,302].indexOf(res.statusCode)>=0) {
if (redirs.length>10) {
return callback.error("excessive 301/302 redirects detected");
} else {
if (redirs.indexOf(res.headers.location)<0) {
redirs.push(res.headers.location);
return fetch(res.headers.location);
} else {
return callback.error("301/302 redirect loop detected");
}
}
} else {
res.on('data', function(chunk){
body.push(chunk);
callback.info({onData:{chunkSize:chunk.length,chunks:body.length}});
});
res.on('end', function(){
try {
// convert to a single buffer
var json = Buffer.concat(body);
console.info({onEnd:{chunks:body.length,bodyLength:body.length}});
// parse the buffer as json
return callback.result(JSON.parse(json),json);
} catch (err) {
console.error("exception in getJSON.fetch:",err.message||err);
if (json.length>32) {
console.error("json==>|"+json.toString('utf-8').substr(0,32)+"|<=== ... (+"+(json.length-32)+" more bytes of json)");
} else {
console.error("json==>|"+json.toString('utf-8')+"|<=== json");
}
return callback.error(err,undefined,json);
}
});
}
});
};
fetch(url);
}
Note - uses a callback helper (shown below)
you can paste this into the node console and it should run as is.
( or for full working demo in context see here )
var
fs = require('fs'),
https = require('https');
function errBack (cb,THIS,logger) {
var
self,
EB=function(fn,r,e){
if (logger===false) {
fn.log=fn.info=fn.warn=fn.errlog=function(){};
} else {
fn.log = logger?logger.log : console.log.bind(console);
fn.info = logger?logger.info : console.info.bind(console);
fn.warn = logger?logger.warn : console.warn.bind(console);
fn.errlog = logger?logger.error : console.error.bind(console);
}
fn.result=r;
fn.error=e;
return (self=fn);
};
if (typeof cb==='function') {
return EB(
logger===false // optimization when not logging - don't log errors
? function(err){
if (err) {
cb (err);
return true;
}
return false;
}
: function(err){
if (err) {
self.errlog(err);
cb (err);
return true;
}
return false;
},
function () {
return cb.apply (THIS,Array.prototype.concat.apply([undefined],arguments));
},
function (err) {
return cb.apply (THIS,Array.prototype.concat.apply([typeof err==='string'?new Error(err):err],arguments));
}
);
} else {
return EB(
function(err){
if (err) {
if (typeof err ==='object' && err instanceof Error) {
throw err;
} else {
throw new Error(err);
}
return true;//redundant due to throw, but anyway.
}
return false;
},
logger===false
? self.log //optimization :resolves to noop when logger==false
: function () {
self.info("ignoring returned arguments:",Array.prototype.concat.apply([],arguments));
},
function (err) {
throw typeof err==='string'?new Error(err):err;
}
);
}
}
function getJSON(url,cb){
var callback=errBack(cb);
if (typeof url!=='string') {
return callback.error("getJSON:expecting url as string");
}
if (typeof cb!=='function') {
return callback.error("getJSON:expecting cb as function");
}
var redirs = [url],
fetch = function(u){
callback.info("hitting:"+u);
https.get(u, function(res){
var body = [];
callback.info({statusCode:res.statusCode});
if ([301,302].indexOf(res.statusCode)>=0) {
if (redirs.length>10) {
return callback.error("excessive 302 redirects detected");
} else {
if (redirs.indexOf(res.headers.location)<0) {
redirs.push(res.headers.location);
return fetch(res.headers.location);
} else {
return callback.error("302 redirect loop detected");
}
}
} else {
res.on('data', function(chunk){
body.push(chunk);
console.info({onData:{chunkSize:chunk.length,chunks:body.length}});
});
res.on('end', function(){
try {
// convert to a single buffer
var json = Buffer.concat(body);
callback.info({onEnd:{chunks:body.length,bodyLength:body.length}});
// parse the buffer as json
return callback.result(JSON.parse(json),json);
} catch (err) {
// read with "bypass refetch" option
console.error("exception in getJSON.fetch:",err.message||err);
if (json.length>32) {
console.error("json==>|"+json.toString('utf-8').substr(0,32)+"|<=== ... (+"+(json.length-32)+" more bytes of json)");
} else {
console.error("json==>|"+json.toString('utf-8')+"|<=== json");
}
return callback.error(err,undefined,json);
}
});
}
});
};
fetch(url);
}
var TLDs,TLDs_fallback = "com.org.tech.net.biz.info.code.ac.ad.ae.af.ag.ai.al.am.ao.aq.ar.as.at.au.aw.ax.az.ba.bb.bd.be.bf.bg.bh.bi.bj.bm.bn.bo.br.bs.bt.bv.bw.by.bz.ca.cc.cd.cf.cg.ch.ci.ck.cl.cm.cn.co.cr.cu.cv.cw.cx.cy.cz.de.dj.dk.dm.do.dz.ec.ee.eg.er.es.et.eu.fi.fj.fk.fm.fo.fr.ga.gb.gd.ge.gf.gg.gh.gi.gl.gm.gn.gp.gq.gr.gs.gt.gu.gw.gy.hk.hm.hn.hr.ht.hu.id.ie.il.im.in.io.iq.ir.is.it.je.jm.jo.jp.ke.kg.kh.ki.km.kn.kp.kr.kw.ky.kz.la.lb.lc.li.lk.lr.ls.lt.lu.lv.ly.ma.mc.md.me.mg.mh.mk.ml.mm.mn.mo.mp.mq.mr.ms.mt.mu.mv.mw.mx.my.mz.na.nc.ne.nf.ng.ni.nl.no.np.nr.nu.nz.om.pa.pe.pf.pg.ph.pk.pl.pm.pn.pr.ps.pt.pw.py.qa.re.ro.rs.ru.rw.sa.sb.sc.sd.se.sg.sh.si.sj.sk.sl.sm.sn.so.sr.st.su.sv.sx.sy.sz.tc.td.tf.tg.th.tj.tk.tl.tm.tn.to.tr.tt.tv.tw.tz.ua.ug.uk.us.uy.uz.va.vc.ve.vg.vi.vn.vu.wf.ws.ye.yt.za.zm.zw".split(".");
var TLD_url = "https://gitcdn.xyz/repo/umpirsky/tld-list/master/data/en/tld.json";
var TLD_cache = "./tld.json";
var TLD_refresh_msec = 15 * 24 * 60 * 60 * 1000;
var TLD_last_msec;
var TLD_default_filter=function(dom){return dom.substr(0,3)!="xn-"};
function getTLDs(cb,filter_func){
if (typeof cb!=='function') return TLDs;
var
read,fetch,
CB_WRAP=function(tlds){
return cb(
filter_func===false
? cb(tlds)
: tlds.filter(
typeof filter_func==='function'
? filter_func
: TLD_default_filter)
);
},
check_mtime = function(mtime) {
if (Date.now()-mtime > TLD_refresh_msec) {
return fetch();
}
if (TLDs) return CB_WRAP (TLDs);
return read();
};
fetch = function(){
getJSON(TLD_url,function(err,data){
if (err) {
console.log("exception in getTLDs.fetch:",err.message||err);
return read(true);
} else {
TLDs=Object.keys(data);
fs.writeFile(TLD_cache,JSON.stringify(TLDs),function(err){
if (err) {
// ignore save error, we have the data
CB_WRAP(TLDs);
} else {
// get mmtime for the file we just made
fs.stat(TLD_cache,function(err,stats){
if (!err && stats) {
TLD_last_msec = stats.mtimeMs;
}
CB_WRAP(TLDs);
});
}
});
}
});
};
read=function(bypassFetch) {
fs.readFile(TLD_cache,'utf-8',function(err,json){
try {
if (err) {
if (bypassFetch) {
// after a http errror, we fallback to hardcoded basic list of tlds
// if the disk file is not readable
console.log("exception in getTLDs.read.bypassFetch:",err.messsage||err);
throw err;
}
// if the disk read failed, get the data from the CDN server instead
return fetch();
}
TLDs=JSON.parse(json);
if (bypassFetch) {
// we need to update stats here as fetch called us directly
// instead of being called by check_mtime
return fs.stat(TLD_cache,function(err,stats){
if (err) return fetch();
TLD_last_msec =stats.mtimeMs;
return CB_WRAP(TLDs);
});
}
} catch (e){
// after JSON error, if we aren't in an http fail situation, refetch from cdn server
if (!bypassFetch) {
return fetch();
}
// after a http,disk,or json parse error, we fallback to hardcoded basic list of tlds
console.log("exception in getTLDs.read:",err.messsage||err);
TLDs=TLDs_fallback;
}
return CB_WRAP(TLDs);
});
};
if (TLD_last_msec) {
return check_mtime(TLD_last_msec);
} else {
fs.stat(TLD_cache,function(err,stats){
if (err) return fetch();
TLD_last_msec =stats.mtimeMs;
return check_mtime(TLD_last_msec);
});
}
}
getTLDs(console.log.bind(console));
for all xml with namespace use local-name()
//*[local-name()='Parent'][@id='1']/*[local-name()='Children']/*[local-name()='child']/@name
Assuming the submodule's repository does contain a commit you want to use (unlike the commit that is referenced from current state of the super-project), there are two ways to do it.
The first requires you to already know the commit from the submodule that you want to use. It works from the “inside, out” by directly adjusting the submodule then updating the super-project. The second works from the “outside, in” by finding the super-project's commit that modified the submodule and then reseting the super-project's index to refer to a different submodule commit.
If you already know which commit you want the submodule to use, cd
to the submodule, check out the commit you want, then git add
and git commit
it back in the super-project.
Example:
$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'
Oops, someone made a super-project commit that refers to an unpublished commit in the submodule sub
. Somehow, we already know that we want the submodule to be at commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
. Go there and check it out directly.
$ cd sub
$ git checkout 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
Note: moving to '5d5a3ee314476701a20f2c6ec4a53f88d651df6c' which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
git checkout -b <new_branch_name>
HEAD is now at 5d5a3ee... quux
$ cd ..
Since we are checking out a commit, this produces a detached HEAD in the submodule. If you want to make sure that the submodule is using a branch, then use git checkout -b newbranch <commit>
to create and checkout a branch at the commit or checkout the branch that you want (e.g. one with the desired commit at the tip).
A checkout in the submodule is reflected in the super-project as a change to the working tree. So we need to stage the change in the super-project's index and verify the results.
$ git add sub
$ git submodule update
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
The submodule update was silent because the submodule is already at the specified commit. The first diff shows that the index and worktree are the same. The third diff shows that the only staged change is moving the sub
submodule to a different commit.
git commit
This commits the fixed-up submodule entry.
If you are not sure which commit you should use from the submodule, you can look at the history in the superproject to guide you. You can also manage the reset directly from the super-project.
$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'
This is the same situation as above. But this time we will focus on fixing it from the super-project instead of dipping into the submodule.
$ git log --oneline -p -- sub
ce5d37c local change in sub
diff --git a/sub b/sub
index 5d5a3ee..e47c0a1 160000
--- a/sub
+++ b/sub
@@ -1 +1 @@
-Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
+Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
bca4663 added sub
diff --git a/sub b/sub
new file mode 160000
index 0000000..5d5a3ee
--- /dev/null
+++ b/sub
@@ -0,0 +1 @@
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
OK, it looks like it went bad in ce5d37c
, so we will restore the submodule from its parent (ce5d37c~
).
Alternatively, you can take the submodule's commit from the patch text (5d5a3ee314476701a20f2c6ec4a53f88d651df6c
) and use the above “inside, out” process instead.
$ git checkout ce5d37c~ -- sub
This reset the submodule entry for sub
to what it was at commit ce5d37c~
in the super-project.
$ git submodule update
Submodule path 'sub': checked out '5d5a3ee314476701a20f2c6ec4a53f88d651df6c'
The submodule update went OK (it indicates a detached HEAD).
$ git diff ce5d37c~ -- sub
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
The first diff shows that sub
is now the same in ce5d37c~
. The second diff shows that the index and worktree are the same. The third diff shows the only staged change is moving the sub
submodule to a different commit.
git commit
This commits the fixed-up submodule entry.
Now you can convert it by using PyInstaller. It works with even Python 3.
Steps:
pip install pyinstaller
pyinstaller <filename>
According to the git-stash manpage, "A stash is represented as a commit whose tree records the state of the working directory, and its first parent is the commit at HEAD
when the stash was created," and git stash show -p
gives us "the changes recorded in the stash as a diff between the stashed state and its original parent.
To keep your other changes intact, use git stash show -p | patch --reverse
as in the following:
$ git init
Initialized empty Git repository in /tmp/repo/.git/
$ echo Hello, world >messages
$ git add messages
$ git commit -am 'Initial commit'
[master (root-commit)]: created 1ff2478: "Initial commit"
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 messages
$ echo Hello again >>messages
$ git stash
$ git status
# On branch master
nothing to commit (working directory clean)
$ git stash apply
# On branch master
# Changed but not updated:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: messages
#
no changes added to commit (use "git add" and/or "git commit -a")
$ echo Howdy all >>messages
$ git diff
diff --git a/messages b/messages
index a5c1966..eade523 100644
--- a/messages
+++ b/messages
@@ -1 +1,3 @@
Hello, world
+Hello again
+Howdy all
$ git stash show -p | patch --reverse
patching file messages
Hunk #1 succeeded at 1 with fuzz 1.
$ git diff
diff --git a/messages b/messages
index a5c1966..364fc91 100644
--- a/messages
+++ b/messages
@@ -1 +1,2 @@
Hello, world
+Howdy all
Edit:
A light improvement to this is to use git apply
in place of patch:
git stash show -p | git apply --reverse
Alternatively, you can also use git apply -R
as a shorthand to git apply --reverse
.
I've been finding this really handy lately...
no, 100 small objects needs more information (memory) than one big.
SELECT * FROM courses WHERE (NOW() + INTERVAL 2 HOUR) > start_time
You want to do what Allain said, however be aware that sometimes the image loads before dom ready, which means your load handler won't fire. The best way is to do as Allain says, but set the src of the image with javascript after attaching the load hander. This way you can guarantee that it fires.
In terms of accessibility, will your site still work for people without javascript? You may want to give the img tag the correct src, attach you dom ready handler to run your js: clear the image src (give it a fixed with and height with css to prevent the page flickering), then set your img load handler, then reset the src to the correct file. This way you cover all bases :)
>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14
Here is the solution.
The HTML:
<table cellspacing="0" cellpadding="0">
<tr>
<td>
123
</td>
</tr>
</table>
The CSS:
table {
border-spacing:0;
border-collapse:collapse;
}
Hope this helps.
EDIT
td, th {padding:0}
Just change the inner query value: E.g Select Top (2)* from Student_Info order by ClassID desc
Use for both problem:
Select Top (1)* from
(
Select Top (1)* from Student_Info order by ClassID desc
) as wsdwe
order by ClassID
I tried to fix the 'no public DNS' once the EC2 was up and running, I couldnt add a public DNS
this is even after following the above steps making mods to the VPC or the Subnet
so, I had to make modifications to the subnet and the vpc, before starting another instance, and THEN start up a new instance.
the new instance had a public DNS. That is how it worked for me.
Just define your action method like this
public string ThemePath()
and simply return the string itself.
I am using Laravel 5.4 and response()->file('path/to/file.ext')
to open e.g. a pdf in inline-mode in browsers. This works quite well, but when a user wants to save the file, the save-dialog suggests the last part of the url as filename.
I already tried adding a headers-array like mentioned in the Laravel-docs, but this doesn't seem to override the header set by the file()-method:
return response()->file('path/to/file.ext', [
'Content-Disposition' => 'inline; filename="'. $fileNameFromDb .'"'
]);
Getting one char from string at specified index
Dim pos As Integer
Dim outStr As String
pos = 2
Dim outStr As String
outStr = Left(Mid("abcdef", pos), 1)
outStr="b"
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");
FileOutputStream f = new FileOutputStream(file);
...
The bootstrap 3 documentation lists this under helper classes:
Muted
, Primary
, Success
, Info
, Warning
, Danger
.
The bootstrap 4 documentation lists this under utilities -> color, and has more options:
primary
, secondary
, success
, danger
, warning
, info
, light
, dark
, muted
, white
.
To access them one uses the class
text-[class-name]
So, if I want the primary text color for example I would do something like this:
<p class="text-primary">This text is the primary color.</p>
This is not a huge number of choices, but it's some.
Hope here is the exact what we are looking for.
private void button2_Click(object sender, RoutedEventArgs e)
{
UpdateExcel("Sheet3", 4, 7, "Namachi@gmail");
}
private void UpdateExcel(string sheetName, int row, int col, string data)
{
Microsoft.Office.Interop.Excel.Application oXL = null;
Microsoft.Office.Interop.Excel._Workbook oWB = null;
Microsoft.Office.Interop.Excel._Worksheet oSheet = null;
try
{
oXL = new Microsoft.Office.Interop.Excel.Application();
oWB = oXL.Workbooks.Open("d:\\MyExcel.xlsx");
oSheet = String.IsNullOrEmpty(sheetName) ? (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet : (Microsoft.Office.Interop.Excel._Worksheet)oWB.Worksheets[sheetName];
oSheet.Cells[row, col] = data;
oWB.Save();
MessageBox.Show("Done!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
if (oWB != null)
oWB.Close();
}
}
I fixed it by changing Mach-O Type under linking section on the Build settings from Nothing to Executable.
One way of doing it is to use the ClientScriptManager
:
Page.ClientScript.RegisterStartupScript(
GetType(),
"MyKey",
"Myfunction();",
true);
The checkbox is in a td
, so need to get the parent first:
$("input:checkbox").on("change", function() {
$(this).parent().next().find("label").text("TESTTTT");
});
Alternatively, find a label which has a for
with the same id
(perhaps more performant than reverse traversal) :
$("input:checkbox").on("change", function() {
$("label[for='" + $(this).attr('id') + "']").text("TESTTTT");
});
Or, to be more succinct just this.id
:
$("input:checkbox").on("change", function() {
$("label[for='" + this.id + "']").text("TESTTTT");
});
I think this is what you want:
REGEX_DATE='^\d{2}[/-]\d{2}[/-]\d{4}$'
echo "$1" | grep -P -q $REGEX_DATE
echo $?
I've used the -P switch to get perl regex.
Another 1-liner but without preg:
$subject = 'bourbon, scotch, beer';
$search = ',';
$replace = ', and';
echo strrev(implode(strrev($replace), explode(strrev($search), strrev($subject), 2))); //output: bourbon, scotch, and beer
You mean like this?
class MyResourcePolicy : IResourcePolicy {
private string version;
public string Version {
get {
return this.version;
}
set {
this.version = value;
}
}
}
As of Java 7 (and Android API level 19):
System.lineSeparator()
Documentation: Java Platform SE 7
For older versions of Java, use:
System.getProperty("line.separator");
See https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html for other properties.
echo "<a href='#' style = \"font-color: #ff0000;\"> Movie List for {$key} 2013 </a>";
Try smallR for writing quick R scripts in the command line:
http://code.google.com/p/simple-r/
(r
command in the directory)
Plotting from the command line using smallR would look like this:
r -p file.txt
In the same vein as martineau's response, the best solution is often not to check. For example, the code
if x in d:
foo = d[x]
else:
foo = bar
is normally written
foo = d.get(x, bar)
which is shorter and more directly speaks to what you mean.
Another common case is something like
if x not in d:
d[x] = []
d[x].append(foo)
which can be rewritten
d.setdefault(x, []).append(foo)
or rewritten even better by using a collections.defaultdict(list)
for d
and writing
d[x].append(foo)
I would suggest you refactoring your code a little bit. When you have to start thinking about using reflection or other kind of stuff, for just testing your code, something is going wrong with your code.
You mentioned different types of problems. Let's start with private fields. In case of private fields I would have added a new constructor and injected fields into that. Instead of this:
public class ClassToTest {
private final String first = "first";
private final List<String> second = new ArrayList<>();
...
}
I'd have used this:
public class ClassToTest {
private final String first;
private final List<String> second;
public ClassToTest() {
this("first", new ArrayList<>());
}
public ClassToTest(final String first, final List<String> second) {
this.first = first;
this.second = second;
}
...
}
This won't be a problem even with some legacy code. Old code will be using an empty constructor, and if you ask me, refactored code will look cleaner, and you'll be able to inject necessary values in test without reflection.
Now about private methods. In my personal experience when you have to stub a private method for testing, then that method has nothing to do in that class. A common pattern, in that case, would be to wrap it within an interface, like Callable
and then you pass in that interface also in the constructor (with that multiple constructor trick):
public ClassToTest() {
this(...);
}
public ClassToTest(final Callable<T> privateMethodLogic) {
this.privateMethodLogic = privateMethodLogic;
}
Mostly all that I wrote looks like it's a dependency injection pattern. In my personal experience it's really useful while testing, and I think that this kind of code is cleaner and will be easier to maintain. I'd say the same about nested classes. If a nested class contains heavy logic it would be better if you'd moved it as a package private class and have injected it into a class needing it.
There are also several other design patterns which I have used while refactoring and maintaining legacy code, but it all depends on cases of your code to test. Using reflection mostly is not a problem, but when you have an enterprise application which is heavily tested and tests are run before every deployment everything gets really slow (it's just annoying and I don't like that kind of stuff).
There is also setter injection, but I wouldn't recommended using it. I'd better stick with a constructor and initialize everything when it's really necessary, leaving the possibility for injecting necessary dependencies.
You are not providing the correct address for the file. You need to provide an address such as C:/Users/xyz/Desktop/myfile.xml
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
Yes, that is supported.
Check the documentation provided here for the supported keywords inside method names.
You can just define the method in the repository interface without using the @Query annotation and writing your custom query. In your case it would be as followed:
List<Inventory> findByIdIn(List<Long> ids);
I assume that you have the Inventory entity and the InventoryRepository interface. The code in your case should look like this:
The Entity
@Entity
public class Inventory implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
// other fields
// getters/setters
}
The Repository
@Repository
@Transactional
public interface InventoryRepository extends PagingAndSortingRepository<Inventory, Long> {
List<Inventory> findByIdIn(List<Long> ids);
}
Instead of what you have written, you can write it directly in the SelectedIndexChanged event of the dropdownlist control, e.g.
protected void ddlleavetype_SelectedIndexChanged(object sender, EventArgs e)
{
//code goes here
}
This is behaviour of floating point arithmetic is by specification. Excerpt from the specification, § 15.17.2. Division Operator /:
Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.
public string ReplaceFirst(string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
here is an Extension Method that could also work as well per VoidKing
request
public static class StringExtensionMethods
{
public static string ReplaceFirst(this string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
}
Solved the problem by re-installing CUDA:
wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-ubuntu1804.pin
mv cuda-ubuntu1804.pin /etc/apt/preferences.d/cuda-repository-pin-600
wget https://developer.download.nvidia.com/compute/cuda/11.1.0/local_installers/cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb
echo "md5sum: $(md5sum cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb)"
echo "correct: 056de5e03444cce506202f50967b0016"
dpkg -i cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb
apt-key add /var/cuda-repo-ubuntu1804-11-1-local/7fa2af80.pub
apt-get -qq update
apt-get -qq -y install cuda
rm cuda-repo-ubuntu1804-11-1-local_11.1.0-455.23.05-1_amd64.deb
No, there's no literal syntax for the empty set. You have to write set()
.
All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.
The python equivalent of NULL
is called None
(good info here). As all objects in python are implemented via references, you can re-write your struct to look like this:
class Node:
def __init__(self): #object initializer to set attributes (fields)
self.val = 0
self.right = None
self.left = None
And then it works pretty much like you would expect:
node = Node()
node.val = some_val #always use . as everything is a reference and -> is not used
node.left = Node()
Note that unlike in NULL
in C, None
is not a "pointer to nowhere": it is actually the only instance of class NoneType
.
Therefore, as None
is a regular object, you can test for it just like any other object:
if node.left == None:
print("The left node is None/Null.")
Although since None
is a singleton instance, it is considered more idiomatic to use is
and compare for reference equality:
if node.left is None:
print("The left node is None/Null.")
Mootools redefines preventDefault in Event objects. So your code should work fine on every browser. If it doesn't, then there's a problem with ie8 support in mootools.
Did you test your code on ie6 and/or ie7?
The doc says
Every event added with addEvent gets the mootools method automatically, without the need to manually instance it.
but in case it doesn't, you might want to try
new Event(event).preventDefault();
String date="Sat Jun 01 12:53:10 IST 2013";
SimpleDateFormat sdf=new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
Date currentdate=sdf.parse(date);
SimpleDateFormat sdf2=new SimpleDateFormat("MMM dd,yyyy HH:mm:ss");
System.out.println(sdf2.format(currentdate));
You can try to upload it to google docs, and download it as HTML.
EDIT: See other answers for getting a list of tasks in the queue.
You should look here: Celery Guide - Inspecting Workers
Basically this:
from celery.app.control import Inspect
# Inspect all nodes.
i = Inspect()
# Show the items that have an ETA or are scheduled for later processing
i.scheduled()
# Show tasks that are currently active.
i.active()
# Show tasks that have been claimed by workers
i.reserved()
Depending on what you want
The lee answer is absolutely correct for iOS prior to 8.
In iOS 9+ you must whitelist any URL schemes your App wants to query in Info.plist under the LSApplicationQueriesSchemes key (an array of strings):
i Use this for the week start from SUNDAY:
SELECT id FROM tbl
WHERE
date >= curdate() - INTERVAL DAYOFWEEK(curdate())+5 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-2 DAY
It's a part of ISO-8601 date representation. It's incomplete because a complete date representation in this pattern should also contains the date:
2015-03-04T00:00:00.000Z //Complete ISO-8601 date
If you try to parse this date as it is you will receive an Invalid Date
error:
new Date('T00:00:00.000Z'); // Invalid Date
So, I guess the way to parse a timestamp in this format is to concat with any date
new Date('2015-03-04T00:00:00.000Z'); // Valid Date
Then you can extract only the part you want (timestamp part)
var d = new Date('2015-03-04T00:00:00.000Z');
console.log(d.getUTCHours()); // Hours
console.log(d.getUTCMinutes());
console.log(d.getUTCSeconds());
$dbc
is returning false. Your query has an error in it:
SELECT users.*, profile.* --You do not join with profile anywhere.
FROM users
INNER JOIN contact_info
ON contact_info.user_id = users.user_id
WHERE users.user_id=3");
The fix for this in general has been described by Raveren.
Actually if you need to test background fetch you need to enable one option in scheme:
Another way how you can test it:
Here is full information about this new feature: http://www.objc.io/issue-5/multitasking.html
Update for everybody coming to check why tensorflow.keras
is not visible in PyCharm
.
Starting from TensorFlow 2.0, only PyCharm versions > 2019.3 are able to recognise tensorflow
and keras
inside tensorflow (tensorflow.keras
) properly.
Also, it is recommended(by Francois Chollet) that everybody switches to tensorflow.keras
in place of plain keras
.
For visual c# console Application use:
Console.ReadLine();
Console.Read();
Console.ReadKey(true);
for visual c++ win32 console application use:
system("pause");
press ctrl+f5 to run the application.
Starting with Android 8.1 (API 27), apps must be granted the ACCESS_COARSE_LOCATION
(or ACCESS_FINE_LOCATION
) permission in order to obtain results from WifiInfo.getSSID()
or WifiInfo.getBSSID()
. Apps that target API 29 or higher (Android 10) must be granted ACCESS_FINE_LOCATION
.
This permission is also needed to obtain results from WifiManager.getConnectionInfo()
and WifiManager.getScanResults()
although it is not clear if this is new in 8.1 or was required previously.
Source: "BSSID/SSID can be used to deduce location, so require the same location permissions for access to these WifiInfo fields requested using WifiManager.getConnectionInfo() as for WifiManager.getScanResults()."
The usage of -->
has historical relevance. Decrementing was (and still is in some cases), faster than incrementing on the x86 architecture. Using -->
suggests that x
is going to 0
, and appeals to those with mathematical backgrounds.
When the return type is void, your method doesn't return anything.
Look again at your code: There's no return in that method. You print to the console and exit.
bool _visible = false;
void _toggle() {
setState(() {
_visible = !_visible;
});
}
onPressed: _toggle,
Visibility(
visible:_visible,
child: new Container(
child: new Container(
padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 10.0),
child: new Material(
elevation: 10.0,
borderRadius: BorderRadius.circular(25.0),
child: new ListTile(
leading: new Icon(Icons.search),
title: new TextField(
controller: controller,
decoration: new InputDecoration(
hintText: 'Search for brands and products', border: InputBorder.none,),
onChanged: onSearchTextChanged,
),
trailing: new IconButton(icon: new Icon(Icons.cancel), onPressed: () {
controller.clear();
onSearchTextChanged('');
},),
),
),
),
),
),
Not sure why the above explanations are so complicated when you have native methods available:
main_list = list(set(list_2)-set(list_1))
To check for assignability, you can use the Type.IsAssignableFrom
method:
typeof(SomeType).IsAssignableFrom(typeof(Derived))
This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.
To check for strict inheritance, you can use Type.IsSubclassOf
:
typeof(Derived).IsSubclassOf(typeof(SomeType))
In the following line.
temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();
You are calling First but the collection returned from db.Responses.Where is empty.
Having the following blog
database table storing the blogs hosted by our platform:
And, we have two blogs currently hosted:
id | created_on | title | url |
---|---|---|---|
1 | 2013-09-30 | Vlad Mihalcea's Blog | https://vladmihalcea.com |
2 | 2017-01-22 | Hypersistence | https://hypersistence.io |
We need to build a report that extracts the following data from the blog
table:
If you're using PostgreSQL, then you have to execute the following SQL query:
SELECT
b.id as blog_id,
extract(
YEAR FROM age(now(), b.created_on)
) AS age_in_years,
date(
created_on + (
extract(YEAR FROM age(now(), b.created_on)) + 1
) * interval '1 year'
) AS next_anniversary,
date(
created_on + (
extract(YEAR FROM age(now(), b.created_on)) + 1
) * interval '1 year'
) - date(now()) AS days_to_next_anniversary
FROM blog b
ORDER BY blog_id
As you can see, the age_in_years
has to be defined three times because you need it when calculating the next_anniversary
and days_to_next_anniversary
values.
And, that's exactly where LATERAL JOIN can help us.
The following relational database systems support the LATERAL JOIN
syntax:
SQL Server can emulate the LATERAL JOIN
using CROSS APPLY
and OUTER APPLY
.
LATERAL JOIN allows us to reuse the age_in_years
value and just pass it further when calculating the next_anniversary
and days_to_next_anniversary
values.
The previous query can be rewritten to use the LATERAL JOIN, as follows:
SELECT
b.id as blog_id,
age_in_years,
date(
created_on + (age_in_years + 1) * interval '1 year'
) AS next_anniversary,
date(
created_on + (age_in_years + 1) * interval '1 year'
) - date(now()) AS days_to_next_anniversary
FROM blog b
CROSS JOIN LATERAL (
SELECT
cast(
extract(YEAR FROM age(now(), b.created_on)) AS int
) AS age_in_years
) AS t
ORDER BY blog_id
And, the age_in_years
value can be calculated one and reused for the next_anniversary
and days_to_next_anniversary
computations:
blog_id | age_in_years | next_anniversary | days_to_next_anniversary |
---|---|---|---|
1 | 7 | 2021-09-30 | 295 |
2 | 3 | 2021-01-22 | 44 |
Much better, right?
The age_in_years
is calculated for every record of the blog
table. So, it works like a correlated subquery, but the subquery records are joined with the primary table and, for this reason, we can reference the columns produced by the subquery.
A)
Object* o;
o = new Object();
`` B)
Object* o = new Object();
I think A and B has no difference. In both the cases o is a pointer to class Object. statement new Object() creates an object of class Object from heap memory. Assignment statement assigns the address of allocated memory to pointer o.
One thing I would like to mention that size of allocated memory from heap is always the sizeof(Object) not sizeof(Object) + sizeof(void *).
It is much better to use
$value = mb_convert_encode($value,'HTML-ENTITIES','UTF-8');
Specially when you are using AJAX call for submitting 'ISO-8859-1' characters. It works for Chinese, Japanese, Czech, German and many more languages.
Try to use:
location.reload(true);
When this method receives a true
value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.
More info:
Basically http.antMatcher()
tells Spring to only configure HttpSecurity
if the path matches this pattern.
I believe running from Eclipse, if you're using "myconf.properties" as the relative path, You file structure should look somehting like this
ProjectRoot
src
bin
myconf.properties
Eclipse will look for the the file in the project root dir if no other dirs are specified in the file path
The definition of SIZE_T
is found at:
https://msdn.microsoft.com/en-us/library/cc441980.aspx and https://msdn.microsoft.com/en-us/library/cc230394.aspx
Pasting here the required information:
SIZE_T
is a ULONG_PTR
representing the maximum number of bytes to which a pointer can point.
This type is declared as follows:
typedef ULONG_PTR SIZE_T;
A ULONG_PTR
is an unsigned long type used for pointer precision. It is used when casting a pointer to a long type to perform pointer arithmetic.
This type is declared as follows:
typedef unsigned __int3264 ULONG_PTR;
Do you have ROWS of data (horizontal) as you stated or COLUMNS (vertical)?
If it's the latter you can use "Text to columns" functionality to convert a whole column "in situ" - to do that:
Select column > Data > Text to columns > Next > Next > Choose "Date" under "column data format" and "YMD" from dropdown > Finish
....otherwise you can convert with a formula by using
=TEXT(A1,"0000-00-00")+0
and format in required date format
Use case match for early return purpose. It will force you to declare all return branches explicitly, preventing the careless mistake of forgetting to write return somewhere.
Use jquery-dateFormat. It will solve your problem.
You need to include the jquery.dateFormat in your html file.
<script>
var date = $('#scheduleDate').val();
document.write($.format.date(date, "dd,MM,yyyy"));
var dateTypeVar = $('#scheduleDate').datepicker('getDate');
document.write($.format.date(dateTypeVar, "dd-MM-yy"));
</script>
In my case the issue was due to incorrect build order. One project had an xcopy command on post-build events to copy files from bin folder to another folder. But because of incorrect dependencies new files were getting created in bin folder while xcopy is in progress.
In VS right click on the project where you have post-build events. Go to Build Dependencies > Project Dependencies and make sure its correct. Verify the project build order(next tab to dependencies) as well.
this
is the DOM element on which the event was hooked. this.id
is its ID. No need to wrap it in a jQuery instance to get it, the id
property reflects the attribute reliably on all browsers.
$("select").change(function() {
alert("Changed: " + this.id);
}
You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event
object's target
property:
$("#container").change(function(event) {
alert("Field " + event.target.id + " changed");
});
(jQuery ensures that the change
event bubbles, even on IE where it doesn't natively.)
We are running Linux, a mostly POSIX-compliant OS. POSIX standards it should be: Utility Argument Syntax.
-o
. -o argument
or
-oargument
. -lst
is equivalent to -t -l -s
.-lst
is equivalent to -tls
.-lst
nonoption.--
argument terminates options.-
option is typically used to represent one of the standard input
streams.This might work a little better this way
<embed src= "MyHome.pdf" width= "500" height= "375">
You can use verbatim literals:
const string test = @"Test
123
456
";
But the indentation of the 1st line is tricky/ugly.
Alternative syntax using the -Not
operator and depending on your preference for readability:
if( -Not (Test-Path -Path $TARGETDIR ) )
{
New-Item -ItemType directory -Path $TARGETDIR
}
Provide the directory on the command line:
svn checkout file:///home/landonwinters/svn/waterproject/trunk public_html
You should be using the json
module. json.dumps(string)
. It can also serialize other python data types.
import json
>>> s = 'my string with "double quotes" blablabla'
>>> json.dumps(s)
<<< '"my string with \\"double quotes\\" blablabla"'
Received SQLSTATE 01000 in the following error message below:
SQL Agent - Jobs Failed: The SQL Agent Job "LiteSpeed Backup Full" has failed with the message "The job failed. The Job was invoked by User X. The last step to run was step 1 (Step1). NOTE: Failed to notify via email. - Executed as user: X. LiteSpeed(R) for SQL Server Version 6.5.0.1460 Copyright 2011 Quest Software, Inc. [SQLSTATE 01000] (Message 1) LiteSpeed for SQL Server could not open backup file: (N:\BACKUP2\filename.BAK). The previous system message is the reason for the failure. [SQLSTATE 42000] (Error 60405). The step failed."
In my case this was related to permission on drive N following an SQL Server failover on an Active/Passive SQL cluster.
All SQL resources where failed over to the seconary resouce and back to the preferred node following maintenance. When the Quest LiteSpeed job then executed on the preferred node it was clear the previous permissions for SQL server user X had been lost on drive N and SQLSTATE 10100 was reported.
Simply added the permissions again to the backup destination drive and the issue was resolved.
Hope that helps someone.
Windows 2008 Enterprise
SQL Server 2008 Active/Passive cluster.
This is what I did:
/* open database, if doesn't exist, create it */
SQLiteDatabase mDatabase = openOrCreateDatabase("exampleDb.db", SQLiteDatabase.CREATE_IF_NECESSARY,null);
Cursor c = null;
boolean tableExists = false;
/* get cursor on it */
try
{
c = mDatabase.query("tbl_example", null,
null, null, null, null, null);
tableExists = true;
}
catch (Exception e) {
/* fail */
Log.d(TAG, tblNameIn+" doesn't exist :(((");
}
return tableExists;
The reason I used a +
instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.
word[Aa]\s+word[Bb]\s+word[Cc]
will match:
wordA wordB wordC
worda wordb wordc
wordA wordb wordC
The words, in this expression, will have to be specific, and also in order (a, b, then c)
Sept 2018
For anyone checking this question recently, Rails 5.2+ now has ActiveStorage by default & I highly recommend checking it out.
Since it is part of the core Rails 5.2+ now, it is very well integrated & has excellent capabilities out of the box (still all other well-known gems like Carrierwave, Shrine, paperclip,... are great but this one offers very good features that we can consider for any new Rails project)
Paperclip team deprecated the gem in favor of the Rails ActiveStorage.
Here is the github page for the ActiveStorage & plenty of resources are available everywhere
Also I found this video to be very helpful to understand the features of Activestorage
sed
is the stream editor, in that you can use |
(pipe) to send standard streams (STDIN and STDOUT specifically) through sed
and alter them programmatically on the fly, making it a handy tool in the Unix philosophy tradition; but can edit files directly, too, using the -i
parameter mentioned below.
Consider the following:
sed -i -e 's/few/asd/g' hello.txt
s/
is used to substitute the found expression few
with asd
:
The few, the brave.
The asd, the brave.
/g
stands for "global", meaning to do this for the whole line. If you leave off the /g
(with s/few/asd/
, there always needs to be three slashes no matter what) and few
appears twice on the same line, only the first few
is changed to asd
:
The few men, the few women, the brave.
The asd men, the few women, the brave.
This is useful in some circumstances, like altering special characters at the beginnings of lines (for instance, replacing the greater-than symbols some people use to quote previous material in email threads with a horizontal tab while leaving a quoted algebraic inequality later in the line untouched), but in your example where you specify that anywhere few
occurs it should be replaced, make sure you have that /g
.
The following two options (flags) are combined into one, -ie
:
-i
option is used to edit in place on the file hello.txt
.
-e
option indicates the expression/command to run, in this case s/
.
Note: It's important that you use -i -e
to search/replace. If you do -ie
, you create a backup of every file with the letter 'e' appended.
To temporarily set an environment variable without having to copy the os.envrion object etc, I do this:
process = subprocess.Popen(['env', 'RSYNC_PASSWORD=foobar', 'rsync', \
'rsync://[email protected]::'], stdout=subprocess.PIPE)
You can try this as well, which is really a combination of previous answers from other posters here :
let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "RubberMat")
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage, at: 0)
In Ubuntu, you can install libtool
which resolves the libraries automatically.
$ sudo apt-get install libtool
This resolved a problem with ltdl
for me, which had been installed as libltdl.so.7
and wasn't found as simply -lltdl
in the make.
psoul's excellent post answers to your question so I won't replicate his good work, but I feel it'd help to explain why this is at once a perfectly valid but also terribly silly question. After all, this is a place to learn, right?
Modern computer programs are produced through a series of conversions, starting with the input of a human-readable body of text instructions (called "source code") and ending with a computer-readable body of instructions (called alternatively "binary" or "machine code").
The way that a computer runs a set of machine code instructions is ultimately very simple. Each action a processor can take (e.g., read from memory, add two values) is represented by a numeric code. If I told you that the number 1 meant scream and the number 2 meant giggle, and then held up cards with either 1 or 2 on them expecting you to scream or giggle accordingly, I would be using what is essentially the same system a computer uses to operate.
A binary file is just a set of those codes (usually call "op codes") and the information ("arguments") that the op codes act on.
Now, assembly language is a computer language where each command word in the language represents exactly one op-code on the processor. There is a direct 1:1 translation between an assembly language command and a processor op-code. This is why coding assembly for an x386 processor is different than coding assembly for an ARM processor.
Disassembly is simply this: a program reads through the binary (the machine code), replacing the op-codes with their equivalent assembly language commands, and outputs the result as a text file. It's important to understand this; if your computer can read the binary, then you can read the binary too, either manually with an op-code table in your hand (ick) or through a disassembler.
Disassemblers have some new tricks and all, but it's important to understand that a disassembler is ultimately a search and replace mechanism. Which is why any EULA which forbids it is ultimately blowing hot air. You can't at once permit the computer reading the program data and also forbid the computer reading the program data.
(Don't get me wrong, there have been attempts to do so. They work as well as DRM on song files.)
However, there are caveats to the disassembly approach. Variable names are non-existent; such a thing doesn't exist to your CPU. Library calls are confusing as hell and often require disassembling further binaries. And assembly is hard as hell to read in the best of conditions.
Most professional programmers can't sit and read assembly language without getting a headache. For an amateur it's just not going to happen.
Anyway, this is a somewhat glossed-over explanation, but I hope it helps. Everyone can feel free to correct any misstatements on my part; it's been a while. ;)
Using aggregate
:
aggregate(x$Frequency, by=list(Category=x$Category), FUN=sum)
Category x
1 First 30
2 Second 5
3 Third 34
In the example above, multiple dimensions can be specified in the list
. Multiple aggregated metrics of the same data type can be incorporated via cbind
:
aggregate(cbind(x$Frequency, x$Metric2, x$Metric3) ...
(embedding @thelatemail comment), aggregate
has a formula interface too
aggregate(Frequency ~ Category, x, sum)
Or if you want to aggregate multiple columns, you could use the .
notation (works for one column too)
aggregate(. ~ Category, x, sum)
or tapply
:
tapply(x$Frequency, x$Category, FUN=sum)
First Second Third
30 5 34
Using this data:
x <- data.frame(Category=factor(c("First", "First", "First", "Second",
"Third", "Third", "Second")),
Frequency=c(10,15,5,2,14,20,3))
If you want window handles for ALL of your application's Window
s for some reason, you can use the Application.Windows
property to get at all the Windows and then use WindowInteropHandler
to get at their handles as you have already demonstrated.
You fiddle already does the job ... maybe you try to get the string before the double colon? (you really should edit your question) Then the code would go like this:
str.substring(0, str.indexOf(":"));
Where 'str' represents the variable with your string inside.
Click here for JSFiddle Example
Javascript
var input_string = document.getElementById('my-input').innerText;
var output_element = document.getElementById('my-output');
var left_text = input_string.substring(0, input_string.indexOf(":"));
output_element.innerText = left_text;
Html
<p>
<h5>Input:</h5>
<strong id="my-input">Left Text:Right Text</strong>
<h5>Output:</h5>
<strong id="my-output">XXX</strong>
</p>
CSS
body { font-family: Calibri, sans-serif; color:#555; }
h5 { margin-bottom: 0.8em; }
strong {
width:90%;
padding: 0.5em 1em;
background-color: cyan;
}
#my-output { background-color: gold; }
Ubuntu 14 and lower does not have "systemctl
" Source: https://docs.docker.com/install/linux/linux-postinstall/#configure-docker-to-start-on-boot
Configure Docker to start on boot:
Most current Linux distributions (RHEL, CentOS, Fedora, Ubuntu 16.04 and higher) use systemd to manage which services start when the system boots. Ubuntu 14.10 and below use upstart.
1) systemd (Ubuntu 16 and above):
$ sudo systemctl enable docker
To disable this behavior, use disable instead.
$ sudo systemctl disable docker
2) upstart (Ubuntu 14 and below):
Docker is automatically configured to start on boot using upstart. To disable this behavior, use the following command:
$ echo manual | sudo tee /etc/init/docker.override
chkconfig
$ sudo chkconfig docker on
Done.
(Alt + Shift + X) , then M
to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations
to check if a date is today's date or not only check for dates not time included with that so make time 00:00:00 and use the code below
Calendar c = Calendar.getInstance();
// set the calendar to start of today
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
Date today = c.getTime();
// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();
int dayOfMonth = 24;
int month = 4;
int year =2013;
// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month - 1);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
// and get that as a Date
Date dateSpecified = c.getTime();
// test your condition
if (dateSpecified.before(today)) {
Log.v(" date is previou")
} else if (dateSpecified.equal(today)) {
Log.v(" date is today ")
}
else if (dateSpecified.after(today)) {
Log.v(" date is future date ")
}
Hope it will help....
The title of the question asks about precision. BigDecimal distinguishes between scale and precision. Scale is the number of decimal places. You can think of precision as the number of significant figures, also known as significant digits.
Some examples in Clojure.
(.scale 0.00123M) ; 5
(.precision 0.00123M) ; 3
(In Clojure, The M
designates a BigDecimal literal. You can translate the Clojure to Java if you like, but I find it to be more compact than Java!)
You can easily increase the scale:
(.setScale 0.00123M 7) ; 0.0012300M
But you can't decrease the scale in the exact same way:
(.setScale 0.00123M 3) ; ArithmeticException Rounding necessary
You'll need to pass a rounding mode too:
(.setScale 0.00123M 3 BigDecimal/ROUND_HALF_EVEN) ;
; Note: BigDecimal would prefer that you use the MathContext rounding
; constants, but I don't have them at my fingertips right now.
So, it is easy to change the scale. But what about precision? This is not as easy as you might hope!
It is easy to decrease the precision:
(.round 3.14159M (java.math.MathContext. 3)) ; 3.14M
But it is not obvious how to increase the precision:
(.round 3.14159M (java.math.MathContext. 7)) ; 3.14159M (unexpected)
For the skeptical, this is not just a matter of trailing zeros not being displayed:
(.precision (.round 3.14159M (java.math.MathContext. 7))) ; 6
; (same as above, still unexpected)
FWIW, Clojure is careful with trailing zeros and will show them:
4.0000M ; 4.0000M
(.precision 4.0000M) ; 5
Back on track... You can try using a BigDecimal constructor, but it does not set the precision any higher than the number of digits you specify:
(BigDecimal. "3" (java.math.MathContext. 5)) ; 3M
(BigDecimal. "3.1" (java.math.MathContext. 5)) ; 3.1M
So, there is no quick way to change the precision. I've spent time fighting this while writing up this question and with a project I'm working on. I consider this, at best, A CRAZYTOWN API, and at worst a bug. People. Seriously?
So, best I can tell, if you want to change precision, you'll need to do these steps:
These steps, as Clojure code:
(def x 0.000691M) ; the input number
(def p' 1) ; desired precision
(def s' (+ (.scale x) p' (- (.precision x)))) ; desired new scale
(.setScale x s' BigDecimal/ROUND_HALF_EVEN)
; 0.0007M
I know, this is a lot of steps just to change the precision!
Why doesn't BigDecimal already provide this? Did I overlook something?
This is slightly an edge case but I think it can add some value to the other answers.
If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.
For instance the following script:
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line
Will give you this figure, which is wrong:
While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);
# do potentially more stuff here
h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)
This is what you'll get:
<div class="content scrollable" ref="msgContainer">
<!-- content -->
</div>
data() {
return {
count: 5
};
},
watch: {
count: function() {
this.$nextTick(function() {
var container = this.$refs.msgContainer;
container.scrollTop = container.scrollHeight + 120;
});
}
}
.scrollable {
overflow: hidden;
overflow-y: scroll;
height: calc(100vh - 20px);
}
Until [character] (t
). It is useful for any command which accepts a range. My favorite is ct;
or ct)
which deletes everything up to the trailing semicolon / closing parentheses and then places you in insert mode.
Also, G
and gg
are useful (Go to bottom and top respectively).
Try running task manager to determine if your program is still running.
If it is running then stop it and run it again. the [Error] ld returned 1 exit status will not come back
Here's a solution to managed your "distinct" issue, which is entirely overblown:
Create a unit sphere and drop points on it with repelling charges. Run a particle system until they no longer move (or the delta is "small enough"). At this point, each of the points are as far away from each other as possible. Convert (x, y, z) to rgb.
I mention it because for certain classes of problems, this type of solution can work better than brute force.
I originally saw this approach here for tesselating a sphere.
Again, the most obvious solutions of traversing HSL space or RGB space will probably work just fine.
Sometimes it is possible to solve it in the model like this: Suppose you have 3 boolean properties OptionA, OptionB, OptionC.
XAML:
<RadioButton IsChecked="{Binding OptionA}"/>
<RadioButton IsChecked="{Binding OptionB}"/>
<RadioButton IsChecked="{Binding OptionC}"/>
CODE:
private bool _optionA;
public bool OptionA
{
get { return _optionA; }
set
{
_optionA = value;
if( _optionA )
{
this.OptionB= false;
this.OptionC = false;
}
}
}
private bool _optionB;
public bool OptionB
{
get { return _optionB; }
set
{
_optionB = value;
if( _optionB )
{
this.OptionA= false;
this.OptionC = false;
}
}
}
private bool _optionC;
public bool OptionC
{
get { return _optionC; }
set
{
_optionC = value;
if( _optionC )
{
this.OptionA= false;
this.OptionB = false;
}
}
}
You get the idea. Not the cleanest thing, but easy.
The major difference between Page_Load
and Page_PreRender
is that in the Page_Load method not all of your page controls are completely initialized (loaded), because individual controls Load()
methods has not been called yet. This means that tree is not ready for rendering yet. In Page_PreRender
you guaranteed that all page controls are loaded and ready for rendering. Technically Page_PreRender
is your last chance to tweak the page before it turns into HTML stream.
If you don't know the type/origin of the error, you can try:
import sys
try:
doSomethingWrongHere()
except:
print('Error: {}'.format(sys.exc_info()[0]))
But be aware, you'll get pep8 warning:
[W] PEP 8 (E722): do not use bare except
var empty = $("#cartContent").html().trim().length == 0;
SQL Row_Number() function is to sort and assign an order number to data rows in related record set. So it is used to number rows, for example to identify the top 10 rows which have the highest order amount or identify the order of each customer which is the highest amount, etc.
If you want to sort the dataset and number each row by seperating them into categories we use Row_Number() with Partition By clause. For example, sorting orders of each customer within itself where the dataset contains all orders, etc.
SELECT
SalesOrderNumber,
CustomerId,
SubTotal,
ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY SubTotal DESC) rn
FROM Sales.SalesOrderHeader
But as I understand you want to calculate the number of rows of grouped by a column. To visualize the requirement, if you want to see the count of all orders of the related customer as a seperate column besides order info, you can use COUNT() aggregation function with Partition By clause
For example,
SELECT
SalesOrderNumber,
CustomerId,
COUNT(*) OVER (PARTITION BY CustomerId) CustomerOrderCount
FROM Sales.SalesOrderHeader
$(".phoneString").text(function(i, text) {
text = text.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
return text;
});
Output :-(123) 657-8963
Joseph's answer pointed out ISNUMERIC also handles scientific notation like '1.3e+3' but his answer doesn't handle this format of number.
Casting to a money or float first handles both the currency and scientific issues:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TryConvertInt]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[TryConvertInt]
GO
CREATE FUNCTION dbo.TryConvertInt(@Value varchar(18))
RETURNS bigint
AS
BEGIN
DECLARE @IntValue bigint;
IF (ISNUMERIC(@Value) = 1)
IF (@Value like '%e%')
SET @IntValue = CAST(Cast(@Value as float) as bigint);
ELSE
SET @IntValue = CAST(CAST(@Value as money) as bigint);
ELSE
SET @IntValue = NULL;
RETURN @IntValue;
END
The function will fail if the number is bigger than a bigint.
If you want to return a different default value, leave this function so it is generic and replace the null afterwards:
SELECT IsNull(dbo.TryConvertInt('nan') , 1000);
Right Click On Project -> Open Module Settings -> Click SDK's
Choose Java Home Directory
Write this is the activity you are in:
Intent intent = new Intent(CurrentActivity.this,NextActivity.class);
intent.putExtras("string_name","string_to_pass");
startActivity(intent);
In the NextActivity.java
Intent getIntent = getIntent();
//call a TextView object to set the string to
TextView text = (TextView)findViewById(R.id.textview_id);
text.setText(getIntent.getStringExtra("string_name"));
This works for me, you can try it.
If you use shared modules, just add RouterModule to a Module where your component is declared and don't forget to add <router-outlet></router-outlet>
Referenced from here RouterLink does not work
Install PIL(Python Image Library) :
then:
from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();
only the below code in Python 3.7 worked for me
from datetime import datetime,timedelta
print(datetime.now()-timedelta(seconds=900))
If you really need multiple columns in your result, and the amount of options is limited, you can even do this:
select
ordered_item.id as `Id`,
ordered_item.Item_Name as `ItemName`,
if(ordered_options.id=1,Ordered_Options.Value,null) as `Option1`,
if(ordered_options.id=2,Ordered_Options.Value,null) as `Option2`,
if(ordered_options.id=43,Ordered_Options.Value,null) as `Option43`,
if(ordered_options.id=44,Ordered_Options.Value,null) as `Option44`,
GROUP_CONCAT(if(ordered_options.id not in (1,2,43,44),Ordered_Options.Value,null)) as `OtherOptions`
from
ordered_item,
ordered_options
where
ordered_item.id=ordered_options.ordered_item_id
group by
ordered_item.id
Here is an example Which can help you better to understand how to pass a function as a parameter.
Suppose you have Parent page and you want to open a child popup window. In the parent page there is a textbox that should be filled basing on child popup textbox.
Here you need to create a delegate.
Parent.cs // declaration of delegates public delegate void FillName(String FirstName);
Now create a function which will fill your textbox and function should map delegates
//parameters
public void Getname(String ThisName)
{
txtname.Text=ThisName;
}
Now on button click you need to open a Child popup window.
private void button1_Click(object sender, RoutedEventArgs e)
{
ChildPopUp p = new ChildPopUp (Getname) //pass function name in its constructor
p.Show();
}
IN ChildPopUp constructor you need to create parameter of 'delegate type' of parent //page
ChildPopUp.cs
public Parent.FillName obj;
public PopUp(Parent.FillName objTMP)//parameter as deligate type
{
obj = objTMP;
InitializeComponent();
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
obj(txtFirstName.Text);
// Getname() function will call automatically here
this.DialogResult = true;
}
Having a lookup table with a bazillion replace() calls is slow and not maintainable.
Fortunately, the build-in escape() function also encodes most of the same characters, and puts them in a consistent format (%XX, where XX is the hex value of the character).
So, you can let escape() method do most of the work for you and just change its answer to be HTML entities instead of URL-escaped characters:
htmlescaped = escape(mystring).replace(/%(..)/g,"&#x$1;");
This uses the hex format for escaping values rather than the named entities, but for storing and displaying the values, it works just as well as named entities.
Of course, escape also escapes characters you don't need to escape in HTML (spaces, for instance), but you can unescape them with a few replace calls.
Edit: I like bucabay's answer better than my own... handles a larger range of characters, and requires no hacking afterward to get spaces, slashes, etc. unescaped.
If using win7 64 bit OS:
After installing the latest JDK make sure you copy the jre folder from the install location {C:\Program Files\Java\jdk1.7.0_40
} directly to your eclipse folder as even pathing it apparently does nothing on win7.
Mad
edit:
Actual jdk version number on folder name will vary as newer versions are released
For the sake of completeness of this popular question, since version 1.0.0 of dplyr
, parameter .groups controls the grouping structure of the summarise
function after group_by
summarise help.
With .groups = "drop_last"
, summarise
drops the last level of grouping. This was the only result obtained before version 1.0.0.
library(dplyr)
library(scales)
original <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n()) %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
#> `summarise()` regrouping output by 'am' (override with `.groups` argument)
original
#> # A tibble: 4 x 4
#> # Groups: am [2]
#> am gear n rel.freq
#> <dbl> <dbl> <int> <chr>
#> 1 0 3 15 78.9%
#> 2 0 4 4 21.1%
#> 3 1 4 8 61.5%
#> 4 1 5 5 38.5%
new_drop_last <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n(), .groups = "drop_last") %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
dplyr::all_equal(original, new_drop_last)
#> [1] TRUE
With .groups = "drop"
, all levels of grouping are dropped. The result is turned into an independent tibble with no trace of the previous group_by
# .groups = "drop"
new_drop <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n(), .groups = "drop") %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
new_drop
#> # A tibble: 4 x 4
#> am gear n rel.freq
#> <dbl> <dbl> <int> <chr>
#> 1 0 3 15 46.9%
#> 2 0 4 4 12.5%
#> 3 1 4 8 25.0%
#> 4 1 5 5 15.6%
If .groups = "keep"
, same grouping structure as .data (mtcars, in this case). summarise
does not peel off any variable used in the group_by
.
Finally, with .groups = "rowwise"
, each row is it's own group. It is equivalent to "keep" in this situation
# .groups = "keep"
new_keep <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n(), .groups = "keep") %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
new_keep
#> # A tibble: 4 x 4
#> # Groups: am, gear [4]
#> am gear n rel.freq
#> <dbl> <dbl> <int> <chr>
#> 1 0 3 15 100.0%
#> 2 0 4 4 100.0%
#> 3 1 4 8 100.0%
#> 4 1 5 5 100.0%
# .groups = "rowwise"
new_rowwise <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n(), .groups = "rowwise") %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
dplyr::all_equal(new_keep, new_rowwise)
#> [1] TRUE
Another point that can be of interest is that sometimes, after applying group_by
and summarise
, a summary line can help.
# create a subtotal line to help readability
subtotal_am <- mtcars %>%
group_by (am) %>%
summarise (n=n()) %>%
mutate(gear = NA, rel.freq = 1)
#> `summarise()` ungrouping output (override with `.groups` argument)
mtcars %>% group_by (am, gear) %>%
summarise (n=n()) %>%
mutate(rel.freq = n/sum(n)) %>%
bind_rows(subtotal_am) %>%
arrange(am, gear) %>%
mutate(rel.freq = scales::percent(rel.freq, accuracy = 0.1))
#> `summarise()` regrouping output by 'am' (override with `.groups` argument)
#> # A tibble: 6 x 4
#> # Groups: am [2]
#> am gear n rel.freq
#> <dbl> <dbl> <int> <chr>
#> 1 0 3 15 78.9%
#> 2 0 4 4 21.1%
#> 3 0 NA 19 100.0%
#> 4 1 4 8 61.5%
#> 5 1 5 5 38.5%
#> 6 1 NA 13 100.0%
Created on 2020-11-09 by the reprex package (v0.3.0)
Hope you find this answer useful.
public static void reverseString(String s){
System.out.println("---------");
for(int i=s.length()-1; i>=0;i--){
System.out.print(s.charAt(i));
}
System.out.println();
}
In my case my column was a datetime it kept giving me all records. What I did is to include time, see below example
SELECT * FROM my_table where start_date > '2011-01-01 01:01:01';
Moving tables:
First run:
SELECT 'ALTER TABLE <schema_name>.' || OBJECT_NAME ||' MOVE TABLESPACE '||' <tablespace_name>; '
FROM ALL_OBJECTS
WHERE OWNER = '<schema_name>'
AND OBJECT_TYPE = 'TABLE' <> '<TABLESPACE_NAME>';
-- Or suggested in the comments (did not test it myself)
SELECT 'ALTER TABLE <SCHEMA>.' || TABLE_NAME ||' MOVE TABLESPACE '||' TABLESPACE_NAME>; '
FROM dba_tables
WHERE OWNER = '<SCHEMA>'
AND TABLESPACE_NAME <> '<TABLESPACE_NAME>
Where <schema_name>
is the name of the user.
And <tablespace_name>
is the destination tablespace.
As a result you get lines like:
ALTER TABLE SCOT.PARTS MOVE TABLESPACE USERS;
Paste the results in a script or in a oracle sql developer like application and run it.
Moving indexes:
First run:
SELECT 'ALTER INDEX <schema_name>.'||INDEX_NAME||' REBUILD TABLESPACE <tablespace_name>;'
FROM ALL_INDEXES
WHERE OWNER = '<schema_name>'
AND TABLESPACE_NAME NOT LIKE '<tablespace_name>';
The last line in this code could save you a lot of time because it filters out the indexes which are already in the correct tablespace.
As a result you should get something like:
ALTER INDEX SCOT.PARTS_NO_PK REBUILD TABLESPACE USERS;
Paste the results in a script or in a oracle sql developer like application and run it.
Last but not least, moving LOBs:
First run:
SELECT 'ALTER TABLE <schema_name>.'||LOWER(TABLE_NAME)||' MOVE LOB('||LOWER(COLUMN_NAME)||') STORE AS (TABLESPACE <table_space>);'
FROM DBA_TAB_COLS
WHERE OWNER = '<schema_name>' AND DATA_TYPE like '%LOB%';
This moves the LOB objects to the other tablespace.
As a result you should get something like:
ALTER TABLE SCOT.bin$6t926o3phqjgqkjabaetqg==$0 MOVE LOB(calendar) STORE AS (TABLESPACE USERS);
Paste the results in a script or in a oracle sql developer like application and run it.
O and there is one more thing:
For some reason I wasn't able to move 'DOMAIN' type indexes. As a work around I dropped the index. changed the default tablespace of the user into de desired tablespace. and then recreate the index again. There is propably a better way but it worked for me.
Use a grep
analog to find the strings oldnamespace
and Jenine
inside the files in your whole project folder. Then you'd know what step to do next.
You can use a shortcut. Create a .bashrc file in your home directory. In there, you can add the following:
alias sshb="ssh buck@host"
To make the alias available in your terminal, you can either close and open your terminal, or run
source ~/.bashrc
Then you can connect by just typing in:
sshb
The const
keyword is in the ECMAScript 6 draft but it thus far only enjoys a smattering of browser support: http://kangax.github.io/compat-table/es6/. The syntax is:
const CONSTANT_NAME = 0;
You can try this:
CommandArgument='<%# "scrapid=" + Eval("ScrapId")+"&"+"UserId="+ Eval("UserId")%>'
You may use the SPOOL command to write the information to a file.
Before executing any command type the following:
SPOOL <output file path>
All commands output following will be written to the output file.
To stop command output writing type
SPOOL OFF
I presume you only want to reset a single element. Resetting an entire form is simple: call its reset method.
The easiest way to "reset" a select element is to set its selectedIndex
property to the default value. If you know that no option is the default selected option, just set the select elemen'ts selectedIndex property to an appropriate value:
function resetSelectElement(selectElement) {
selecElement.selectedIndex = 0; // first option is selected, or
// -1 for no option selected
}
However, since one option may have the selected attribtue or otherwise be set to the default selected option, you may need to do:
function resetSelectElement(selectElement) {
var options = selectElement.options;
// Look for a default selected option
for (var i=0, iLen=options.length; i<iLen; i++) {
if (options[i].defaultSelected) {
selectElement.selectedIndex = i;
return;
}
}
// If no option is the default, select first or none as appropriate
selectElement.selectedIndex = 0; // or -1 for no option selected
}
And beware of setting attributes rather than properties, they have different effects in different browsers.
Here, you could use cv2.bitwise_and
function if you already have the mask image.
For check the below code:
img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)
The output will be as follows for a lena image, and for rectangular mask.
If you want to check that one String contains another Sub-String within it or not you can check it like this too,
var name = String()
name = "John has two apples."
Now, in this particular string if you want to know if it contains fruit name 'apple' or not you can do,
if name.contains("apple")
{
print("Yes , it contains fruit name")
}
else
{
print(it does not contain any fruit name)
}
Hope this works for you.
Replace the first instance with a unique placeholder then split from there.
"good_luck_buddy".replace(/\_/,'&').split('&')
["good","luck_buddy"]
This is more useful when both sides of the split are needed.
think simple
<button id="button1" onclick="Click();">ok</button>
<script>
var buttonClick = false;
function Click() {
if (buttonClick) {
return;
}
else {
buttonClick = true;
//todo
alert("ok");
//buttonClick = false;
}
}
</script>
if you want run once :)
I know I am late to the party, but I'll quote like they say, "better be late than never". So let us get going, Everybody has their own ways to explain things, let me try to sum it up and simple it up for you in a few steps with an example; Suppose you have a simple form, form.jsp
<form:form action="processForm" modelAttribute="student">
First Name : <form:input path="firstName" />
<br><br>
Last Name : <form:input path="lastName" />
<br><br>
<input type="submit" value="submit"/>
</form:form>
path="firstName" path="lastName" These are the fields/properties in the StudentClass when the form is called their getters are called but once submitted their setters are called and their values are set in the bean that was indicated in the modelAttribute="student" in the form tag.
We have StudentController that includes the following methods;
@RequestMapping("/showForm")
public String showForm(Model theModel){ //Model is used to pass data between
//controllers and views
theModel.addAttribute("student", new Student()); //attribute name, value
return "form";
}
@RequestMapping("/processForm")
public String processForm(@ModelAttribute("student") Student theStudent){
System.out.println("theStudent :"+ theStudent.getLastName());
return "form-details";
}
//@ModelAttribute("student") Student theStudent
//Spring automatically populates the object data with form data all behind the
//scenes
now finally we have a form-details.jsp
<b>Student Information</b>
${student.firstName}
${student.lastName}
So back to the question What is @ModelAttribute in Spring MVC? A sample definition from the source for you, http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation The @ModelAttribute is an annotation that binds a method parameter or method return value to a named model attribute and then exposes it to a web view.
What actually happens is it gets all the values of your form those were submitted by it and then holds them for you to bind or assign them to the object. It works same like the @RequestParameter where we only get a parameter and assign the value to some field. Only difference is @ModelAttribute holds all form data rather than a single parameter. It creates a bean for you that holds form submitted data to be used by the developer later on.
To recap the whole thing. Step 1 : A request is sent and our method showForm runs and a model, a temporary bean is set with the name student is forwarded to the form. theModel.addAttribute("student", new Student());
Step 2 : modelAttribute="student" on form submission model changes the student and now it holds all parameters of the form
Step 3 : @ModelAttribute("student") Student theStudent We fetch the values being hold by @ModelAttribute and assign the whole bean/object to Student.
Step 4 : And then we use it as we bid, just like showing it on the page etc like I did
I hope it helps you to understand the concept. Thanks
Instead of void you can also use:
<a href="javascript:;">this link is disabled</a>
You can use query
, i.e.:
b = df.query('a > 1 & a < 5')
In a global function we can't pass a custom value directly but there are many way as below
var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf(item);//item: the value which you want to remove
//Method 1
ary.splice(index,1);
//Method 2
delete ary[index]; //in this method the deleted element will be undefined
My favorite no-conflict-friendly construct:
jQuery(function($) {
// ...
});
Calling jQuery with a function pointer is a shortcut for $(document).ready(...)
Or as we say in coffeescript:
jQuery ($) ->
# code here
(Note: root, base, apex domains are all the same thing. Using interchangeably for google-foo.)
Traditionally, to point your apex domain you'd use an A record pointing to your server's IP. This solution doesn't scale and isn't viable for a cloud platform like Heroku, where multiple and frequently changing backends are responsible for responding to requests.
For subdomains (like www.example.com
) you can use CNAME records pointing to your-app-name.herokuapp.com
. From there on, Heroku manages the dynamic A records behind your-app-name.herokuapp.com
so that they're always up-to-date. Unfortunately, the DNS specification does not allow CNAME records on the zone apex (the base domain). (For example, MX records would break as the CNAME would be followed to its target first.)
Back to root domains, the simple and generic solution is to not use them at all. As a fallback measure, some DNS providers offer to setup an HTTP redirect for you. In that case, set it up so that example.com
is an HTTP redirect to www.example.com
.
Some DNS providers have come forward with custom solutions that allow CNAME-like behavior on the zone apex. To my knowledge, we have DNSimple's ALIAS record and DNS Made Easy's ANAME record; both behave similarly.
Using those, you could setup your records as (using zonefile notation, even tho you'll probably do this on their web user interface):
@ IN ALIAS your-app-name.herokuapp.com.
www IN CNAME your-app-name.herokuapp.com.
Remember @
here is a shorthand for the root domain (example.com
). Also mind you that the trailing dots are important, both in zonefiles, and some web user interfaces.
Amazon's Route 53 also has an ALIAS record type, but it's somewhat limited, in that it only works to point within AWS. At the moment I would not recommend using this for a Heroku setup.
Some people confuse DNS providers with domain name registrars, as there's a bit of overlap with companies offering both. Mind you that to switch your DNS over to one of the aforementioned providers, you only need to update your nameserver records with your current domain registrar. You do not need to transfer your domain registration.
Use:
#include <iostream>
...
std::cout << std::hex << a;
There are many other options to control the exact formatting of the output number, such as leading zeros and upper/lower case.
If you don't wan't to use ng-model there is ng-value
you can try.
Here's the fiddle for this: http://jsfiddle.net/Rg9sG/1/