By using sscanf we can convert string to float.
#include<stdio.h>
#include<string.h>
int main()
{
char str[100] ="4.0800" ;
const char s[2] = "-";
char *token;
double x;
/* get the first token */
token = strtok(str, s);
sscanf(token,"%f",&x);
printf( " %f",x );
return 0;
}
You are missing an include :
#include <stdlib.h>
, so GCC creates an implicit declaration of atof
and atod
, leading to garbage values.
And the format specifier for double is %f
, not %d
(that is for integers).
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *test = "12.11";
double temp = strtod(test,NULL);
float ftemp = atof(test);
printf("price: %f, %f",temp,ftemp);
return 0;
}
/* Output */
price: 12.110000, 12.110000
[0-9]
is not always equivalent to \d
. In python3, [0-9]
matches only 0123456789
characters, while \d
matches [0-9]
and other digit characters, for example Eastern Arabic numerals ??????????
.
The reason you separate the login and non-login shell is because the .bashrc
file is reloaded every time you start a new copy of Bash. The .profile
file is loaded only when you either log in or use the appropriate flag to tell Bash to act as a login shell.
Personally,
PATH
setup into a .profile
file (because I sometimes use other shells);.bashrc
file;I put this
#!/bin/bash
#
# CRM .bash_profile Time-stamp: "2008-12-07 19:42"
#
# echo "Loading ${HOME}/.bash_profile"
source ~/.profile # get my PATH setup
source ~/.bashrc # get my Bash aliases
in my .bash_profile
file.
Oh, and the reason you need to type bash
again to get the new alias is that Bash loads your .bashrc
file when it starts but it doesn't reload it unless you tell it to. You can reload the .bashrc
file (and not need a second shell) by typing
source ~/.bashrc
which loads the .bashrc
file as if you had typed the commands directly to Bash.
As i know, you can't do it in a sentence.
But you can build an stored procedure that do the deletes you want in whatever table in a transaction, what is almost the same.
This script iterates all directories and zip each one
Get-ChildItem -Attributes d | foreach {write-zip $.Name "$($.Name).zip"}
If you have access to the code that creates the canvas - simply call the function right there after the canvas is created.
If you have no access to that code (eg. If it is a 3rd party code such as google maps) then what you could do is test for the existence in an interval:
var checkExist = setInterval(function() {
if ($('#the-canvas').length) {
console.log("Exists!");
clearInterval(checkExist);
}
}, 100); // check every 100ms
But note - many times 3rd party code has an option to activate your code (by callback or event triggering) when it finishes to load. That may be where you can put your function. The interval solution is really a bad solution and should be used only if nothing else works.
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array empty or does not exist
}
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ? do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values like null
, undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as the arguments
object and DOM NodeList
objects. Depending on your situation, this might not be the behavior you're after.
The array.length
condition checks whether the variable's length
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0
or array.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ? probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ? probably OK to process array
}
For those of us still working with older browsers, here's some extended backwards compatibility:
<div style="text-align: center;">
<div style="display:-moz-inline-stack; display:inline-block; zoom:1; *display:inline; text-align: left;">
Line 1: Testing<br>
Line 2: More testing<br>
Line 3: Even more testing<br>
</div>
</div>
_x000D_
Partially inspired by this post: https://stackoverflow.com/a/12567422/14999964.
A simple answer is to add checked
attributes within a checkbox:
$('input[id='+$(this).attr("id")+']').attr("checked", "checked");
Another case is http redirection. If your page redirects http requests to https, then may be your partial view tries to redirect by itself.
It causes same problem again. For this problem, you can reorganize your .net error pages or iis error pages configuration.
Just make sure you are redirecting requests to right error or not found page and make sure this error page contains non problematic partial. If your page supports only https, do not forward requests to error page without using https, if error page contains partial, this partials tries to redirect seperately from requested url, it causes problem.
In your manifest file where our activity is defined
<activity
android:name=".YourPopUpActivity"
android:theme="@android:style/Theme.Holo.Dialog" >
</activity>
without action bar
<activity android:name=".YourPopUpActivity"
android:theme="@android:style/Theme.Holo.Dialog.NoActionBar"/>
In my case it was the wrong dependecy for CrudRepository. My IDE added also follwing:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>1.11.2.RELEASE</version>
</dependency>
But I just needed:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>RELEASE</version>
</dependency>
I removed the first one and everything was fine.
Here is something I did which open Facebook App with Link
shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setComponent(new ComponentName("com.facebook.katana",
"com.facebook.katana.activity.composer.ImplicitShareIntentHandler"));
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, videoUrl);
These are all very sub-optimal solutions. From the GZIP spec
ID2 (IDentification 2)
These have the fixed values ID1 = 31 (0x1f, \037), ID2 = 139 (0x8b, \213), to identify the file as being in gzip format.
Has to be coded into whatever language you're using.
No, it's not possible using just one selector. The :first-of-type
pseudo-class selects the first element of its type (div
, p
, etc). Using a class selector (or a type selector) with that pseudo-class means to select an element if it has the given class (or is of the given type) and is the first of its type among its siblings.
Unfortunately, CSS doesn't provide a :first-of-class
selector that only chooses the first occurrence of a class. As a workaround, you can use something like this:
.myclass1 { color: red; }
.myclass1 ~ .myclass1 { color: /* default, or inherited from parent div */; }
Explanations and illustrations for the workaround are given here and here.
It's just a basic operation.
Remember when you learned to divide. In the beginning we solved 9/6 = 1 with remainder 3
.
9 / 6 == 1 //true
9 % 6 == 3 // true
The /-operator in combination with the %-operator are used to retrieve those values.
I am sure It working fine for you
Goto top level SVN folder.
Right Click on folder(that has your svn files) -> TortoiseSVN -> CleanUp
This will surely solve your problem.
Get the content of the JSON file using file_get_contents()
:
$str = file_get_contents('http://example.com/example.json/');
Now decode the JSON using json_decode()
:
$json = json_decode($str, true); // decode the JSON into an associative array
You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:
echo '<pre>' . print_r($json, true) . '</pre>';
This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true
in order to let print_r()
know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:
$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];
Or loop through the array however you wish:
foreach ($json['daily']['data'] as $field => $value) {
// Use $field and $value here
}
What causes a "broken pipe", and more importantly, is it possible to recover from that state?
It is caused by something causing the connection to close. (It is not your application that closed the connection: that would have resulted in a different exception.)
It is not possible to recover the connection. You need to open a new one.
If it cannot be recovered, it seems this would be a good sign that an irreversible problem has occurred and that I should simply close this socket connection. Is that a reasonable assumption?
Yes it is. Once you've received that exception, the socket won't ever work again. Closing it is is the only sensible thing to do.
Is there ever a time when this
IOException
would occur while the socket connection is still being properly connected in the first place (rather than a working connection that failed at some point)?
No. (Or at least, not without subverting proper behavior of the OS'es network stack, the JVM and/or your application.)
Is it wise to always call
SocketChannel.isConnected()
before attempting aSocketChannel.write()
...
In general, it is a bad idea to call r.isXYZ()
before some call that uses the (external) resource r
. There is a small chance that the state of the resource will change between the two calls. It is a better idea to do the action, catch the IOException
(or whatever) resulting from the failed action and take whatever remedial action is required.
In this particular case, calling isConnected()
is pointless. The method is defined to return true
if the socket was connected at some point in the past. It does not tell you if the connection is still live. The only way to determine if the connection is still alive is to attempt to use it; e.g. do a read or write.
Another option is to repeat the rules in two prefix locations using an included file. Since prefix locations are position independent in the configuration, using them can save some confusion as you add other regex locations later on. Avoiding regex locations when you can will help your configuration scale smoothly.
server {
location /first/location/ {
include shared.conf;
}
location /second/location/ {
include shared.conf;
}
}
Here's a sample shared.conf:
default_type text/plain;
return 200 "http_user_agent: $http_user_agent
remote_addr: $remote_addr
remote_port: $remote_port
scheme: $scheme
nginx_version: $nginx_version
";
You need the full render partial syntax if you are passing locals
<%= render @users, :locals => {:size => 30} %>
Becomes
<%= render :partial => 'users', :collection => @users, :locals => {:size => 30} %>
Or to use the new hash syntax
<%= render partial: 'users', collection: @users, locals: {size: 30} %>
Which I think is much more readable
I resolved this problem, searching the dll's file in C:\Windows\assembly\GAC_MSIL\ and copied to bin directory of the proyect deployed. That work for me.
Nowadays, Java 8 allows for a one-line functional solution that is cleaner, faster, and a whole lot simpler than the accepted solution:
List<String> list = new ArrayList<>();
list.add("behold");
list.add("bend");
list.add("bet");
list.add("bear");
list.add("beat");
list.add("become");
list.add("begin");
List<String> matches = list.stream().filter(it -> it.contains("bea")).collect(Collectors.toList());
System.out.println(matches); // [bear, beat]
And even easier in Kotlin:
val matches = list.filter { it.contains("bea") }
Try writting the lambda with the same conditions as the delegate. like this:
List<AnalysisObject> analysisObjects =
analysisObjectRepository.FindAll().Where(
(x =>
(x.ID == packageId)
|| (x.Parent != null && x.Parent.ID == packageId)
|| (x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)
).ToList();
If you want to add a dynamic class to your host element, you may combine your HostBinding
with a getter as
@HostBinding('class') get class() {
return aComponentVariable
}
Stackblitz demo at https://stackblitz.com/edit/angular-dynamic-hostbinding
In order to make <tbody>
element scrollable, we need to change the way it's displayed on the page i.e. using display: block;
to display that as a block level element.
Since we change the display
property of tbody
, we should change that property for thead
element as well to prevent from breaking the table layout.
So we have:
thead, tbody { display: block; }
tbody {
height: 100px; /* Just for the demo */
overflow-y: auto; /* Trigger vertical scroll */
overflow-x: hidden; /* Hide the horizontal scroll */
}
Web browsers display the thead
and tbody
elements as row-group (table-header-group
and table-row-group
) by default.
Once we change that, the inside tr
elements doesn't fill the entire space of their container.
In order to fix that, we have to calculate the width of tbody
columns and apply the corresponding value to the thead
columns via JavaScript.
Here is the jQuery version of above logic:
// Change the selector if needed
var $table = $('table'),
$bodyCells = $table.find('tbody tr:first').children(),
colWidth;
// Get the tbody columns width array
colWidth = $bodyCells.map(function() {
return $(this).width();
}).get();
// Set the width of thead columns
$table.find('thead tr').children().each(function(i, v) {
$(v).width(colWidth[i]);
});
And here is the output (on Windows 7 Chrome 32):
As the Original Poster needed, we could expand the table
to 100% of width
of its container, and then using a relative (Percentage) width
for each columns of the table.
table {
width: 100%; /* Optional */
}
tbody td, thead th {
width: 20%; /* Optional */
}
Since the table has a (sort of) fluid layout, we should adjust the width of thead
columns when the container resizes.
Hence we should set the columns' widths once the window is resized:
// Adjust the width of thead cells when *window* resizes
$(window).resize(function() {
/* Same as before */
}).resize(); // Trigger the resize handler once the script runs
The output would be:
I've tested the two above methods on Windows 7 via the new versions of major Web Browsers (including IE10+) and it worked.
However, it doesn't work properly on IE9 and below.
That's because in a table layout, all elements should follow the same structural properties.
By using display: block;
for the <thead>
and <tbody>
elements, we've broken the table structure.
One approach is to redesign the (entire) table layout. Using JavaScript to create a new layout on the fly and handle and/or adjust the widths/heights of the cells dynamically.
For instance, take a look at the following examples:
This approach uses two nested tables with a containing div. The first table
has only one cell which has a div
, and the second table is placed inside that div
element.
Check the Vertical scrolling tables at CSS Play.
This works on most of web browsers. We can also do the above logic dynamically via JavaScript.
Since the purpose of adding vertical scroll bar to the <tbody>
is displaying the table header at the top of each row, we could position the thead
element to stay fixed
at the top of the screen instead.
Here is a Working Demo of this approach performed by Julien.
It has a promising web browser support.
And here a pure CSS implementation by Willem Van Bockstal.
Here is the old answer. Of course I've added a new method and refined the CSS declarations.
In this case, the table
should have a fixed width
(including the sum of columns' widths and the width of vertical scroll-bar).
Each column should have a specific width and the last column of thead
element needs a greater width which equals to the others' width + the width of vertical scroll-bar.
Therefore, the CSS would be:
table {
width: 716px; /* 140px * 5 column + 16px scrollbar width */
border-spacing: 0;
}
tbody, thead tr { display: block; }
tbody {
height: 100px;
overflow-y: auto;
overflow-x: hidden;
}
tbody td, thead th {
width: 140px;
}
thead th:last-child {
width: 156px; /* 140px + 16px scrollbar width */
}
Here is the output:
In this approach, the table
has a width of 100%
and for each th
and td
, the value of width
property should be less than 100% / number of cols
.
Also, we need to reduce the width of thead
as value of the width of vertical scroll-bar.
In order to do that, we need to use CSS3 calc()
function, as follows:
table {
width: 100%;
border-spacing: 0;
}
thead, tbody, tr, th, td { display: block; }
thead tr {
/* fallback */
width: 97%;
/* minus scroll bar width */
width: -webkit-calc(100% - 16px);
width: -moz-calc(100% - 16px);
width: calc(100% - 16px);
}
tr:after { /* clearing float */
content: ' ';
display: block;
visibility: hidden;
clear: both;
}
tbody {
height: 100px;
overflow-y: auto;
overflow-x: hidden;
}
tbody td, thead th {
width: 19%; /* 19% is less than (100% / 5 cols) = 20% */
float: left;
}
Here is the Online Demo.
Note: This approach will fail if the content of each column breaks the line, i.e. the content of each cell should be short enough.
In the following, there are two simple example of pure CSS solution which I created at the time I answered this question.
Here is the jsFiddle Demo v2.
Old version: jsFiddle Demo v1
Visual Studio 2015:
Project
=>
Your Application Properties
. Each argument can be separated using space. If you have a space in between for the same argument, put double quotes as shown in the example below.
static void Main(string[] args)
{
if(args == null || args.Length == 0)
{
Console.WriteLine("Please specify arguments!");
}
else
{
Console.WriteLine(args[0]); // First
Console.WriteLine(args[1]); // Second Argument
}
}
Working with GPX files with Xcode compatibility
I followed the link given by AlexWien and it was extremely useful: https://blackpixel.com/writing/2013/05/simulating-locations-with-xcode.html
But, I spent quite some time searching for how to generate .gpx files with waypoints (wpt tags), as Xcode only accepts wpt tags.
The following tool converts a Google Maps link (also works with Google Maps Directions) to a .gpx file.
https://mapstogpx.com/mobiledev.php
Simulating a trip duration is supported, custom durations can be specified. Just select Xcode and it gets the route as waypoints.
You can effectively "empty" the Recycle Bin from the command line by permanently deleting the Recycle Bin directory on the drive that contains the system files. (In most cases, this will be the C:
drive, but you shouldn't hardcode that value because it won't always be true. Instead, use the %systemdrive%
environment variable.)
The reason that this tactic works is because each drive has a hidden, protected folder with the name $Recycle.bin
, which is where the Recycle Bin actually stores the deleted files and folders. When this directory is deleted, Windows automatically creates a new directory.
So, to remove the directory, use the rd
command (r?emove d?irectory) with the /s
parameter, which indicates that all of the files and directories within the specified directory should be removed as well:
rd /s %systemdrive%\$Recycle.bin
Do note that this action will permanently delete all files and folders currently in the Recycle Bin from all user accounts. Additionally, you will (obviously) have to run the command from an elevated command prompt in order to have sufficient privileges to perform this action.
This is precisely the sort of scenario where analytics come to the rescue.
Given this test data:
SQL> select * from employment_history
2 order by Gc_Staff_Number
3 , start_date
4 /
GC_STAFF_NUMBER START_DAT END_DATE C
--------------- --------- --------- -
1111 16-OCT-09 Y
2222 08-MAR-08 26-MAY-09 N
2222 12-DEC-09 Y
3333 18-MAR-07 08-MAR-08 N
3333 01-JUL-09 21-MAR-09 N
3333 30-JUL-10 Y
6 rows selected.
SQL>
An inline view with an analytic LAG() function provides the right answer:
SQL> select Gc_Staff_Number
2 , start_date
3 , prev_end_date
4 from (
5 select Gc_Staff_Number
6 , start_date
7 , lag (end_date) over (partition by Gc_Staff_Number
8 order by start_date )
9 as prev_end_date
10 , current_flag
11 from employment_history
12 )
13 where current_flag = 'Y'
14 /
GC_STAFF_NUMBER START_DAT PREV_END_
--------------- --------- ---------
1111 16-OCT-09
2222 12-DEC-09 26-MAY-09
3333 30-JUL-10 21-MAR-09
SQL>
The inline view is crucial to getting the right result. Otherwise the filter on CURRENT_FLAG removes the previous rows.
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
This should be
$endOfCycle=date('Y-m-d', strtotime("+30 days"));
strtotime
expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
while
date
Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.
See the manual pages for:
My advise is: try not to rely on dependencies when you can easily do it with few lines of codes
Here's what you're trying to achieve in 14 lines of code:
fs.isDir = function(dpath) {
try {
return fs.lstatSync(dpath).isDirectory();
} catch(e) {
return false;
}
};
fs.mkdirp = function(dirname) {
dirname = path.normalize(dirname).split(path.sep);
dirname.forEach((sdir,index)=>{
var pathInQuestion = dirname.slice(0,index+1).join(path.sep);
if((!fs.isDir(pathInQuestion)) && pathInQuestion) fs.mkdirSync(pathInQuestion);
});
};
import java.util.ArrayList;
public class numbers {
private int number1 = 50;
private int number2 = 100;
private List<Integer> list;
public numbers() {
list = new ArrayList<Integer>();
list.add(number1);
list.add(number2);
}
public List<Integer> getList() {
return list;
}
}
And the test class:
import java.util.ArrayList;
public class test {
private numbers number;
//example
public test() {
number = new numbers();
List<Integer> list = number.getList();
//hurray !
}
}
You could try the fnmatch module, it's got a shell-like wildcard syntax
or can use regular expressions
import re
nope, none of this will work. What you need is this!!!
Try this:
if (screen.width <= 960) {
alert('Less than 960');
} else if (screen.width >960) {
alert('More than 960');
}
I have created a function that allows me to obtain this feature:
function redirect_blank(url) {
var a = document.createElement('a');
a.target="_blank";
a.href=url;
a.click();
}
It's not unique to WP7--it's present on all .Net objects. It sort of does what you describe, but I would not recommend it as a unique identifier in your apps, as it is not guaranteed to be unique.
To avoid the boxing of KeyValuePair.Equals(object)
you can use a ValueTuple
.
if ((getResult.Key, getResult.Value) == default)
Yes, the constant CI_VERSION
will give you the current CodeIgniter version number. It's defined in: /system/codeigniter/CodeIgniter.php As of CodeIgniter 2, it's defined in /system/core/CodeIgniter.php
For example,
echo CI_VERSION; // echoes something like 1.7.1
A couple of things come to mind:
Use an onkeydown
handler in your text field, measure the text*, and increase the text box size accordingly.
Attach a :focus
css class to your text box with a larger width. Then your box will be larger when focused. That's not exactly what you're asking for, but similar.
* It's not straightforward to measure text in javascript. Check out this question for some ideas.
The most common answer to that is simple: Bundle few apps (busybox?) with your APK (assuming you want to use it within an application). As far as I know, the /data partition is not mounted noexec, and even if you don't want to deploy a fully-fledged APK, you could modify ConnectBot sources to build an APK with a set of command line tools included.
For command line tools, I recommend using crosstool-ng and building a set of statically-linked tools (linked against uClibc). They might be big, but they'll definitely work.
You must change the location of MySQL's temporary folder which is '/tmp' in most cases to a location with a bigger disk space. Change it in MySQL's config file.
Basically your server is running out of disk space where /tmp is located.
In the file: $your_eclipse_installation\configuration.settings\org.eclipse.core.net.prefs
you need the option: systemProxiesEnabled=true
You can set it also by the Eclipse GUI: Go to Window -> Preferences -> General -> Network Connections Change the provider to "Native"
The first way is working even if your Eclipse is broken due to wrong configuration attempts.
Instead of a List<UserRole>
, you can let your Model contain a SelectList<UserRole>
. Also add a property SelectedUserRoleId
to store... well... the selected UserRole's Id value.
Fill up the SelectList, then in your View use:
@Html.DropDownListFor(x => x.SelectedUserRoleId, x.UserRole)
and you should be fine.
See also http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist(v=vs.108).aspx.
For Internet Explorer
@media all and (-ms-high-contrast: none) {
.banner-wrapper{
background: rgba(0, 0, 0, 0.16)
}
}
For Edge
@supports (-ms-ime-align:auto) {
.banner-wrapper{
background: rgba(0, 0, 0, 0.16);
}
}
To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.
class YourClass():
def your_function(self, *args):
self.callable_function(param) # if you need to pass any parameter
def callable_function(self, *params):
print('Your param:', param)
Try Case
SELECT stock.name,
CASE
WHEN stock.quantity <20 THEN 'Buy urgent'
ELSE 'There is enough'
END
FROM stock
And if you add an alias for it then it's even better right?
git config --global alias.nccommit 'commit -a --allow-empty-message -m ""'
Now you just do an nccommit, nc because of no comment, and everything should be commited.
Use the following code:
if(processing == success) {
header("Location:filename");
exit();
}
And you are good to go.
make sure settings.py has
USE_TZ = True
In your python file:
from django.utils import timezone
timezone.now() # use its value in model field
SELECT *
FROM table_name
WHERE CONCAT( SUBSTRING(json_date, 11, 4 ) , '-', SUBSTRING( json_date, 7, 2 ) , '-', SUBSTRING( json_date, 3, 2 ) ) >= NOW();
This is bcrypt:
Generate a random salt. A "cost" factor has been pre-configured. Collect a password.
Derive an encryption key from the password using the salt and cost factor. Use it to encrypt a well-known string. Store the cost, salt, and cipher text. Because these three elements have a known length, it's easy to concatenate them and store them in a single field, yet be able to split them apart later.
When someone tries to authenticate, retrieve the stored cost and salt. Derive a key from the input password, cost and salt. Encrypt the same well-known string. If the generated cipher text matches the stored cipher text, the password is a match.
Bcrypt operates in a very similar manner to more traditional schemes based on algorithms like PBKDF2. The main difference is its use of a derived key to encrypt known plain text; other schemes (reasonably) assume the key derivation function is irreversible, and store the derived key directly.
Stored in the database, a bcrypt
"hash" might look something like this:
$2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa
This is actually three fields, delimited by "$":
2a
identifies the bcrypt
algorithm version that was used.10
is the cost factor; 210 iterations of the key derivation function are used (which is not enough, by the way. I'd recommend a cost of 12 or more.)vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa
is the salt and the cipher text, concatenated and encoded in a modified Base-64. The first 22 characters decode to a 16-byte value for the salt. The remaining characters are cipher text to be compared for authentication.This example is taken from the documentation for Coda Hale's ruby implementation.
If you want to do it with multiline/multiple command/s then you can do this:
output=$( bash <<EOF
#multiline/multiple command/s
EOF
)
Or:
output=$(
#multiline/multiple command/s
)
Example:
#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"
Output:
first
second
third
I got a version based on what I saw previously. It helped me a lot to create export files as CSV or TXT. I'm storing a table into a ## Temp Table:
IF OBJECT_ID('tempdb..##TmpExportFile') IS NOT NULL
DROP TABLE ##TmpExportFile;
DECLARE @columnHeader VARCHAR(8000)
DECLARE @raw_sql nvarchar(3000)
SELECT
* INTO ##TmpExportFile
------ FROM THE TABLE RESULTS YOU WANT TO GET
------ COULD BE A TABLE OR A TEMP TABLE BASED ON INNER JOINS
------ ,ETC.
FROM TableName -- optional WHERE ....
DECLARE @table_name VARCHAR(50) = '##TmpExportFile'
SELECT
@columnHeader = COALESCE(@columnHeader + ',', '') + '''[' + c.name + ']''' + ' as ' + '' + c.name + ''
FROM tempdb.sys.columns c
INNER JOIN tempdb.sys.tables t
ON c.object_id = t.object_id
WHERE t.NAME = @table_name
print @columnheader
DECLARE @ColumnList VARCHAR(max)
SELECT
@ColumnList = COALESCE(@ColumnList + ',', '') + 'CAST([' + c.name + '] AS CHAR(' + LTRIM(STR(max_length)) + '))'
FROM tempdb.sys.columns c
INNER JOIN tempdb.sys.tables t
ON c.object_id = t.object_id
WHERE t.name = @table_name
print @ColumnList
--- CSV FORMAT
SELECT
@raw_sql = 'bcp "SELECT ' + @columnHeader + ' UNION all SELECT ' + @ColumnList + ' FROM ' + @table_name + ' " queryout \\networkdrive\networkfolder\datafile.csv -c -t, /S' + ' SQLserverName /T'
--PRINT @raw_sql
EXEC xp_cmdshell @raw_sql
--- TXT FORMAT
SET @raw_sql = 'bcp "SELECT ' + @columnHeader + ' UNION all SELECT ' + @ColumnList + ' FROM ' + @table_name + ' " queryout \\networkdrive\networkfolder\MISD\datafile.txt /c /S'+ ' SQLserverName /T'
EXEC xp_cmdshell @raw_sql
DROP TABLE ##TmpExportFile
A short solution without libraries at all. :)
d = "8/16/18"
day_value = d[(d.find('/')+1):d.find('/18')]
tomorrow = f"{d[0:d.find('/')]}/{int(day_value)+1}{d[d.find('/18'):len(d)]}".format()
print(tomorrow)
# 8/17/18
Make sure that "string d" is actually in the form of %m/%d/%Y
so that you won't have problems transitioning from one month to the next.
IMHO, fs.readFile()
should be avoided because it loads ALL the file in memory and it won't call the callback until all the file has been read.
The easiest way to read a text file is to read it line by line. I recommend a BufferedReader:
new BufferedReader ("file", { encoding: "utf8" })
.on ("error", function (error){
console.log ("error: " + error);
})
.on ("line", function (line){
console.log ("line: " + line);
})
.on ("end", function (){
console.log ("EOF");
})
.read ();
For complex data structures like .properties or json files you need to use a parser (internally it should also use a buffered reader).
If you want to clear all the input fields after submitting the form, consider using reset method on the FormGroup.
It looks like your Spring component scan Base is missing UserServiceImpl
<context:component-scan base-package="org.assessme.com.controller." />
What you do is called a projection. That's when you return only a scalar value that belongs to one entity. You can do this with JPA. See scalar value.
I think in this case, omitting the entity type altogether is possible:
Query query = em.createNativeQuery( "select id from users where username = ?");
query.setParameter(1, "lt");
BigDecimal val = (BigDecimal) query.getSingleResult();
Example taken from here.
I'm not sure I understand the problem.
I you want to change the status bar color programmatically (and provided the device has Android 5.0) then you can use Window.setStatusBarColor()
. It shouldn't make a difference whether the activity is derived from Activity
or ActionBarActivity
.
Just try doing:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.BLUE);
}
Just tested this with ActionBarActivity
and it works alright.
Note: Setting the FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
flag programmatically is not necessary if your values-v21
styles file has it set already, via:
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
Use ToString("X4")
.
The 4 means that the string will be 4 digits long.
Reference: The Hexadecimal ("X") Format Specifier on MSDN.
Another way using dictionary comprehensions,
>>> t = [('A', 1), ('B', 2), ('C', 3)]
>>> d = { i:j for i,j in t }
>>> d
{'A': 1, 'B': 2, 'C': 3}
In general, recommendation are next:
But in particular case you should choose the most appropriate solution or their combination.
Also bear in mind that sometime index could be useful e.g. when you perform update of non-indexed column by some condition.
I don't think there are any machine code decompilers that produce Pascal code. Most "Delphi decompilers" parse form and RTTI data, but do not actually decompile the machine code. I can only recommend using something like DeDe (or similar software) to extract symbol information in combination with a C decompiler, then translate the decompiled C code to Delphi (there are many source code converters out there).
if you need the index just use:
import random
foo = ['a', 'b', 'c', 'd', 'e']
print int(random.random() * len(foo))
print foo[int(random.random() * len(foo))]
random.choice does the same:)
I think most people want their placeholder text to be in grey and appear only once, so this is what I did:
Set your color in viewDidLoad()
(not in IB)
commentsTextView.textColor = UIColor.darkGray
Implement UITextViewDelegate
to your controller
add function to your controller
func textViewDidBeginEditing(_ textView: UITextView) {
if (commentsTextView.textColor == UIColor.darkGray) {
commentsTextView.text = ""
commentsTextView.textColor = UIColor.black
}
}
This solution is simple.
A query string carries textual data so there is no option but to explode the array, encode it correctly and pass it in a representational format of your choice:
p1=value1&pN=valueN...
data=[value1,...,valueN]
data={p1:value1,...,pN:valueN}
and then decode it in your server side code.
for API before 11 you cannot use recreate(). I solved in this way:
Bundle temp_bundle = new Bundle();
onSaveInstanceState(temp_bundle);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("bundle", temp_bundle);
startActivity(intent);
finish();
and in onCreate..
@Override
public void onCreate(Bundle savedInstanceState) {
if (getIntent().hasExtra("bundle") && savedInstanceState==null){
savedInstanceState = getIntent().getExtras().getBundle("bundle");
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code
}
To check if o
is an instance of str
or any subclass of str
, use isinstance (this would be the "canonical" way):
if isinstance(o, str):
To check if the type of o
is exactly str
(exclude subclasses):
if type(o) is str:
The following also works, and can be useful in some cases:
if issubclass(type(o), str):
See Built-in Functions in the Python Library Reference for relevant information.
One more note: in this case, if you're using Python 2, you may actually want to use:
if isinstance(o, basestring):
because this will also catch Unicode strings (unicode
is not a subclass of str
; both str
and unicode
are subclasses of basestring
). Note that basestring
no longer exists in Python 3, where there's a strict separation of strings (str
) and binary data (bytes
).
Alternatively, isinstance
accepts a tuple of classes. This will return True
if o
is an instance of any subclass of any of (str, unicode)
:
if isinstance(o, (str, unicode)):
You need to use \n
inside quotes.
document.getElementById("address_box").value = (title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4)
\n
is called a EOL
or line-break
, \n
is a common EOL
marker and is commonly refereed to as LF
or line-feed
, it is a special ASCII
character
Actually, it is as simple as setting major
and minor
separately:
In [9]: plot([23, 456, 676, 89, 906, 34, 2345])
Out[9]: [<matplotlib.lines.Line2D at 0x6112f90>]
In [10]: yscale('log')
In [11]: grid(b=True, which='major', color='b', linestyle='-')
In [12]: grid(b=True, which='minor', color='r', linestyle='--')
The gotcha with minor grids is that you have to have minor tick marks turned on too. In the above code this is done by yscale('log')
, but it can also be done with plt.minorticks_on()
.
You can use
$window.scrollTo(x, y);
where x
is the pixel along the horizontal axis and y
is the pixel along the vertical axis.
Scroll to top
$window.scrollTo(0, 0);
Focus on element
$window.scrollTo(0, angular.element('put here your element').offsetTop);
Update:
Also you can use $anchorScroll
In prototypeJS, we have method isJSON. You can try that. Even json might help.
"something".isJSON();
// -> false
"\"something\"".isJSON();
// -> true
"{ foo: 42 }".isJSON();
// -> false
"{ \"foo\": 42 }".isJSON();
Besides the third party products listed here, there is another one: NetLib Encryptionizer. However it works in a different way than the obfuscators. Obfuscators modify the assembly itself with a deobfuscation "engine" built into it. Encryptionizer encrypts the DLLs (Managed or Unmanaged) at the file level. So it does not modify the DLL except to encrypt it. The "engine" in this case is a kernel mode driver that sits between your application and the operating system. (Disclaimer: I am from NetLib Security)
Pythonic way to do this is ...
np.divide(data.T,vector).T
This takes care of reshaping and also the results are in floating point format. In other answers results are in rounded integer format.
#NOTE: No of columns in both data and vector should match
I have encountered similar (nearly unexplainable) behavior
Found a reference to deleting .exd files under the directory C:\Users\username\AppData\Local\Temp Located one in each of the directory Excel8.0 and VBE. Typical name is MSForms.exd
Google "Excel exd" or "KB 2553154" From my perspective, it is a completely unacceptable situation which has been there for at least a month now.
On Mac, use the command git credential-osxkeychain erase
.
OR remove manually from keychain from Applications ? Utilities ? Keychain Access. Then remove the github.com keychain. Then use push; it will ask for the keychain access; then deny.
It will ask for the new username and password, add it then pushes a file for that.
After git push
I found this error. Then I use the upper case-
issue:
remote: Permission to user1/file.git denied to user2(previously exist user ). fatal: unable to access 'https://github.com/xxxxxxxxxxxx/': The requested URL returned error: 403
Instead of
$("#header ul li:last")
try
$("#header ul")
I created this comparison between function objects, function calls, call/apply
and bind
a while ago:
.bind
allows you to set the this
value now while allowing you to execute the function in the future, because it returns a new function object.
You need to use the select new
LINQ keyword to explicitly convert your tbcourse
entity into the custom type course
. Example of select new
:
var q = from o in db.Orders
where o.Products.ProductName.StartsWith("Asset") &&
o.PaymentApproved == true
select new { name = o.Contacts.FirstName + " " +
o.Contacts.LastName,
product = o.Products.ProductName,
version = o.Products.Version +
(o.Products.SubVersion * 0.1)
};
One reason to use an explicite Platform.runLater() could be that you bound a property in the ui to a service (result) property. So if you update the bound service property, you have to do this via runLater():
In UI thread also known as the JavaFX Application thread:
...
listView.itemsProperty().bind(myListService.resultProperty());
...
in Service implementation (background worker):
...
Platform.runLater(() -> result.add("Element " + finalI));
...
Following width worked well in HTML5: -
<table >
<tr>
<th style="min-width:120px">Month</th>
<th style="min-width:60px">Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
Please note that
Another way would be something like this, the idea here is to use grouper, but get rid of None
. In this case we'll have all 'small_parts' formed from elements at the first part of the list, and 'larger_parts' from the later part of the list. Length of 'larger parts' is len(small_parts) + 1. We need to consider x as two different sub-parts.
from itertools import izip_longest
import numpy as np
def grouper(n, iterable, fillvalue=None): # This is grouper from itertools
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
def another_chunk(x,num):
extra_ele = len(x)%num #gives number of parts that will have an extra element
small_part = int(np.floor(len(x)/num)) #gives number of elements in a small part
new_x = list(grouper(small_part,x[:small_part*(num-extra_ele)]))
new_x.extend(list(grouper(small_part+1,x[small_part*(num-extra_ele):])))
return new_x
The way I have it set up returns a list of tuples:
>>> x = range(14)
>>> another_chunk(x,3)
[(0, 1, 2, 3), (4, 5, 6, 7, 8), (9, 10, 11, 12, 13)]
>>> another_chunk(x,4)
[(0, 1, 2), (3, 4, 5), (6, 7, 8, 9), (10, 11, 12, 13)]
>>> another_chunk(x,5)
[(0, 1), (2, 3, 4), (5, 6, 7), (8, 9, 10), (11, 12, 13)]
>>>
Here's another way of doing the code above using the openpyxl
module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.
from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')
fc. fc is better at handling large files (> 4 GBytes) than Cygwin's diff.
I think simpler (though without a script) assuming the Status
column is ColumnS.
Select ColumnS and clear formatting from it. Select entire range to be formatted and Format, Conditional formatting..., Format cells if... Custom formula is
and:
=and($S1<>"",search("Complete",$S1)>0)
with fill of choice and Done.
This is not case sensitive (change search
to find
for that) and will highlight a row where ColumnS contains the likes of Now complete
(though also Not yet complete
).
They really make you run around the barn to do it with the GUI:
Make sure your column does not violate the unique constraint before you begin.
alter table location_key drop constraint pinky;
alter table your_table add constraint pinky unique(yourcolumn);
Changes take effect immediately:
Command(s) completed successfully.
I got same issue with
$image_base64 = base64_encode(file_get_contents($_FILES['file']['tmp_name']) );
$image = 'data:image/jpeg;base64,'.$image_base64;
$query = "insert into images(image) values('".$image."')";
mysqli_query($con,$query);
In \xampp\mysql\bin\my.ini file of phpmyadmin we get only
[mysqldump]
max_allowed_packet=110M
which is just for mysqldump -u root -p dbname . I resolved my issue by replacing above code with
max_allowed_packet=110M
[mysqldump]
max_allowed_packet=110M
The First Commented code will increment the number while each "Rebuild Project" and save the the value in the "Version Property" file.
The Second Commented code will generate new version name of APK file while "Build APKs".
android {
compileSdkVersion 28
buildToolsVersion "29.0.0"
//==========================START==================================
def Properties versionProps = new Properties()
def versionPropsFile = file('version.properties')
if(versionPropsFile.exists())
versionProps.load(new FileInputStream(versionPropsFile))
def code = (versionProps['VERSION_CODE'] ?: "0").toInteger() + 1
versionProps['VERSION_CODE'] = code.toString()
versionProps.store(versionPropsFile.newWriter(), null)
//===========================END===================================
defaultConfig {
applicationId "com.example.myapp"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "0.19"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
//=======================================START===============================================
android.applicationVariants.all { variant ->
variant.outputs.all {
def appName = "MyAppSampleName"
outputFileName = appName+"_v${variant.versionName}.${versionProps['VERSION_CODE']}.apk"
}
}
//=======================================END===============================================
}
}
}
public class StringTest{
public static void main(String[] args){
String s ="aaabbbbccccccdd";
String result="";
StringBuilder sb = new StringBuilder(s);
while(sb.length() != 0){
int count = 0;
char test = sb.charAt(0);
while(sb.indexOf(test+"") != -1){
sb.deleteCharAt(sb.indexOf(test+""));
count++;
}
//System.out.println(test+" is repeated "+count+" number of times");
result=result+test+count;
}
System.out.println(result);
}
}
Look for this:
ANY page in your project that has a missing, or different Namespace...
If you have ANY page in your project with <NO Namespace
> , OR a
DIFFERENT Namespace than Default.aspx, you will get this
"Cannot load Default.aspx", or this: "Default.aspx does not belong here".
ALSO: If you have a Redirect to a page in your Solution/Project and the page which is to be Redirected To has a bad namespace -- you may not get a compiler error, until you try and run. If the Redirect is removed or commented-out, the error goes away...
BTW -- What the hell do these error messages mean? Is this MS.Access, with the "misdirection" -- ??
DGK
I had the same problem, just use console.log(...)
(like firebug), and the install a log viewer application, this will allow you to view all the logs for your browser.
The below code disables the EditText in android
editText.setEnabled(false);
List<String> entries;
private ArrayAdapter<String> categoryAdapter;
//Your list of entries {Example: <"category1","category2","category3">}
entries = new ArrayList<String>();
categoryAdapter = new ArrayAdapter<String>(ViewBeaconsActivity.this,
android.R.layout.simple_list_item_1, entries);
//Remove that specific category from the list
entries.remove(categoryName);
//Notify the adapter that your dataset has changed.
categoryAdapter.notifyDataSetChanged();
Better to have this things in info.plist
<key>UIStatusBarHidden</key>
<true/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
this makes no status bar at all.
You need to aggregate the data first, this can be done using the GROUP BY clause:
SELECT Group, COUNT(*)
FROM table
GROUP BY Group
ORDER BY COUNT(*) DESC
The DESC keyword allows you to show the highest count first, ORDER BY by default orders in ascending order which would show the lowest count first.
var checkedString = $('input:checkbox:checked.name').map(function() { return this.value; }).get().join();
Default value doesn't mean default value of data type .Here default value mean value defined at the time of defining function. we have to declare default value of variable while defining variable in function.
Note first that your question shows a bit of misunderstanding. origin/HEAD represents the default branch on the remote, i.e. the HEAD that's in that remote repository you're calling origin. When you switch branches in your repo, you're not affecting that. The same is true for remote branches; you might have master
and origin/master
in your repo, where origin/master
represents a local copy of the master
branch in the remote repository.
origin's HEAD will only change if you or someone else actually changes it in the remote repository, which should basically never happen - you want the default branch a public repo to stay constant, on the stable branch (probably master). origin/HEAD is a local ref representing a local copy of the HEAD in the remote repository. (Its full name is refs/remotes/origin/HEAD.)
I think the above answers what you actually wanted to know, but to go ahead and answer the question you explicitly asked... origin/HEAD is set automatically when you clone a repository, and that's about it. Bizarrely, that it's not set by commands like git remote update
- I believe the only way it will change is if you manually change it. (By change I mean point to a different branch; obviously the commit it points to changes if that branch changes, which might happen on fetch/pull/remote update.)
Edit: The problem discussed below was corrected in Git 1.8.4.3; see this update.
There is a tiny caveat, though. HEAD is a symbolic ref, pointing to a branch instead of directly to a commit, but the git remote transfer protocols only report commits for refs. So Git knows the SHA1 of the commit pointed to by HEAD and all other refs; it then has to deduce the value of HEAD by finding a branch that points to the same commit. This means that if two branches happen to point there, it's ambiguous. (I believe it picks master if possible, then falls back to first alphabetically.) You'll see this reported in the output of git remote show origin
:
$ git remote show origin
* remote origin
Fetch URL: ...
Push URL: ...
HEAD branch (remote HEAD is ambiguous, may be one of the following):
foo
master
Oddly, although the notion of HEAD printed this way will change if things change on the remote (e.g. if foo is removed), it doesn't actually update refs/remotes/origin/HEAD
. This can lead to really odd situations. Say that in the above example origin/HEAD actually pointed to foo, and origin's foo branch was then removed. We can then do this:
$ git remote show origin
...
HEAD branch: master
$ git symbolic-ref refs/remotes/origin/HEAD
refs/remotes/origin/foo
$ git remote update --prune origin
Fetching origin
x [deleted] (none) -> origin/foo
(refs/remotes/origin/HEAD has become dangling)
So even though remote show knows HEAD is master, it doesn't update anything. The stale foo branch is correctly pruned, and HEAD becomes dangling (pointing to a nonexistent branch), and it still doesn't update it to point to master. If you want to fix this, use git remote set-head origin -a
, which automatically determines origin's HEAD as above, and then actually sets origin/HEAD to point to the appropriate remote branch.
For your specific data, you can use
Select col1, col2, LTRIM(RTRIM(SUBSTRING(
STUFF(col3, CHARINDEX('|', col3,
PATINDEX('%|Client Name =%', col3) + 14), 1000, ''),
PATINDEX('%|Client Name =%', col3) + 14, 1000))) col3
from Table01
Test
select col3='Clent ID = 4356hy|Client Name = B B BOB|Client Phone = 667-444-2626|Client Fax = 666-666-0151|Info = INF8888877 -MAC333330554/444400800'
into t1m
from master..spt_values a
cross join master..spt_values b
where a.number < 100
-- (711704 row(s) affected)
set statistics time on
dbcc dropcleanbuffers
dbcc freeproccache
select a=CHARINDEX('|Client Name =', col3) into #tmp1 from t1m
drop table #tmp1
dbcc dropcleanbuffers
dbcc freeproccache
select a=PATINDEX('%|Client Name =%', col3) into #tmp2 from t1m
drop table #tmp2
set statistics time off
Timings
CHARINDEX:
SQL Server Execution Times (1):
CPU time = 5656 ms, elapsed time = 6418 ms.
SQL Server Execution Times (2):
CPU time = 5813 ms, elapsed time = 6114 ms.
SQL Server Execution Times (3):
CPU time = 5672 ms, elapsed time = 6108 ms.
PATINDEX:
SQL Server Execution Times (1):
CPU time = 5906 ms, elapsed time = 6296 ms.
SQL Server Execution Times (2):
CPU time = 5860 ms, elapsed time = 6404 ms.
SQL Server Execution Times (3):
CPU time = 6109 ms, elapsed time = 6301 ms.
Conclusion
The timings for CharIndex and PatIndex for 700k calls are within 3.5% of each other, so I don't think it would matter whichever is used. I use them interchangeably when both can work.
<?
# ------- The graph values in the form of associative array
$values=array(
"Jan" => 110,
"Feb" => 130,
"Mar" => 215,
"Apr" => 81,
"May" => 310,
"Jun" => 110,
"Jul" => 190,
"Aug" => 175,
"Sep" => 390,
"Oct" => 286,
"Nov" => 150,
"Dec" => 196
);
$img_width=450;
$img_height=300;
$margins=20;
# ---- Find the size of graph by substracting the size of borders
$graph_width=$img_width - $margins * 2;
$graph_height=$img_height - $margins * 2;
$img=imagecreate($img_width,$img_height);
$bar_width=20;
$total_bars=count($values);
$gap= ($graph_width- $total_bars * $bar_width ) / ($total_bars +1);
# ------- Define Colors ----------------
$bar_color=imagecolorallocate($img,0,64,128);
$background_color=imagecolorallocate($img,240,240,255);
$border_color=imagecolorallocate($img,200,200,200);
$line_color=imagecolorallocate($img,220,220,220);
# ------ Create the border around the graph ------
imagefilledrectangle($img,1,1,$img_width-2,$img_height-2,$border_color);
imagefilledrectangle($img,$margins,$margins,$img_width-1-$margins,$img_height-1-$margins,$background_color);
# ------- Max value is required to adjust the scale -------
$max_value=max($values);
$ratio= $graph_height/$max_value;
# -------- Create scale and draw horizontal lines --------
$horizontal_lines=20;
$horizontal_gap=$graph_height/$horizontal_lines;
for($i=1;$i<=$horizontal_lines;$i++){
$y=$img_height - $margins - $horizontal_gap * $i ;
imageline($img,$margins,$y,$img_width-$margins,$y,$line_color);
$v=intval($horizontal_gap * $i /$ratio);
imagestring($img,0,5,$y-5,$v,$bar_color);
}
# ----------- Draw the bars here ------
for($i=0;$i< $total_bars; $i++){
# ------ Extract key and value pair from the current pointer position
list($key,$value)=each($values);
$x1= $margins + $gap + $i * ($gap+$bar_width) ;
$x2= $x1 + $bar_width;
$y1=$margins +$graph_height- intval($value * $ratio) ;
$y2=$img_height-$margins;
imagestring($img,0,$x1+3,$y1-10,$value,$bar_color);imagestring($img,0,$x1+3,$img_height-15,$key,$bar_color);
imagefilledrectangle($img,$x1,$y1,$x2,$y2,$bar_color);
}
header("Content-type:image/png");
imagepng($img);
$_REQUEST['asdfad']=234234;
?>
The published responses are correct but incomplete.
Git to install the packages we first need to make sure git is installed.
$ sudo apt install git-core
Bower uses Node.js and npm to manage the programs so lets install these.
$ sudo apt install nodejs
Node will now be installed with the executable located in /etc/usr/nodejs
.
You should be able to execute Node.js by using the command below, but as ours are location in nodejs we will get an error No such file or directory.
$ /usr/bin/env node
We can manually fix this by creating a symlink.
$ sudo ln -s /usr/bin/nodejs /usr/bin/node
Now check Node.js is installed correctly by using.
$ /usr/bin/env node
>
Some users suggest installing legacy nodejs, this package just creates a symbolic link to binary nodejs.
$ sudo apt install nodejs-legacy
Now, you can install npm and bower
Install npm
$ sudo apt install npm
Install Bower
$ sudo npm install -g bower
Check bower is installed and what version you're running.
$ bower -v
1.8.0
Reference:
htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.
Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.
thread apply all bt
I just had to update legacy Weblogic 8 app to use a data-source instead of hard-coded JDBC string. Datasource JNDI name on the configuration tab in the Weblogic admin showed: "weblogic.jdbc.ESdatasource", below are two ways that worked:
Context ctx = new InitialContext();
DataSource dataSource;
try {
dataSource = (DataSource) ctx.lookup("weblogic.jdbc.ESdatasource");
response.getWriter().println("A " +dataSource);
}catch(Exception e) {
response.getWriter().println("A " + e.getMessage() + e.getCause());
}
//or
try {
dataSource = (DataSource) ctx.lookup("weblogic/jdbc/ESdatasource");
response.getWriter().println("F "+dataSource);
}catch(Exception e) {
response.getWriter().println("F " + e.getMessage() + e.getCause());
}
//use your datasource
conn = datasource.getConnection();
That's all folks. No passwords and initial context factory needed from the inside of Weblogic app.
^M
is 0x0d
, i.e. the carriage return character. If your display looks like
line 1^M line 2^M
then the file must have come from Windows because the standard newline sequence on Windows is CR
LF
(0x0d 0x0a
) whereas the standard newline sequence consists solely of LF
on Unices.
If the file had come from a Mac OS 9 or earlier system, you would see it as
line 1^Mline 2^M
because there would be no line feeds following the carriage returns.
When the iFrame points to your site like this:
<html>
<head>
<script type="text/javascript" src="/jquery.js"></script>
</head>
<body>
<iframe id="my_frame" src="/wherev"></iframe>
</body>
</html>
You can access iFrame DOM through this kind of thing.
var iframeBody = $(window.my_frame.document.getElementsByTagName("body")[0]);
iframeBody.append($("<h1/>").html("Hello world!"));
Make sure you correctly define the project's JDK and restart IntelliJ (full restart).
It will work for that code sometimes need both properties
android:layout_gravity="center"
android:layout_centerHorizontal="true"
This will provide information about all the pods,deployments, services and jobs in the namespace.
kubectl get pods,services, deployments, jobs
pods can either be created by deployments or jobs
kubectl delete job [job_name]
kubectl delete deployment [deployment_name]
If you delete the deployment or job then restart of the pods can be stopped.
Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.
Static method is declared with static keyword. Instance method is not with static keyword.
Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.
Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.
Static methods can’t access instance methods and instance variables directly. Instance method can access static variables and static methods directly.
Reference : geeksforgeeks
If you're referring to what happens when you echo something, the single quotes will literally echo what you have between them, while the double quotes will evaluate variables between them and output the value of the variable.
For example, this
#!/bin/sh
MYVAR=sometext
echo "double quotes gives you $MYVAR"
echo 'single quotes gives you $MYVAR'
will give this:
double quotes gives you sometext
single quotes gives you $MYVAR
You can do like...
If you want to access using ColumnName
Int32 First = Convert.ToInt32(ds.Tables[0].Rows[0]["column4Name"].ToString());
Int32 Second = Convert.ToInt32(ds.Tables[0].Rows[0]["column5Name"].ToString());
OR, if you want to access using Index
Int32 First = Convert.ToInt32(ds.Tables[0].Rows[0][4].ToString());
Int32 Second = Convert.ToInt32(ds.Tables[0].Rows[0][5].ToString());
You can cast like this:
return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);
Or like this if you want to be compatible with tsx mode:
return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);
Just remember that this is a compile-time cast, and not a runtime cast.
How about calling a function from within your callback instead of returning a value in sync_call()?
function sync_call(input) {
var value;
// Assume the async call always succeed
async_call(input, function(result) {
value = result;
use_value(value);
} );
}
Remove the slashes:
String json = {"phonetype":"N95","cat":"WP"};
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
I am working in python flask: I had the same problem... There was a "," after I declared my my form variables; I am working with wtforms. That is what caused all the confusion
I think it is worth mentioning that since Spring 3, if you want to create a factory, you can also use the @configuration
annotation combined with the proper @scope
@Configuration
public class MyFactory {
@Bean
@Scope("prototype")
public MyClass create() {
return new MyClass();
}
}
Your factory should be visible by Spring container using the @ComponentScan
annotation or xml configuration
By default Jsonresult "Deny get"
Suppose if we have method like below
[HttpPost]
public JsonResult amc(){}
By default it "Deny Get".
In the below method
public JsonResult amc(){}
When you need to allowget or use get ,we have to use JsonRequestBehavior.AllowGet.
public JsonResult amc()
{
return Json(new Modle.JsonResponseData { Status = flag, Message = msg, Html = html }, JsonRequestBehavior.AllowGet);
}
Despite the fact that a lot of solutions have been already proposed.
I guess that the following one will be short and clear:
public class IntegerToRoman {
public static String intToRoman(int number) {
String[] thousands = {"", "M", "MM", "MMM"};
String[] hundreds = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
String[] tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
String[] units = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
return thousands[number / 1000]
+ hundreds[(number % 1000) / 100]
+ tens[(number % 100) / 10]
+ units[number % 10];
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 5, 10, 14, 17, 20, 25, 38, 49, 63, 72, 81, 97, 98, 99, 100, 101, 248, 253, 799, 1325, 1900, 2000, 2456, 1715};
final Instant startTimeIter = Instant.now();
for (int number : numbers) {
System.out.printf("%4d -> %8s\n", number, intToRoman(number));
}
final Instant endTimeIter = Instant.now();
System.out.printf("Elapsed time: %d ms\n\n", Duration.between(startTimeIter, endTimeIter).toMillis());
}
}
Output:
1 -> I
2 -> II
3 -> III
...
2456 -> MMCDLVI
1715 -> MDCCXV
Elapsed time: 66 ms
Logic is quite simple:
3000
numberThe File
class represents the "idea" of a file, not an actual handle to use for I/O. This is why the File
class has a .exists()
method, to tell you if the file exists or not. (How can you have a File
object that doesn't exist?)
By contrast, constructing a new FileInputStream(new File("/my/file"))
gives you an actual stream to read bytes from.
While File.ReadAllLines()
is one of the simplest ways to read a file, it is also one of the slowest.
If you're just wanting to read lines in a file without doing much, according to these benchmarks, the fastest way to read a file is the age old method of:
using (StreamReader sr = File.OpenText(fileName))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
//do minimal amount of work here
}
}
However, if you have to do a lot with each line, then this article concludes that the best way is the following (and it's faster to pre-allocate a string[] if you know how many lines you're going to read) :
AllLines = new string[MAX]; //only allocate memory here
using (StreamReader sr = File.OpenText(fileName))
{
int x = 0;
while (!sr.EndOfStream)
{
AllLines[x] = sr.ReadLine();
x += 1;
}
} //Finished. Close the file
//Now parallel process each line in the file
Parallel.For(0, AllLines.Length, x =>
{
DoYourStuff(AllLines[x]); //do your work here
});
There is a better way to do this now. You can use the bottom property.
.my-element {
position: absolute;
bottom: 30px;
}
Create a function to move it:
function move_file($file, $to){
$path_parts = pathinfo($file);
$newplace = "$to/{$path_parts['basename']}";
if(rename($file, $newplace))
return $newplace;
return null;
}
try
block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
If you want a robust library, Text_Diff (a PEAR package) looks to be pretty good. It has some pretty cool features.
You can check if the element has child nodes element.hasChildNodes()
. Beware in Mozilla this will return true if the is whitespace after the tag so you will need to verify the tag type.
That Exception is thrown if there is already a key in the dictionary when you try to add the new one.
There must be more than one line in rct3Lines
with the same first word. You can't have 2 entries in the same dictionary with the same key.
You need to decide what you want to happen if the key already exists - if you want to just update the value where the key exists you can simply
rct3Features[items[0]]=items[1]
but, if not you may want to test if the key already exists with:
if(rect3Features.ContainsKey(items[0]))
{
//Do something
}
else
{
//Do something else
}
Wikipedia (or rather, the community on Wikipedia) keeps a pretty good up-to-date list here.
There is a static method System.IO.File.WriteAllBytes
There is a simple one-liner solution not yet mentioned that will convert hex strings into byte arrays (we don't care about negative interpretation here as it does not matter):
BigInteger.Parse(str, System.Globalization.NumberStyles.HexNumber).ToByteArray().Reverse().ToArray();
I had similar problem before. But this was resolved when I started using hostname instead of IP address in my connection string.
I pasted the contents of your example into a file named so.txt
.
$ cat so.txt | awk '{ print $7 }' | cut -f2 -d"="
9
10
Explanation:
cat so.txt
will print the contents of the file to stdout
. awk '{ print $7 }'
will print the seventh column, i.e. the one containing id=n
cut -f2 -d"="
will cut the output of step #2 using =
as the delimiter and get the second column (-f2
)If you'd rather get id=
also, then:
$ cat so.txt | awk '{ print $7 }'
id=9
id=10
I resolved this problem, by stop the application (red square in Eclipse) before run again. If you don't stop it , the application stay in run mode , so port still used .
SimpleDateFormat will not work if he is starting with LocalDate which is new in Java 8. From what I can see, you will have to use DateTimeFormatter, http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html.
LocalDate localDate = LocalDate.now();//For reference
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd LLLL yyyy");
String formattedString = localDate.format(formatter);
That should print 05 May 1988. To get the period after the day and before the month, you might have to use "dd'.LLLL yyyy"
Edit from the future: Please don't use this, this function was removed in Python 3 and Python 2 is dead. Even if you are still using Python 2 you should write Python 3 ready code to make the inevitable upgrade easier.
Although @Burhan Khalid's answer is good, I think it's more understandable like this:
from str import join
sentence = ['this','is','a','sentence']
join(sentence, "-")
The second argument to join() is optional and defaults to " ".
The following code will compare each item with other list of items using contains() method.Length of for loop must be bigger size() of bigger list then only it will compare all the values of both list.
List<String> str = new ArrayList<String>();
str.add("first");
str.add("second");
str.add("third");
List<String> str1 = new ArrayList<String>();
str1.add("first");
str1.add("second");
str1.add("third1");
for (int i = 0; i<str1.size(); i++)
{
System.out.println(str.contains(str1.get(i)));
}
Output is true true false
If you want to avoid the null value use IsNull(Column, 1)
There's also COM.
There are technicalities, but I'd say the advantage is that you'll be able to call methods that you can define.
MSDN offers C# COM interop tutorials. Please search because these links do change.
To get started rightaway go here...
public class One {
private static One one = null;
Map<String, String> configParameter = Collections.synchronizedMap(new HashMap<String, String>());
private One() {
ResourceBundle rb = ResourceBundle.getBundle("System", Locale.getDefault());
Enumeration en = rb.getKeys();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = rb.getString(key);
configParameter.put(key, value);
}
}
public static One getInstance() {
if (one == null) {
one= new One();
}
return one;
}
public Map<String, String> getParameter() {
return configParameter;
}
public static void main(String[] args) {
String string = One.getInstance().getParameter().get("subin");
System.out.println(string);
}
}
Using Java 8 Streams:
Map<Object, Object> map = new HashMap<>();
String content = map.entrySet()
.stream()
.map(e -> e.getKey() + "=\"" + e.getValue() + "\"")
.collect(Collectors.joining(", "));
System.out.println(content);
root/
assets/
lib/-------------------------libraries--------------------
bootstrap/--------------Libraries can have js/css/images------------
css/
js/
images/
jquery/
js/
font-awesome/
css/
images/
common/--------------------common section will have application level resources
css/
js/
img/
index.html
This is how I organized my application's static resources.
This is how I restore RecyclerView position with GridLayoutManager after rotation when you need to reload data from internet with AsyncTaskLoader.
Make a global variable of Parcelable and GridLayoutManager and a static final string:
private Parcelable savedRecyclerLayoutState;
private GridLayoutManager mGridLayoutManager;
private static final String BUNDLE_RECYCLER_LAYOUT = "recycler_layout";
Save state of gridLayoutManager in onSaveInstance()
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(BUNDLE_RECYCLER_LAYOUT,
mGridLayoutManager.onSaveInstanceState());
}
Restore in onRestoreInstanceState
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//restore recycler view at same position
if (savedInstanceState != null) {
savedRecyclerLayoutState = savedInstanceState.getParcelable(BUNDLE_RECYCLER_LAYOUT);
}
}
Then when loader fetches data from internet you restore recyclerview position in onLoadFinished()
if(savedRecyclerLayoutState!=null){
mGridLayoutManager.onRestoreInstanceState(savedRecyclerLayoutState);
}
..of course you have to instantiate gridLayoutManager inside onCreate. Cheers
var html = "<p>Hello, <b>World</b>";
var div = document.createElement("div");
div.innerHTML = html;
alert(div.innerText); // Hello, World
That pretty much the best way of doing it, you're letting the browser do what it does best -- parse HTML.
Edit: As noted in the comments below, this is not the most cross-browser solution. The most cross-browser solution would be to recursively go through all the children of the element and concatenate all text nodes that you find. However, if you're using jQuery, it already does it for you:
alert($("<p>Hello, <b>World</b></p>").text());
Check out the text method.
In general the logs are in /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/
.
In NetBeans go to the "Services" tab open "Servers", right-click on your Glassfish instance and click "View Domain Server Log".
If this doesn't work right-click on the Glassfish instance and click "Properties", you can see the folder with the domains under "Domains folder". Go to this folder -> your-domain -> logs
If the server is already running you should see an Output
tab in NetBeans which is named similar to GlassFish Server x.x.x
You can also use cat
or tail -F
on /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/server.log
. If you are using a different domain then domain1
you have to adjust the path for that.
try this code:
.absolute {
position: absolute;
top: 0; left: 0;
width: 200px;
height: 50px;
background: yellow;
}
You can pass the parameter to the setTimeout callback function as:
setTimeout(function, milliseconds, param1, param2, ...)
eg.
function myFunction() {
setTimeout(alertMsg, 3000, "Hello");
}
function alertMsg(message) {
alert(message)
}
One more simple way:
mComponentName.setBackgroundResource(android.R.color.transparent);
What about
30.seconds.ago
2.days.ago
Or something else you were shooting for?
Let's say for instance you want to get a list of all your customers:
var customers = context.Customers.ToList();
And let's assume that each Customer
object has a reference to its set of Orders
, and that each Order
has references to LineItems
which may also reference a Product
.
As you can see, selecting a top-level object with many related entities could result in a query that needs to pull in data from many sources. As a performance measure, Include()
allows you to indicate which related entities should be read from the database as part of the same query.
Using the same example, this might bring in all of the related order headers, but none of the other records:
var customersWithOrderDetail = context.Customers.Include("Orders").ToList();
As a final point since you asked for SQL, the first statement without Include()
could generate a simple statement:
SELECT * FROM Customers;
The final statement which calls Include("Orders")
may look like this:
SELECT *
FROM Customers JOIN Orders ON Customers.Id = Orders.CustomerId;
I removed the packages indicated in the api 22 in the sdk and the problem is not resolved.
I edited device.xml of Applications / Android / android-sdk-macosx / system-images / android-22 / android-wear / x86 and of Applications / Android / android-sdk-macosx / system-images / android-22 / android-wear / armeabi-v7a I removed the lines containing "d:skin"
Finally restart eclipse and the problem was resolved!
I made a mix of the answers here, took the code of @Julian and ideas from the others, seems clearer to me, this is what's left:
//store the element
var $cache = $('.my-sticky-element');
//store the initial position of the element
var vTop = $cache.offset().top - parseFloat($cache.css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= vTop) {
// if so, ad the fixed class
$cache.addClass('stuck');
} else {
// otherwise remove it
$cache.removeClass('stuck');
}
});
.my-sticky-element.stuck {
position:fixed;
top:0;
box-shadow:0 2px 4px rgba(0, 0, 0, .3);
}
I don't know any language where subclasses inherit constructors (but then, I am not much of a programming polyglott).
Here's a discussion about the same question concerning C#. The general consensus seems to be that it would complicate the language, introduce the potential for nasty side effects to changes in a base class, and generally shouldn't be necessary in a good design.
The print
statement in Python converts its arguments to strings, and outputs those strings to stdout. To save the string to a variable instead, only convert it to a string:
a = str(tag.getArtist())
Not exactly passing a value directly, but using it as if it was passed.
x = 7
def my_method():
nonlocal x
x += 1
my_method()
print(x) # 8
Caveats:
nonlocal
was introduced in python 3global
instead of nonlocal
.It's a syntax for array references - you need to use (&array)
to clarify to the compiler that you want a reference to an array, rather than the (invalid) array of references int & array[100];
.
EDIT: Some clarification.
void foo(int * x);
void foo(int x[100]);
void foo(int x[]);
These three are different ways of declaring the same function. They're all treated as taking an int *
parameter, you can pass any size array to them.
void foo(int (&x)[100]);
This only accepts arrays of 100 integers. You can safely use sizeof
on x
void foo(int & x[100]); // error
This is parsed as an "array of references" - which isn't legal.
I had the same problem .. something happened to my bash profile that wasn't setting up the RVM stuff correctly.
Make sure your bash profile has the following line:
[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # This loads RVM into a shell session.
Then I ran "source ~/.bash_profile" and that reloaded everything that was in my bash profile.
That seemed to fix it for me.
Another variation you can try is(expanding @mnel's answer) if you have many temp'x'.
here "n" could be the number of temp variables present
rm(list = c(paste("temp",c(1:n),sep="")))
Try applying this style to your div class="input-group"
:
text-align:center;
View it: Fiddle.
I just did this tutorial and followed @gion_13 answer. Still did not work. Solved it by making my ng-app name in the index identical to the one in my js file. Exactly identical, even the quotes. So:
<div ng-app="myapp">
<div ng-controller="FirstCtrl">
and the js:
angular.module("myapp", [])
.controller('FirstCtrl',function($scope) {
$scope.data= {message:"hello"};
});
Weird how the ng-app has to be identical but the ng-controller doesn't.
You can annotate a class or a method with SuppressWarnings
@java.lang.SuppressWarnings("squid:S00112")
squid:S00112 in this case is a Sonar issue ID. You can find this ID in the Sonar UI. Go to Issues Drilldown. Find an issue you want to suppress warnings on. In the red issue box in your code is there a Rule link with a definition of a given issue. Once you click that you will see the ID at the top of the page.
I think the first article you link to states it pretty clearly:
The obvious advantage to writing JavaScript in this manner is that you can use it obscure values that you don't want the user to directly access.
The goal here is to encapsulate and abstract away the fields by only allowing access to them thru a get()
or set()
method. This way, you can store the field/data internally in whichever way you want, but outside components are only away of your published interface. This allows you to make internal changes without changing external interfaces, to do some validation or error-checking within the set()
method, etc.
I have tried some methods above. However, the experiment by @zbinsd has its limitation. The sparsity of matrix used in the experiment is extremely low while the real sparsity is usually over 90%. In my condition, the sparse is with the shape of (7000, 25000) and the sparsity of 97%. The method 4 is extremely slow and I can't tolerant getting the results. I use the method 6 which is finished in 10 s. Amazingly, I try the method below and it's finished in only 0.247 s.
import sklearn.preprocessing as pp
def cosine_similarities(mat):
col_normed_mat = pp.normalize(mat.tocsc(), axis=0)
return col_normed_mat.T * col_normed_mat
This efficient method is linked by enter link description here
I faced similar scenario. It was happening because classA's initilization was dependent on classB's initialization. When classB's static block faced runtime exception, classB was not initialized. Because of this, classB did not throw any exception and classA's initialization failed too.
class A{//this class will never be initialized because class B won't intialize
static{
try{
classB.someStaticMethod();
}catch(Exception e){
sysout("This comment will never be printed");
}
}
}
class B{//this class will never be initialized
static{
int i = 1/0;//throw run time exception
}
public static void someStaticMethod(){}
}
And yes...catching Exception
will catch run time exceptions as well.
JSON string that needs to be deserialized will have to contain the type information about parameter T
.
You will have to put Jackson annotations on every class that can be passed as parameter T
to class Data
so that the type information about parameter type T
can be read from / written to JSON string by Jackson.
Let us assume that T
can be any class that extends abstract class Result
.
class Data <T extends Result> {
int found;
Class<T> hits
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({
@JsonSubTypes.Type(value = ImageResult.class, name = "ImageResult"),
@JsonSubTypes.Type(value = NewsResult.class, name = "NewsResult")})
public abstract class Result {
}
public class ImageResult extends Result {
}
public class NewsResult extends Result {
}
Once each of the class (or their common supertype) that can be passed as parameter T
is annotated, Jackson will include information about parameter T
in the JSON. Such JSON can then be deserialized without knowing the parameter T
at compile time.
This Jackson documentation link talks about Polymorphic Deserialization but is useful to refer to for this question as well.
Using cin's >> operator will drop leading whitespace and stop input at the first trailing whitespace. To grab an entire line of input, including spaces, try cin.getline()
. To grab one character at a time, you can use cin.get()
.
You could try something like this:
...Binding="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...
"an object" of what type?
You can certainly assign NULL
(and nullptr
) to objects of pointer types, and it is implementation defined if you can assign NULL
to objects of arithmetic types.
If you mean objects of some class type, the answer is NO (excepting classes that have operator=
accepting pointer or arithmetic types)
"empty" is more plausible, as many types have both copy assignment and default construction (often implicitly). To see if an existing object is like a default constructed one, you will also need an appropriate bool operator==
use:
i.ToString("D10")
See Int32.ToString (MSDN), and Standard Numeric Format Strings (MSDN).
Or use String.PadLeft
. For example,
int i = 321;
Key = i.ToString().PadLeft(10, '0');
Would result in 0000000321
. Though String.PadLeft
would not work for negative numbers.
See String.PadLeft (MSDN).
Do you by size mean the number of records in the table, by any chance? In that case:
SELECT COUNT(*) FROM your_table_name
Just a note to anyone landing here from google, the answers setting path are all correct, but this problem probably stems from not giving the python installer administrative rights it needs to set the path itself. An alternative may be to simply right click the installer and select run as administrator, then repair the installation. If that still doesn't work, choose the [Environment] answer below that corresponds to your python version and installation directory. – MaxPRafferty Nov 18 '15 at 20:06
Maybe it is wise to let Python installer to add the path itself. The trap here is that by default Python installer does NOT add path for you. You should look carefully (by scrolling down to see what has been installed) during the installation process instead of directly next
ing to the end.
What he missed saying is that you cannot run as administrator
once you have installed it. Uninstall and reinstall may do, but the simplest is to right click and Troubleshoot compatibility
, being careful this time to check the 'add path' in the "what to install" dialog before hiting next
. Then restart powershell. Voilà. It works for me.
*args
just means that the function takes a number of arguments, generally of the same type.
Check out this section in the Python tutorial for more info.
Use something like this -
SELECT DISTINCT COL_NAME FROM myTable WHERE UPPER(COL_NAME) LIKE UPPER('%PriceOrder%')
or
SELECT DISTINCT COL_NAME FROM myTable WHERE LOWER(COL_NAME) LIKE LOWER('%PriceOrder%')
I had a similar requirement in the app I am working on. And, I found a third-party library which does a slide-up, slide-down and slide-right in Android.
Refer to the link for more details: https://github.com/mancj/SlideUp-Android
To set up the library(copied from the ReadMe portion of its Github page on request):
Get SlideUp library
Add the JitPack repository to your build file. Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
maven { url "https://maven.google.com" } // or google() in AS 3.0
}
}
Add the dependency (in the Module gradle)
dependencies {
compile 'com.github.mancj:SlideUp-Android:2.2.1'
compile 'ru.ztrap:RxSlideUp2:2.x.x' //optional, for reactive listeners based on RxJava-2
compile 'ru.ztrap:RxSlideUp:1.x.x' //optional, for reactive listeners based on RxJava
}
To add the SlideUp into your project, follow these three simple steps:
Step 1:
create any type of layout
<LinearLayout
android:id="@+id/slideView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Step 2:
Find that view in your activity/fragment
View slideView = findViewById(R.id.slideView);
Step 3:
Create a SlideUp object and pass in your view
slideUp = new SlideUpBuilder(slideView)
.withStartState(SlideUp.State.HIDDEN)
.withStartGravity(Gravity.BOTTOM)
//.withSlideFromOtherView(anotherView)
//.withGesturesEnabled()
//.withHideSoftInputWhenDisplayed()
//.withInterpolator()
//.withAutoSlideDuration()
//.withLoggingEnabled()
//.withTouchableAreaPx()
//.withTouchableAreaDp()
//.withListeners()
//.withSavedState()
.build();
You may also refer to the sample project on the link. I found it quite useful.
for anyone encountering this later this may also help. I encountered this exact issue trying to use adb from a user command prompt and the answers above did not help, but the problem went away with an "adb kill-server" when running in an administrator command prompt.
I (being people myself) wrote this statement because I wanted to detect the key which the user typed on the keyboard across different browsers.
In firefox for example, characters have > 0 charCode and 0 keyCode, and keys such as arrows & backspace have > 0 keyCode and 0 charCode.
However, using this statement can be problematic as "collisions" are possible. For example, if you want to distinguish between the Delete and the Period keys, this won't work, as the Delete has keyCode = 46 and the Period has charCode = 46.
verpatch is good, but doesn't handle unicode characters...
try ResourceLib
It would probably be easier to just fake it by using a div. Just make sure you set the height if its empty so that it can actually appear. Say for instance you want it to be 50px tall set the div height to 50px.
<div id="rightflower">
<div id="divImg"></div>
</div>
And in your style sheet just add the background and its properties, height and width, and what ever positioning you had in mind.
For me, I changed C:\apps\Java\jdk1.8_162\bin\javac.exe to C:\apps\Java\jdk1.8_162\bin\javacpl.exe Since there was no executable with that name in the bin folder. That worked.
Lazy loading will produce several SQL calls while Eager loading may load data with one "more heavy" call (with joins/subqueries).
For example, If there is a high ping between your web and sql servers you would go with Eager loading instead of loading related items 1-by-1 with lazy Loading.
For makecert, your startInfo.FileName
should be the complete path of makecert (or just makecert.exe if it's in standard path) then the Arguments
would be -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer
now I'm bit unfamiliar with how certificate store works, but perhaps you'll need to set startInfo.WorkingDirectory
if you're referring the .cer files outside the certificate store
Specifying the column type as serial for PostgreSQL to generate the id.
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(Order=1, TypeName="serial")]
public int ID { get; set; }
https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL
Set libraries search path first:
LINK_DIRECTORIES(${CMAKE_BINARY_DIR}/res)
And then just do
TARGET_LINK_LIBRARIES(GLBall mylib)
Google Place API requires the referer HTTP header to be included when making the API call.
Include HTTP header "Referer:yourdomain.com" and this should fix the response issues.
You can do it calling setRowSelectionInterval :
table.setRowSelectionInterval(0, 0);
to select the first row.
I assume that REALLY you get object from server and want to get object on output
Object.keys(data).map(k=> data[k].Status=='Invalid' && delete data[k])
var data = { 5: { "ID": "0", "Status": "Valid" } }; // some OBJECT from server response_x000D_
_x000D_
data = { ...data,_x000D_
0: { "ID": "1", "Status": "Valid" },_x000D_
1: { "ID": "2", "Status": "Invalid" },_x000D_
2: { "ID": "3", "Status": "Valid" }_x000D_
}_x000D_
_x000D_
// solution 1: where output is sorted filtred array_x000D_
let arr=Object.keys(data).filter(k=> data[k].Status!='Invalid').map(k=>data[k]).sort((a,b)=>+a.ID-b.ID);_x000D_
_x000D_
// solution2: where output is filtered object_x000D_
Object.keys(data).map(k=> data[k].Status=='Invalid' && delete data[k])_x000D_
_x000D_
// show_x000D_
console.log('Object',data);_x000D_
console.log('Array ',arr);
_x000D_
Try not to go
MAMP > conf > [your PHP version] > php.ini
but
MAMP > bin > php > [your PHP version] > conf > php.ini
and change it there, it worked for me...
This is actually javascript but related/relevant because .querySelectorAll targets by CSS syntax:
var i_will_target_self = document.querySelectorAll("ul.menu li a#example")
this example uses css to target links in a menu with id = "example"
that creates a variable which is a collection of the elements we want to change, but we still have actually change them by setting the new target ("_blank"):
for (var i = 0; i < 5; i++) {
i_will_target_self[i].target = "_blank";
}
That code assumes that there are 5 or less elements. That can be changed easily by changing the phrase "i < 5."
read more here: http://xahlee.info/js/js_get_elements.html
From Apple documentation
If you’re developing a new app, you should use HTTPS exclusively. If you have an existing app, you should use HTTPS as much as you can right now, and create a plan for migrating the rest of your app as soon as possible. In addition, your communication through higher-level APIs needs to be encrypted using TLS version 1.2 with forward secrecy. If you try to make a connection that doesn't follow this requirement, an error is thrown. If your app needs to make a request to an insecure domain, you have to specify this domain in your app's Info.plist file.
To Bypass App Transport Security:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>yourserver.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
To allow all insecure domains
<key>NSAppTransportSecurity</key>
<dict>
<!--Include to allow all connections (DANGER)-->
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Read More: Configuring App Transport Security Exceptions in iOS 9 and OSX 10.11
How about a NuGet Windows Identity Foundation. Just add it you you project and away you go! Its one of the MS owned NuGets so should be maintained accordingly.
EDIT: In Windows 8 Windows Identity Foundation is installed (enabled) by turning a windows feature on in Control Panel > All Control Panel Items > Programs and Features > Turn Windows feature on or off the feature is Windows Identity Foundation 3.5. Installers linked in the answer above will not work on Windows 8
The Update table1 set (a,b,c) = (select x,y,x)
syntax is an example of the use of
row-value constructors, Oracle supports this, MSSQL does not. (Connect item)
do a :
git branch
if git show you something like :
* (no branch)
master
Dbranch
You have a "detached HEAD". If you have modify some files on this branch you, commit them, then return to master with
git checkout master
Now you should be able to delete the Dbranch.
^\d{1,2}[\W_]?po$
\d
defines a number and {1,2}
means 1 or two of the expression before, \W
defines a non word character.
Simply look at:
http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#ROUND_HALF_UP
and:
setScale(int precision, int roundingMode)
Or if using Java 6, then
http://download.oracle.com/javase/6/docs/api/java/math/RoundingMode.html#HALF_UP
http://download.oracle.com/javase/6/docs/api/java/math/MathContext.html
and either:
setScale(int precision, RoundingMode mode);
round(MathContext mc);
=IFS(COUNTIF(A1,"*cats*"),"cats",COUNTIF(A1,"*22*"),"22",TRUE,"none")
Well, for your sample and any with a limited number of unique columns, this should do it.
select
distinct a,
(select distinct t2.b from t t2 where t1.a=t2.a and t2.b='VIEW'),
(select distinct t2.b from t t2 where t1.a=t2.a and t2.b='EDIT')
from t t1
System.currentTimeMillis()
does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date
instance to a string before using it. You can use DateFormat
s to convert Date
s to String
s in any timezone:
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());
Another option is to use "localStorage". You can easealy request the value with javascript in another page.
On the first page, you use the following snippet of javascript code to set the localStorage:
<script>
localStorage.setItem("serialNumber", "abc123def456");
</script>
On the second page, you can retrieve the value with the following javascript code snippet:
<script>
console.log(localStorage.getItem("serialNumber"));
</script>
On Google Chrome You can vizualize the values pressing F12 > Application > Local Storage.
Source: https://www.w3schools.com/jsref/prop_win_localstorage.asp
A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.
A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.
You don't need a jQuery selector at all. You already have a reference to the cells in each row via the cells
property.
$('#tblNewAttendees tr').each(function() {
$.each(this.cells, function(){
alert('hi');
});
});
It is far more efficient to utilize a collection that you already have, than to create a new collection via DOM selection.
Here I've used the jQuery.each()
(docs) method which is just a generic method for iteration and enumeration.