You can use Decode
as well:
SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item
The java.lang.SecurityException
you are seeing is because you may enter two entries pointing to the same activity. Remove the second one and you should be good to go.
You may be declared the activity 2 times in the manifest with different properties, like :
<activity android:name=".myclass"> </activity>
and
<activity android:name=".myclass" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
You should remove the unwanted one from the manifest
Method Object JComboBox.getSelectedItem()
returns a value that is wrapped by Object
type so you have to cast it accordingly.
Syntax:
YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();
None of these answers worked for me for python. I solved by this
a[not(@id='XX')]
Also you can use or condition in your xpath by |
operator. Such as
a[not(@id='XX')]|a[not(@class='YY')]
Sometimes we want element which has no class. So you can do like
a[not(@class)]
As always, read Bootstrap's great documentation:
3.x Docs: https://getbootstrap.com/docs/3.3/css/#grid-nesting
Make sure the parent level row is inside of a .container
element. Whenever you'd like to nest rows, just open up a new .row
inside of your column.
Here's a simple layout to work from:
<div class="container">
<div class="row">
<div class="col-xs-6">
<div class="big-box">image</div>
</div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-6"><div class="mini-box">1</div></div>
<div class="col-xs-6"><div class="mini-box">2</div></div>
<div class="col-xs-6"><div class="mini-box">3</div></div>
<div class="col-xs-6"><div class="mini-box">4</div></div>
</div>
</div>
</div>
</div>
4.0 Docs: http://getbootstrap.com/docs/4.0/layout/grid/#nesting
Here's an updated version for 4.0, but you should really read the entire docs section on the grid so you understand how to leverage this powerful feature
<div class="container">
<div class="row">
<div class="col big-box">
image
</div>
<div class="col">
<div class="row">
<div class="col mini-box">1</div>
<div class="col mini-box">2</div>
</div>
<div class="row">
<div class="col mini-box">3</div>
<div class="col mini-box">4</div>
</div>
</div>
</div>
</div>
Which will look like this (with a little bit of added styling):
This is what you CAN do:
write a file in drawable folder, lets name it background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="?attr/colorPrimary"/>
</shape>
then set your Layout's (or what so ever the case is) android:background="@drawable/background"
on setting your theme this color would represent the same.
For me, the try_files
directive in the (currently most voted) answer https://stackoverflow.com/a/11957896/608359 led to rewrite cycles,
*173 rewrite or internal redirection cycle while internally redirecting
I had better luck with the index directive. Note that I used a forward slash before the name, which might or might not be what you want.
server {
listen 443 ssl;
server_name example.com;
root /home/dclo/example;
index /index.html;
error_page 404 /index.html;
# ... ssl configuration
}
In this case, I wanted all paths to lead to /index.html, including when returning a 404.
While looking at the same problem, I found an example
<style type="text/css">
#topright {
position: absolute;
right: 0;
top: 0;
display: block;
height: 125px;
width: 125px;
background: url(TRbanner.gif) no-repeat;
text-indent: -999em;
text-decoration: none;
}
</style>
<a id="topright" href="#" title="TopRight">Top Right Link Text</a>
The trick here is to create a small, (I used GIMP) a PNG (or GIF) that has a transparent background, (and then just delete the opposite bottom corner.)
According to the spec RFC 2045 #Syntax of the Content-Type Header Field application/myappname
is not allowed, but application/x-myappname
is allowed and sounds most appropriate for you're application to me.
If you need to insert node/element in some specific place , you can to do next steps
It is simple algorithm but should works...
I use DrawERD for ERD & DB doc. https://drawerd.com
Below changes works for me on Angular 2 final version:
export class AppSettings {
public static API_ENDPOINT='http://127.0.0.1:6666/api/';
}
And then in the service:
import {Http} from 'angular2/http';
import {Message} from '../models/message';
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import {AppSettings} from '../appSettings';
import 'rxjs/add/operator/map';
@Injectable()
export class MessageService {
constructor(private http: Http) { }
getMessages(): Observable<Message[]> {
return this.http.get(AppSettings.API_ENDPOINT+'/messages')
.map(response => response.json())
.map((messages: Object[]) => {
return messages.map(message => this.parseData(message));
});
}
private parseData(data): Message {
return new Message(data);
}
}
To my knowledge there is no difference between NUMERIC and DECIMAL data types. They are synonymous to each other and either one can be used. DECIMAL and NUMERIC data types are numeric data types with fixed precision and scale.
Edit:
Speaking to a few collegues maybe its has something to do with DECIMAL being the ANSI SQL standard and NUMERIC being one Mircosoft prefers as its more commonly found in programming languages. ...Maybe ;)
Click on Statistics icon to display and then run the query to get the timings and to know how efficient your query is
If you installed GitHubDesktop then the path for git.exe will be ,
C:\Users\<'Username'>\AppData\Local\GitHubDesktop\app-1.1.1\resources\app\git\cmd
Add this path to the environment variables by following,
** (Note: \cmd at the end, not \cmd\git.exe).**
Navigate to the Environmental Variables Editor and find the Path variable in the “System Variables” section. Click Edit… and paste the URL of Git to the end. Save!
Now open a new cmd and type command git. If you are able to see the git usage then it's done.
Now you can execute your command to install your package.
ex: npm install native-base --save
The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.
Please see the error below:
Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)
which points to username
not getting populated
.
Please recheck system properties
dataSource.setUsername(System.getProperty("root"));
some packages seems to be missing as well pointing to a dependency issue:
package org.gjt.mm.mysql does not exist
Please run a mvn dependency:tree
command to check for dependencies
I have a lot of problems with breakpoints in Xcode (2.4.1). I use a project that just contains other projects (like a Solution in Visual Studio). I find sometimes that breakpoints don't work at all unless there is at least one breakpoint set in the starting project (i.e. the one containing the entry point for my code). If the only breakpoints are in "lower level" projects, they just get ignored.
It also seems as if Xcode only handles breakpoint operations correctly if you act on the breakpoint when you're in the project that contains the source line the breakpoint's on.
If I try deleting or disabling breakpoints via another project, the action sometimes doesn't take effect, even though the debugger indicates that it has. So I will find myself breaking on disabled breakpoints, or on a (now invisible) breakpoint that I removed earlier.
If you have pip install and you want to see what packages have been installed with your installer tools you can simply call this:
pip freeze
It will also include version numbers for the installed packages.
Update
pip has been updated to also produce the same output as pip freeze
by calling:
pip list
Note
The output from pip list
is formatted differently, so if you have some shell script that parses the output (maybe to grab the version number) of freeze
and want to change your script to call list
, you'll need to change your parsing code.
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
// Assume x, y, and diameter are instance variables.
Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter);
g2d.fill(circle);
...
}
Here are some docs about paintComponent (link).
You should override that method in your JPanel and do something similar to the code snippet above.
In your ActionListener you should specify x, y, diameter
and call repaint()
.
You can use a custom style:
<!-- Alert Dialog -->
<style name="ThemeOverlay.MaterialComponents.MaterialAlertDialog_Background" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
<!-- Background Color-->
<item name="android:background">@color/.....</item>
<!-- Text Color for title and message -->
<item name="colorOnSurface">@color/......</item>
<!-- Style for positive button -->
<item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
<!-- Style for negative button -->
<item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
</style>
<style name="PositiveButtonStyle" parent="@style/Widget.MaterialComponents.Button">
<!-- text color for the button -->
<item name="android:textColor">@color/.....</item>
<!-- Background tint for the button -->
<item name="backgroundTint">@color/primaryDarkColor</item>
</style>
And just use the default MaterialAlertDialogBuilder
:
new MaterialAlertDialogBuilder(AlertDialogActivity.this,
R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog_Background)
.setTitle("Dialog")
.setMessage("Message... ....")
.setPositiveButton("Ok", /* listener = */ null)
.show();
public class UserNotFoundException extends Exception {
public UserNotFoundException(String message) {
super(message)
I know I am late to the party, but how about this?
const char* dayNames[] = { [Sunday] = "Sunday", [Monday] = "Monday", /*and so on*/ };
printf("%s", dayNames[Sunday]); // prints "Sunday"
This way, you do not have to manually keep the enum
and the char*
array in sync. If you are like me, chances are that you will later change the enum
, and the char*
array will print invalid strings.
This may not be a feature universally supported. But afaik, most of the mordern day C compilers support this designated initialier style.
You can read more about designated initializers here.
If you have installed jdk8 on your Mac but now you want to remove it, just run below command "sudo rm -rf /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk"
To switch between tabs action class does not always works on all browser and on all webdriver. the best way is to use robot class. try this code.
String website = "https://www.google.com";
String website1 = "https://www.msn.com/en-in/";
String controlpath = "C:\\Libraries\\msedgedriver.exe";
System.setProperty("webdriver.edge.driver", controlpath);
driver = new EdgeDriver();
driver.manage().window().maximize(); // Maximize browser
driver.get(website);
System.out.println("Google page");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_T);
//Switch focus to new tab
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
//System.out.println("Handle info"+ driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
//Launch URL in the new tab
driver.get(website1);
System.out.println("msn page");
Thread.sleep(5000);
driver.switchTo().window(tabs.get(0));
Thread.sleep(5000);
if you want to remove all elements with matching ID parts, for example:
<span id='myID_123'>
<span id='myID_456'>
<span id='myID_789'>
try this:
$("span[id*=myID]").remove();
don't forget the '*' - this will remove them all at once - cheers
Steps:
What's wrong with
func (e *Easy)SetStringOption(option Option, param string)
func (e *Easy)SetLongOption(option Option, param long)
and so on?
Update for CXF 3.1.7
In my case I put the WSDL files in src/main/resources
and added this path to my Srouces in Eclipse (Right Click on Project-> Build Path -> Configure Build Path...-> Source[Tab] -> Add Folder).
Here is how my pom
file looks like and as can be seen there is NO wsdlLocation
option needed:
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${cxf.version}</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${project.build.directory}/generated/cxf</sourceRoot>
<wsdlOptions>
<wsdlOption>
<wsdl>classpath:wsdl/FOO_SERVICE.wsdl</wsdl>
</wsdlOption>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
</plugin>
And here is the generated Service. As can be seen the URL is get from ClassLoader and not from the Absolute File-Path
@WebServiceClient(name = "EventService",
wsdlLocation = "classpath:wsdl/FOO_SERVICE.wsdl",
targetNamespace = "http://www.sas.com/xml/schema/sas-svcs/rtdm-1.1/wsdl/")
public class EventService extends Service {
public final static URL WSDL_LOCATION;
public final static QName SERVICE = new QName("http://www.sas.com/xml/schema/sas-svcs/rtdm-1.1/wsdl/", "EventService");
public final static QName EventPort = new QName("http://www.sas.com/xml/schema/sas-svcs/rtdm-1.1/wsdl/", "EventPort");
static {
URL url = EventService.class.getClassLoader().getResource("wsdl/FOO_SERVICE.wsdl");
if (url == null) {
java.util.logging.Logger.getLogger(EventService.class.getName())
.log(java.util.logging.Level.INFO,
"Can not initialize the default wsdl from {0}", "classpath:wsdl/FOO_SERVICE.wsdl");
}
WSDL_LOCATION = url;
}
It seems you need DataFrame.var
:
Normalized by N-1 by default. This can be changed using the ddof argument
var1 = credit_card.var()
Sample:
#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4
var1 = credit_card.var()
print (var1)
A 8.8
B 10.0
C 10.0
D 7.7
E 7.8
dtype: float64
var2 = credit_card.var(axis=1)
print (var2)
0 4.3
1 3.8
2 9.8
3 12.2
4 2.3
dtype: float64
If need numpy solutions with numpy.var
:
print (np.var(credit_card.values, axis=0))
[ 7.04 8. 8. 6.16 6.24]
print (np.var(credit_card.values, axis=1))
[ 3.44 3.04 7.84 9.76 1.84]
Differences are because by default ddof=1
in pandas
, but you can change it to 0
:
var1 = credit_card.var(ddof=0)
print (var1)
A 7.04
B 8.00
C 8.00
D 6.16
E 6.24
dtype: float64
var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0 3.44
1 3.04
2 7.84
3 9.76
4 1.84
dtype: float64
Following code works..
datePickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(0);
}
});
@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
day = selectedDay;
month = selectedMonth;
year = selectedYear;
datePickerButton.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
+ selectedYear);
}
};
var yearStart = 2000;
var yearEnd = 2040;
var arr = [];
for (var i = yearStart; i <= yearEnd; i++) {
arr.push(i);
}
I faced the same issue. Just download and install the SQL Server suite from the following link :http://www.microsoft.com/en-US/download/details.aspx?id=42299
restart your SSMS and you should be able to "Register Local Servers" via right-click on "Local Servers Groups", select "tasks", click "register local servers"
This is an old question but one that I think needs another entry (although I doubt anyone will read it). The use of Immediately Invoked Function Expressions (IIFE) can be used in conjunction with closures and inline functions to allow for function overloading. Consider the following (contrived) example:
var foo;
// original 'foo' definition
foo = function(a) {
console.log("a: " + a);
}
// define 'foo' to accept two arguments
foo = (function() {
// store a reference to the previous definition of 'foo'
var old = foo;
// use inline function so that you can refer to it internally
return function newFoo(a,b) {
// check that the arguments.length == the number of arguments
// defined for 'newFoo'
if (arguments.length == newFoo.length) {
console.log("a: " + a);
console.log("b: " + b);
// else if 'old' is a function, apply it to the arguments
} else if (({}).toString.call(old) === '[object Function]') {
old.apply(null, arguments);
}
}
})();
foo(1);
> a: 1
foo(1,2);
> a: 1
> b: 2
foo(1,2,3)
> a: 1
In short, the use of the IIFE creates a local scope, allowing us to define the private variable old
to store a reference to the initial definition of the function foo
. This function then returns an inline function newFoo
that logs the contents of both two arguments if it is passed exactly two arguments a
and b
or calls the old
function if arguments.length !== 2
. This pattern can be repeated any number of times to endow one variable with several different functional defitions.
With the Date and Time API (java.time classes) built into Java 8 and later, you can use the LocalDate
class.
public static boolean isDateValid(int year, int month, int day) {
boolean dateIsValid = true;
try {
LocalDate.of(year, month, day);
} catch (DateTimeException e) {
dateIsValid = false;
}
return dateIsValid;
}
I would like to use this field in order to return all the records that have been updated in the last 5 minutes.
This means you need to update the date to "now" every time you save the object. Maybe you'll find this useful: Moongoose create-modified plugin
Was just trying to work this out myself, and the solution I came up with was:
<meta name="viewport" content="initial-scale = 1.0,maximum-scale = 1.0" />
This seems to lock the device into 1.0 scale regardless of it's orientation. As a side effect, it does however completely disable user scaling (pinch zooming, etc).
Simply declare it as below if you want to us the STL queue container.
std::queue<myclass*> my_queue;
A quite efficient and platform independent solution would be using the system property for line separators and the StringBuilder class to build strings:
String separator = System.getProperty("line.separator");
String[] lines = {"Line 1", "Line 2" /*, ... */};
StringBuilder builder = new StringBuilder(lines[0]);
for (int i = 1; i < lines.length(); i++) {
builder.append(separator).append(lines[i]);
}
String multiLine = builder.toString();
I made an extension method based on this MSDN article. This is how you can determine whether a socket is still connected.
public static bool IsConnected(this Socket client)
{
bool blockingState = client.Blocking;
try
{
byte[] tmp = new byte[1];
client.Blocking = false;
client.Send(tmp, 0, 0);
return true;
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
{
return true;
}
else
{
return false;
}
}
finally
{
client.Blocking = blockingState;
}
}
Thanks @gniourf_gniourf for detailed comments on my combination of best worlds so far. Sorry for posting code not thoroughly designed and tested. Here is a better try.
# join with separator
join_ws() { local d=$1 s=$2; shift 2 && printf %s "$s${@/#/$d}"; }
This beauty by conception is
Additional examples:
$ join_ws '' a b c
abc
$ join_ws ':' {1,7}{A..C}
1A:1B:1C:7A:7B:7C
$ join_ws -e -e
-e
$ join_ws $'\033[F' $'\n\n\n' 1. 2. 3. $'\n\n\n\n'
3.
2.
1.
$ join_ws $
$
EDIT: This answer is old and likely out of date. Just a heads up so it doesn't lead folks astray. I no longer use Angular so I'm not in a good position to make improvements.
It's actually pretty good logic but you can simplify things a bit.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.model = { name: 'World' };
$scope.name = "Felipe";
});
app.directive('myDirective', function($compile) {
return {
restrict: 'AE', //attribute or element
scope: {
myDirectiveVar: '=',
//bindAttr: '='
},
template: '<div class="some">' +
'<input ng-model="myDirectiveVar"></div>',
replace: true,
//require: 'ngModel',
link: function($scope, elem, attr, ctrl) {
console.debug($scope);
//var textField = $('input', elem).attr('ng-model', 'myDirectiveVar');
// $compile(textField)($scope.$parent);
}
};
});
<body ng-controller="MainCtrl">
This scope value <input ng-model="name">
<my-directive my-directive-var="name"></my-directive>
</body>
.some {
border: 1px solid #cacaca;
padding: 10px;
}
You can see it in action with this Plunker.
Here's what I see:
EDIT As mentioned by Mark in his comment, there's no reason that you can't use ng-model, just to keep with convention.
In general, your directives should use the isolated scope (which you did correctly) and use the '=' type scope if you want a value in your directive to always map to a value in the parent scope.
You can Try using :- git ls-files -s
... Could not load file or assembly 'X' or one of its dependencies ...
Most likely it fails to load another dependency.
you could try to check the dependencies with a dependency walker.
I.e: https://www.dependencywalker.com/
Also check your build configuration (x86 / 64)
Edit: I also had this problem once when I was copying dlls in zip from a "untrusted" network share. The file was locked by Windows and the FileNotFoundException was raised.
See here: Detected DLLs that are from the internet and "blocked" by CASPOL
I suspect you will be able to import 1 GB file through phpmyadmin But you can try by increasing the following value in php.ini and restart the wamp.
post_max_size=1280M
upload_max_filesize=1280M
max_execution_time = 300 //increase time as per your server requirement.
You can also try below command from command prompt, your path may be different as per your MySQL installation.
C:\wamp\bin\mysql\mysql5.5.24\bin\mysql.exe -u root -p db_name < C:\some_path\your_sql_file.sql
You should increase the max_allowed_packet
of mysql in my.ini
to avoid MySQL server gone away
error, something like this
max_allowed_packet = 100M
Check out this jsfiddle.
// note the change... I set the disabled property right away
<input type="submit" id="register" value="Register" disabled="disabled" />
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
} else {
$('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
}
});
})()
The nice thing about this is that it doesn't matter how many input fields you have in your form, it will always keep the button disabled if there is at least 1 that is empty. It also checks emptiness on the .keyup()
which I think makes it more convenient for usability.
There isn't anything built-in, but you can easily create your own extension method to do it:
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");
foreach (T item in source)
{
action(item);
}
}
Anwer is here How to dynamically add a style for text-align using jQuery
this error occur when you change your php version: it's very simple to suppress this error message
To suppress the DEPRECATED Error message, just add below code into your index.php file:
init_set('display_errors',False);
Have you seen the wiki pages on the zxing website? It seems you might find GettingStarted, DeveloperNotes and ScanningViaIntent helpful.
You could always just up or downcase the strings first.
string title = "string":
title.ToUpper().Contains("STRING") // returns true
Oops, just saw that last bit. A case insensitive compare would *
probably*
do the same anyway, and if performance is not an issue, I don't see a problem with creating uppercase copies and comparing those. I could have sworn that I once saw a case-insensitive compare once...
To add new column with some custom value or dynamic value calculation which will be populated based on the existing columns.
e.g.
|ColumnA | ColumnB |
|--------|---------|
| 10 | 15 |
| 10 | 20 |
| 10 | 30 |
and new ColumnC as ColumnA+ColumnB
|ColumnA | ColumnB | ColumnC|
|--------|---------|--------|
| 10 | 15 | 25 |
| 10 | 20 | 30 |
| 10 | 30 | 40 |
using
#to add new column
def customColumnVal(row):
rd=row.asDict()
rd["ColumnC"]=row["ColumnA"] + row["ColumnB"]
new_row=Row(**rd)
return new_row
----------------------------
#convert DF to RDD
df_rdd= input_dataframe.rdd
#apply new fucntion to rdd
output_dataframe=df_rdd.map(customColumnVal).toDF()
input_dataframe
is the dataframe which will get modified and customColumnVal
function is having code to add new column.
The second half of the currently accepted answer is outdated and has two deprecations. First and most important, you can no longer pass a dictionary of dictionaries to the agg
groupby method. Second, never use .ix
.
If you desire to work with two separate columns at the same time I would suggest using the apply
method which implicitly passes a DataFrame to the applied function. Let's use a similar dataframe as the one from above
df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df['group'] = [0, 0, 1, 1]
df
a b c d group
0 0.418500 0.030955 0.874869 0.145641 0
1 0.446069 0.901153 0.095052 0.487040 0
2 0.843026 0.936169 0.926090 0.041722 1
3 0.635846 0.439175 0.828787 0.714123 1
A dictionary mapped from column names to aggregation functions is still a perfectly good way to perform an aggregation.
df.groupby('group').agg({'a':['sum', 'max'],
'b':'mean',
'c':'sum',
'd': lambda x: x.max() - x.min()})
a b c d
sum max mean sum <lambda>
group
0 0.864569 0.446069 0.466054 0.969921 0.341399
1 1.478872 0.843026 0.687672 1.754877 0.672401
If you don't like that ugly lambda column name, you can use a normal function and supply a custom name to the special __name__
attribute like this:
def max_min(x):
return x.max() - x.min()
max_min.__name__ = 'Max minus Min'
df.groupby('group').agg({'a':['sum', 'max'],
'b':'mean',
'c':'sum',
'd': max_min})
a b c d
sum max mean sum Max minus Min
group
0 0.864569 0.446069 0.466054 0.969921 0.341399
1 1.478872 0.843026 0.687672 1.754877 0.672401
apply
and returning a SeriesNow, if you had multiple columns that needed to interact together then you cannot use agg
, which implicitly passes a Series to the aggregating function. When using apply
the entire group as a DataFrame gets passed into the function.
I recommend making a single custom function that returns a Series of all the aggregations. Use the Series index as labels for the new columns:
def f(x):
d = {}
d['a_sum'] = x['a'].sum()
d['a_max'] = x['a'].max()
d['b_mean'] = x['b'].mean()
d['c_d_prodsum'] = (x['c'] * x['d']).sum()
return pd.Series(d, index=['a_sum', 'a_max', 'b_mean', 'c_d_prodsum'])
df.groupby('group').apply(f)
a_sum a_max b_mean c_d_prodsum
group
0 0.864569 0.446069 0.466054 0.173711
1 1.478872 0.843026 0.687672 0.630494
If you are in love with MultiIndexes, you can still return a Series with one like this:
def f_mi(x):
d = []
d.append(x['a'].sum())
d.append(x['a'].max())
d.append(x['b'].mean())
d.append((x['c'] * x['d']).sum())
return pd.Series(d, index=[['a', 'a', 'b', 'c_d'],
['sum', 'max', 'mean', 'prodsum']])
df.groupby('group').apply(f_mi)
a b c_d
sum max mean prodsum
group
0 0.864569 0.446069 0.466054 0.173711
1 1.478872 0.843026 0.687672 0.630494
public class MyArray : List<string> { }
services.Configure<ShipmentDetailsDisplayGidRoles>(Configuration.GetSection("MyArray"));
public SomeController(IOptions<MyArray> myArrayOptions)
{
myArray = myArrayOptions.Value;
}
Caveats: this answer only allows exports color settings.
iTerm => Preferences => Profiles => Colors => Load Presets => Export
Import shall be similar.
1) Replace all new line and tab characters with spaces.
2) Remove all leading and trailing spaces.
UPDATE mytable SET `title` = TRIM(REPLACE(REPLACE(REPLACE(`title`, '\n', ' '), '\r', ' '), '\t', ' '));
You can't search a text field without converting it from text to varchar.
declare @table table (a text)
insert into @table values ('a')
insert into @table values ('a')
insert into @table values ('b')
insert into @table values ('c')
insert into @table values ('d')
select *
from @table
where a ='a'
This give an error:
The data types text and varchar are incompatible in the equal to operator.
Wheras this does not:
declare @table table (a varchar(max))
Interestingly, LIKE
still works, i.e.
where a like '%a%'
In my case i have to concatenate all the account number of a person who's mobile number is unique. So i have used the following query to achieve that.
SELECT GROUP_CONCAT(AccountsNo) as Accounts FROM `tblaccounts` GROUP BY MobileNumber
Query Result is below:
Accounts
93348001,97530801,93348001,97530801
89663501
62630701
6227895144840002
60070021
60070020
60070019
60070018
60070017
60070016
60070015
What is the best practice on where the logic for the @foreach should be at?
Nowhere, just get rid of it. You could use editor or display templates.
So for example:
@foreach (var item in Model.Foos)
{
<div>@item.Bar</div>
}
could perfectly fine be replaced by a display template:
@Html.DisplayFor(x => x.Foos)
and then you will define the corresponding display template (if you don't like the default one). So you would define a reusable template ~/Views/Shared/DisplayTemplates/Foo.cshtml
which will automatically be rendered by the framework for each element of the Foos collection (IEnumerable<Foo> Foos { get; set; }
):
@model Foo
<div>@Model.Bar</div>
Obviously exactly the same conventions apply for editor templates which should be used in case you want to show some input fields allowing you to edit the view model in contrast to just displaying it as readonly.
Yes Jython does this, but it may or may not be what you want
exec
will also return a ChildProcess object that is an EventEmitter.
var exec = require('child_process').exec;
var coffeeProcess = exec('coffee -cw my_file.coffee');
coffeeProcess.stdout.on('data', function(data) {
console.log(data);
});
OR pipe
the child process's stdout to the main stdout.
coffeeProcess.stdout.pipe(process.stdout);
OR inherit stdio using spawn
spawn('coffee -cw my_file.coffee', { stdio: 'inherit' });
The answer given by @7-isnotbad is extremely close, but doesn't count single-word lines. Here's the fix, which seems to account for every possible combination of words, spaces and newlines.
function countWords(s){
s = s.replace(/\n/g,' '); // newlines to space
s = s.replace(/(^\s*)|(\s*$)/gi,''); // remove spaces from start + end
s = s.replace(/[ ]{2,}/gi,' '); // 2 or more spaces to 1
return s.split(' ').length;
}
The easiest way is to simply use the
stmt.setString(position, xml);
methods (for "small" strings which can be easily kept in Java memory), or
try {
java.sql.Clob clob =
oracle.sql.CLOB.createTemporary(
connection, false, oracle.sql.CLOB.DURATION_SESSION);
clob.setString(1, xml);
stmt.setClob(position, clob);
stmt.execute();
}
// Important!
finally {
clob.free();
}
To reset the form call the reset function with the form name in the same structure as like from group
addPost(){
this.newPost = {
title: this.title,
body: this.body
}
this.formName.reset({
"title": '',
"body": ''
});
}
SELECT
t.A,
t.B,
t.C,
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS number
FROM tableZ AS t
See working example at SQLFiddle
Of course, you may want to define the row-numbering order – if so, just swap OVER (ORDER BY (SELECT 1))
for, e.g., OVER (ORDER BY t.C)
, like in a normal ORDER BY
clause.
DB_*/**/*.sql
Here is a variation to perform an action if one or more files exist corresponding to a wildcard filter. That is, you don't know the exact name of the file.
Here, we are looking for "*.sql" files in any sub-directories called "DB_*", recursively. You can adjust the filter to your needs.
NB: Apache Ant 1.7 and higher!
Here is the target to set a property if matching files exist:
<target name="check_for_sql_files">
<condition property="sql_to_deploy">
<resourcecount when="greater" count="0">
<fileset dir="." includes="DB_*/**/*.sql"/>
</resourcecount>
</condition>
</target>
Here is a "conditional" target that only runs if files exist:
<target name="do_stuff" depends="check_for_sql_files" if="sql_to_deploy">
<!-- Do stuff here -->
</target>
More esoteric ways:
Rails.cache.delete_matched("*")
For Redis:
Redis.new.keys.each{ |key| Rails.cache.delete(key) }
An extension of juba's method is to use reformulate
, a function which is explicitly designed for such a task.
## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")
reformulate(xnam, "y")
y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 +
x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 +
x22 + x23 + x24 + x25
For the example in the OP, the easiest solution here would be
# add y variable to data.frame d
d <- cbind(y, d)
reformulate(names(d)[-1], names(d[1]))
y ~ x1 + x2 + x3
or
mod <- lm(reformulate(names(d)[-1], names(d[1])), data=d)
Note that adding the dependent variable to the data.frame in d <- cbind(y, d)
is preferred not only because it allows for the use of reformulate
, but also because it allows for future use of the lm
object in functions like predict
.
Like @wesley says, you have not closed your first <td>
. You opened it two times.
<table class="list1">
<tr>
<td>1</td><td>a</td>
</tr>
<tr>
<td>2</td><td>b</td>
</tr>
<tr>
<td>3</td><td>c</td>
</tr>
</table>
CSS:
.list1 tr:hover{
background-color:#fefefe;
}
There is no JavaScript needed, just complete your HTML code
You can style the option elements to some extent.
Using the * CSS tag you can style the options inside the box that is drawn by the system.
Example:
#ddlProducts *
{
border-radius:15px;
background-color:red;
}
That will look like this:
I wrote a similar answer to a similar question on Stack Overflow, but here is part of that answer.
The new version of Android Studio (2.1) has support for Java 8 features. Here is an extract from the Android Developers blogspot post:
... Android Studio 2.1 release includes support for the new Jack compiler and support for Java 8.
...
To use Java 8 language features when developing with the N Developer Preview, you need to use the Jack compiler. The New Project Wizard [File? New? Project] generates the correct configurations for projects targeting the N.
Android does not support Java 1.8 yet (it only supports up to 1.7), so you cannot use Java 8 features like lambdas.
This answer gives more detail on Android Studio's compatibility; it states:
If you want to use lambdas, one of the major features of Java 8 in Android, you can use gradle-retrolamba
If you want to know more about using gradle-retrolambda
, this answer gives a lot of detail on doing that.
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
I found out what option 2 means. From a repository, you can do:
git checkout-index -a -f --prefix=/destination/path/
The slash at the end of the path is important, otherwise it will result in the files being in /destination with a prefix of 'path'.
Since in a normal situation the index contains the contents of the repository, there is nothing special to do to "read the desired tree into the index". It's already there.
The -a
flag is required to check out all files in the index (I'm not sure what it means to omit this flag in this situation, since it doesn't do what I want). The -f
flag forces overwriting any existing files in the output, which this command doesn't normally do.
This appears to be the sort of "git export" I was looking for.
You could open the SLN file in any text editor (Notepad, etc.) and simply change the project path there.
agf's bytearray solution is workable, but if you find yourself needing to build up more complicated packets using datatypes other than bytes, you can try struct.pack()
. http://docs.python.org/release/3.1.3/library/struct.html
You can clean cache in React Native >= 0.50 and npm > 5 :
watchman watch-del-all &&
rm -rf $TMPDIR/react-native-packager-cache-* &&
rm -rf $TMPDIR/metro-bundler-cache-* &&
rm -rf node_modules/
&& npm cache clean --force &&
npm install &&
npm start -- --reset-cache
Apart from cleaning npm cache you might need to reset simulator or clean build etc.
Did you try deleting and recreating your AVD? You can manually delete the AVD files by going to the directory they're stored in (in your user's /.android/avd subdirectory).
To those suggesting the use of margin-top or padding-top to move the main division below the fixed menu - you don't seem to be testing it completely.
If you set a margin or padding, it will scroll with the page and you will lose lines - go try this page
Looks good, does it not? Highlight a word on the bottom visible line and press page-down - the line with the highlighted word, and a few other lines, will be scrolled under the fixed division.
Margin-top or padding-top WILL position the main division below the fixed division but it all falls flat on its face when you page-down or click the scroll bar to scroll one viewport height of the page.
Same problem if you page-up, lines "fall off" the bottom of the view-port.
Does anyone have an actual fix for THIS problem?
I know how to position things - that's fairly easy if you know the basics about margins, padding, etc. - but how do you prevent the loss of lines when scrolling?
I've looked at a lot of examples of what are claimed to be a properly functioning pages with fixed divisions at the top, but they don't work! They all have problems which scrolling.
I have come across some pages appear to work but if the fixed division is made higher, lines will be lost. I believe I know why they appear to work.
Think in terms of how text on a totally normal (no fancy formatting) page scrolls. Do you see the bottom line when you scroll up or do you see the next line - the bottom one having scrolled off the top of the viewport?
Answer - you see the bottom line scrolled to become the top line.
The fixed menu pages that seem to work really don't. Scroll them and the bottom line is scrolled off the viewport but since the next line is visible, it appears that the fixed division works - but we know better, don't we?
If the fixed division gets higher than the height of one line of text, they fail and lines are lost.
The only pages that I've seen that actually work properly are on sites such as yahoo and I don't have the time, nor inclination, to dig down into what is a lot of CSS, HTML, and JavaScript on the pages to get to the heart of the matter.
So - go to that page and see if you can make changes ("inspect" the elements and make changes to the CSS rules) that fix the scrolling problems.
If you can, come back and share your discovery with world.
My page is a good place to look at what it takes to be able to fix a division at the top, center it (and the main division) and restrict it to a max-width. It may help some of you but I'm sorry I don't have a fix for the scrolling problem
Play with the height of the fix division - make it short enough so that only one line shows and then play with the scrolling. Then make it large enough for two lines and then three and play with the scrolling. You'll see the issues.
Here is a page that is supposed to work but it doesn't - read the very last comment - they describe the problem in a different way but it is the same problem
I just tested the page again in Chrome and it seems to work fairly satisfactorily. With FF the problem exists. Haven't tried IE again, yet.
So - what is different with FF?
Here's a page at cNet which works with chrome and ff - so what are they doing?
More testing with Chrome shows that it fails to fully display the bottom line when scrolled. Just part of the line that was at the bottom is visiable when your scroll - so, still need a fix.
I know it's over a year old, but calling requestFeature()
never solved my problem. In fact I don't call it at all.
It was an issue with inflating the view I suppose. Despite all my searching, I never found a suitable solution until I played around with the different methods of inflating a view.
AlertDialog.Builder is the easy solution but requires a lot of work if you use the onPrepareDialog()
to update that view.
Another alternative is to leverage AsyncTask for dialogs.
A final solution that I used is below:
public class CustomDialog extends AlertDialog {
private View content;
public CustomDialog(Context context) {
super(context);
LayoutInflater li = LayoutInflater.from(context);
content = li.inflate(R.layout.custom_view, null);
setUpAdditionalStuff(); // do more view cleanup
setView(content);
}
private void setUpAdditionalStuff() {
// ...
}
// Call ((CustomDialog) dialog).prepare() in the onPrepareDialog() method
public void prepare() {
setTitle(R.string.custom_title);
setIcon( getIcon() );
// ...
}
}
* Some Additional notes:
I found answer myself; and if someone will face same issue, i hope my solution will work for them as well.
You can try something like this:
Inside customview constructor:
mContext = context;
Next inside customview you can call:
((MainActivity) mContext).updateText( text );
Inside MainAcivity
define:
public void updateText(final String text) {
TextView txtView = (TextView) findViewById(R.id.text);
txtView.setText(text);
}
It works for me.
The answer by Jared Forsyth is horribly wrong and outdated. It follows a whole set of antipatterns such as usage of stopPropagation
, initializing state from props, usage of jQuery, nested objects in state and has some odd dragging
state field. If being rewritten, the solution will be the following, but it still forces virtual DOM reconciliation on every mouse move tick and is not very performant.
UPD. My answer was horribly wrong and outdated. Now the code alleviates issues of slow React component lifecycle by using native event handlers and style updates, uses transform
as it doesn't lead to reflows, and throttles DOM changes through requestAnimationFrame
. Now it's consistently 60 FPS for me in every browser I tried.
const throttle = (f) => {
let token = null, lastArgs = null;
const invoke = () => {
f(...lastArgs);
token = null;
};
const result = (...args) => {
lastArgs = args;
if (!token) {
token = requestAnimationFrame(invoke);
}
};
result.cancel = () => token && cancelAnimationFrame(token);
return result;
};
class Draggable extends React.PureComponent {
_relX = 0;
_relY = 0;
_ref = React.createRef();
_onMouseDown = (event) => {
if (event.button !== 0) {
return;
}
const {scrollLeft, scrollTop, clientLeft, clientTop} = document.body;
// Try to avoid calling `getBoundingClientRect` if you know the size
// of the moving element from the beginning. It forces reflow and is
// the laggiest part of the code right now. Luckily it's called only
// once per click.
const {left, top} = this._ref.current.getBoundingClientRect();
this._relX = event.pageX - (left + scrollLeft - clientLeft);
this._relY = event.pageY - (top + scrollTop - clientTop);
document.addEventListener('mousemove', this._onMouseMove);
document.addEventListener('mouseup', this._onMouseUp);
event.preventDefault();
};
_onMouseUp = (event) => {
document.removeEventListener('mousemove', this._onMouseMove);
document.removeEventListener('mouseup', this._onMouseUp);
event.preventDefault();
};
_onMouseMove = (event) => {
this.props.onMove(
event.pageX - this._relX,
event.pageY - this._relY,
);
event.preventDefault();
};
_update = throttle(() => {
const {x, y} = this.props;
this._ref.current.style.transform = `translate(${x}px, ${y}px)`;
});
componentDidMount() {
this._ref.current.addEventListener('mousedown', this._onMouseDown);
this._update();
}
componentDidUpdate() {
this._update();
}
componentWillUnmount() {
this._ref.current.removeEventListener('mousedown', this._onMouseDown);
this._update.cancel();
}
render() {
return (
<div className="draggable" ref={this._ref}>
{this.props.children}
</div>
);
}
}
class Test extends React.PureComponent {
state = {
x: 100,
y: 200,
};
_move = (x, y) => this.setState({x, y});
// you can implement grid snapping logic or whatever here
/*
_move = (x, y) => this.setState({
x: ~~((x - 5) / 10) * 10 + 5,
y: ~~((y - 5) / 10) * 10 + 5,
});
*/
render() {
const {x, y} = this.state;
return (
<Draggable x={x} y={y} onMove={this._move}>
Drag me
</Draggable>
);
}
}
ReactDOM.render(
<Test />,
document.getElementById('container'),
);
and a bit of CSS
.draggable {
/* just to size it to content */
display: inline-block;
/* opaque background is important for performance */
background: white;
/* avoid selecting text while dragging */
user-select: none;
}
For me, now in 2018. The only thing that fixed my problem (a white glitchy-flicker line running through an image on hover) was applying this to my link element holding the image element that has transform: scale(1.05)
a {
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-transform: translateZ(0) scale(1.0, 1.0);
transform: translateZ(0) scale(1.0, 1.0);
-webkit-filter: blur(0);
filter: blur(0);
}
a > .imageElement {
transition: transform 3s ease-in-out;
}
I don't think it's possible with bluetooth, but you could try looking into WiFi Peer-to-Peer,
which allows one-to-many connections.
try this for sql server
CREATE TRIGGER yourNewTrigger ON yourSourcetable
FOR INSERT
AS
INSERT INTO yourDestinationTable
(col1, col2 , col3, user_id, user_name)
SELECT
'a' , default , null, user_id, user_name
FROM inserted
go
I was testing my application with special characters & was observing the same error. After some research, turns out the % symbol was the cause. I had to modify it to the encoded representation %25. Its all fine now, thanks to the below post
You need to add a Serializable
attribute to the class which you want to serialize.
[Serializable]
public class OrgPermission
Could not get this to work until I put Authorization in single quotes:
axios.get(URL, { headers: { 'Authorization': AuthStr } })
I couldn't find one that worked well for my needs. Written and post @ https://gist.github.com/geoffreyrobichaux/0a7774b424703b6c0fffad309ab0ad0a
function validURL(s) {_x000D_
var regexp = /^(ftp|http|https|chrome|:\/\/|\.|@){2,}(localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\S*:\w*@)*([a-zA-Z]|(\d{1,3}|\.){7}){1,}(\w|\.{2,}|\.[a-zA-Z]{2,3}|\/|\?|&|:\d|@|=|\/|\(.*\)|#|-|%)*$/gum_x000D_
return regexp.test(s);_x000D_
}
_x000D_
Add the below line in your app.gradle file before depencencies block.
configurations.all {
resolutionStrategy {
force 'com.android.support:support-annotations:26.1.0'
}
}
There's also screenshot below for a better understanding.
the configurations.all block will only be helpful if you want your target sdk to be 26. If you can change it to 27 the error will be gone without adding the configuration block in app.gradle file.
There is one more way if you would remove all the test implementation from app.gradle file it would resolve the error and in this also you dont need to add the configuration block nor you need to change the targetsdk version.
Hope that helps.
I'm facing the same issue here.
If this occurs right after you run brew install yarn
try running yarn global add npm
and voilà - fixed!
Try with below logic
driver.get("http://www.labmultis.info/jpecka.portal-exdrazby/index.php?c1=2&a=s&aa=&ta=1");
List<WebElement> allElements=driver.findElements(By.cssSelector(".list.list-categories li"));
for(WebElement ele :allElements) {
System.out.println("Name + Number===>"+ele.getText());
String s=ele.getText();
s=s.substring(s.indexOf("(")+1, s.indexOf(")"));
System.out.println("Number==>"+s);
}
====Output======
Name + Number===>Vše (950)
Number==>950
Name + Number===>Byty (181)
Number==>181
Name + Number===>Domy (512)
Number==>512
Name + Number===>Pozemky (172)
Number==>172
Name + Number===>Chaty (28)
Number==>28
Name + Number===>Zemedelské objekty (5)
Number==>5
Name + Number===>Komercní objekty (30)
Number==>30
Name + Number===>Ostatní (22)
Number==>22
Iterate over the array and do whatever you want with the individual values.
foreach ($array as $key => $value) {
echo $key . ' contains ' . $value . '<br/>';
}
You can use window.location.reload();
in your componentDidMount()
lifecycle method. If you are using react-router
, it has a refresh method to do that.
Edit: If you want to do that after a data update, you might be looking to a re-render
not a reload
and you can do that by using this.setState(). Here is a basic example of it to fire a re-render
after data is fetched.
import React from 'react'
const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;
class MyComponent extends React.Component {
state = {
users: null
}
componentDidMount() {
fetch(url)
.then(response => response.json())
.then(users => this.setState({users: users}));
}
render() {
const {users} = this.state;
if (users) {
return (
<ul>
{users.map(user => <li>{user.name}</li>)}
</ul>
)
} else {
return (<h1>Loading ...</h1>)
}
}
}
export default MyComponent;
A List is more flexible.... so better to List than array
You can use title
attribute.
<img src="smiley.gif" title="Smiley face"/>
You can change the source of image as you want.
And as @Gray commented:
You can also use the title
on other things like <a ...
anchors, <p>
, <div>
, <input>
, etc.
See: this
I got a different idea:
First:
pip install python-dotenv
Install the python-dotenv
module, which will read local preference for your project environment.
Second:
Add .flaskenv
file in your project directory. Add following code:
FLASK_ENV=development
It's done!
With this config for your Flask project, when you run flask run
and you will see this output in your terminal:
And when you edit your file, just save the change. You will see auto-reload is there for you:
With more explanation:
Of course you can manually hit export FLASK_ENV=development
every time you need. But using different configuration file to handle the actual working environment seems like a better solution, so I strongly recommend this method I use.
java.exe
is the console app while javaw.exe
is windows app (console-less). You can't have Console
with javaw.exe
.
Use:
git remote add upstream ORIGINAL_REPOSITORY_URL
This will set your upstream to the repository you forked from. Then do this:
git fetch upstream
This will fetch all the branches including master from the original repository.
Merge this data in your local master branch:
git merge upstream/master
Push the changes to your forked repository i.e. to origin:
git push origin master
Voila! You are done with the syncing the original repository.
try this way Simply loop through that, building your own array. This code assumes it's an array of strings, it shouldn't be hard to modify to suit your particular array structure.
JSONArray jsonArray = new JSONArray(jsonArrayString);
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
list.add( jsonArray.getString(i) );
UUID is similar in notion to port numbers in Internet. However, the difference between Bluetooth and the Internet is that, in Bluetooth, port numbers are assigned dynamically by the SDP (service discovery protocol) server during runtime where each UUID is given a port number. Other devices will ask the SDP server, who is registered under a reserved port number, about the available services on the device and it will reply with different services distinguishable from each other by being registered under different UUIDs.
My first post...
I tried this: change 'tr' for 'td' and you will get all HTMLRowElements into an Array, and using textContent will change from Object into String
var dataArray = [];
var data = table.find('td'); //Get All HTML td elements
// Save important data into new Array
for (var i = 0; i <= data.size() - 1; i = i + 4)
{
dataArray.push(data[i].textContent, data[i + 1].textContent, data[i + 2].textContent);
}
The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:
Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();
This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.
If you absolutely need to only use one regex then
/(?=.*?(string1))(?=.*?(string2))/is
i modifier = case-insensitive
.*? Lazy evaluation for any character (matches as few as possible)
?= for Positive LookAhead it has to match somewhere
s modifier = .(period) also accepts line breaks
for me: the function of a method and a function is the same if I agree that:
Just like any piece of code you may have objects you put in and you may have an object that comes as a result. During doing that they might change the state of an object but that would not change their basic functioning for me.
There might be a definition differencing in calling functions of objects or other codes. But isn't that something for a verbal differenciations and that's why people interchange them? The mentions example of computation I would be careful with. because I hire employes to do my calculations:
new Employer().calculateSum( 8, 8 );
By doing it that way I can rely on an employer being responsible for calculations. If he wants more money I free him and let the carbage collector's function of disposing unused employees do the rest and get a new employee.
Even arguing that a method is an objects function and a function is unconnected computation will not help me. The function descriptor itself and ideally the function's documentation will tell me what it needs and what it may return. The rest, like manipulating some object's state is not really transparent to me. I do expect both functions and methods to deliver and manipulate what they claim to without needing to know in detail how they do it. Even a pure computational function might change the console's state or append to a logfile.
TS offers getters and setters which allow object properties to have more control of how they are accessed (getter) or updated (setter) outside of the object. Instead of directly accessing or updating the property a proxy function is called.
Example:
class Person {
constructor(name: string) {
this._name = name;
}
private _name: string;
get name() {
return this._name;
}
// first checks the length of the name and then updates the name.
set name(name: string) {
if (name.length > 10) {
throw new Error("Name has a max length of 10");
}
this._name = name;
}
doStuff () {
this._name = 'foofooooooofoooo';
}
}
const person = new Person('Willem');
// doesn't throw error, setter function not called within the object method when this._name is changed
person.doStuff();
// throws error because setter is called and name is longer than 10 characters
person.name = 'barbarbarbarbarbar';
The conversion of your code to Swift 4 can also be done this way:
let str = "Hello, playground"
let index = str.index(of: ",")!
let substr = str.prefix(upTo: index)
You can use the code below to have a new string:
let newString = String(str.prefix(upTo: index))
I tried using the dtypes=[datetime, ...] option, but
import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = [datetime, datetime, str, float]
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)
I encountered the following error:
TypeError: data type not understood
The only change I had to make is to replace datetime with datetime.datetime
import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = [datetime.datetime, datetime.datetime, str, float]
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)
const int * ptr;
means that the pointed data is constant and immutable but the pointer is not.
int * const ptr;
means that the pointer is constant and immutable but the pointed data is not.
Pay attention:
A Java char
corresponds to a UTF-16 code unit, and in some cases two consecutive char
s (a so-called surrogate pair) are needed for one real Unicode character (codepoint).
XORing two valid UTF-16 sequences (i.e. Java Strings char
by char
, or byte by byte after encoding to UTF-16) does not necessarily give you another valid UTF-16 string - you may have unpaired surrogates as a result. (It would still be a perfectly usable Java String, just the codepoint-concerning methods could get confused, and the ones that convert to other encodings for output and similar.)
The same is valid if you first convert your Strings to UTF-8 and then XOR these bytes - here you quite probably will end up with a byte sequence which is not valid UTF-8, if your Strings were not already both pure ASCII strings.
Even if you try to do it right and iterate over your two Strings by codepoint and try to XOR the codepoints, you can end up with codepoints outside the valid range (for example, U+FFFFF
(plane 15) XOR U+10000
(plane 16) = U+1FFFFF
(which would the last character of plane 31), way above the range of existing codepoints. And you could also end up this way with codepoints reserved for surrogates (= not valid ones).
If your strings only contain chars < 128, 256, 512, 1024, 2048, 4096, 8192, 16384, or 32768, then the (char-wise) XORed strings will be in the same range, and thus certainly not contain any surrogates. In the first two cases you could also encode your String as ASCII or Latin-1, respectively, and have the same XOR-result for the bytes. (You still can end up with control chars, which may be a problem for you.)
What I'm finally saying here: don't expect the result of encrypting Strings to be a valid string again - instead, simply store and transmit it as a byte[]
(or a stream of bytes). (And yes, convert to UTF-8 before encrypting, and from UTF-8 after decrypting).
I always use an easy method. Just add below lines to \public\index.php
file. You don't have to use a middleware I think.
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
I have tried &, but it didn't work. Based on Wim ten Brink's answer I tried &amp and it worked.
One of my fellow developers suggested me to use & and that worked regardless of how many times it may be rendered.
Have a look at the Python tutorial on tuples:
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:
>>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',)
If you put just a pair of parentheses around your string object, they will only turn that expression into an parenthesized expression (emphasis added):
A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list.
An empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the rules for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object).
Note that tuples are not formed by the parentheses, but rather by use of the comma operator. The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.
That is (assuming Python 2.7),
a = 'Quattro TT'
print tuple(a) # <-- you create a tuple from a sequence
# (which is a string)
print tuple([a]) # <-- you create a tuple from a sequence
# (which is a list containing a string)
print tuple(list(a)) # <-- you create a tuple from a sequence
# (which you create from a string)
print (a,) # <-- you create a tuple containing the string
print (a) # <-- it's just the string wrapped in parentheses
The output is as expected:
('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')
('Quattro TT',)
('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')
('Quattro TT',)
Quattro TT
To add some notes on the print statement. When you try to create a single-element tuple as part of a print statement in Python 2.7 (as in print (a,)
) you need to use the parenthesized form, because the trailing comma of print a,
would else be considered part of the print statement and thus cause the newline to be suppressed from the output and not a tuple being created:
A '\n' character is written at the end, unless the print statement ends with a comma.
In Python 3.x most of the above usages in the examples would actually raise SyntaxError
, because in Python 3 print
turns into a function (you need to add an extra pair of parentheses).
But especially this may cause confusion:
print (a,) # <-- this prints a tuple containing `a` in Python 2.x
# but only `a` in Python 3.x
states = "Alaska Alabama Arkansas American Samoa Arizona California Colorado"
states_list = states.split (' ')
First, I should say that the easiest way to do this is to use the prename or rename commands.
On Ubuntu, OSX (Homebrew package rename
, MacPorts package p5-file-rename
), or other systems with perl rename (prename):
rename s/0000/000/ F0000*
or on systems with rename from util-linux-ng, such as RHEL:
rename 0000 000 F0000*
That's a lot more understandable than the equivalent sed command.
But as for understanding the sed command, the sed manpage is helpful. If you run man sed and search for & (using the / command to search), you'll find it's a special character in s/foo/bar/ replacements.
s/regexp/replacement/
Attempt to match regexp against the pattern space. If success-
ful, replace that portion matched with replacement. The
replacement may contain the special character & to refer to that
portion of the pattern space which matched, and the special
escapes \1 through \9 to refer to the corresponding matching
sub-expressions in the regexp.
Therefore, \(.\)
matches the first character, which can be referenced by \1
.
Then .
matches the next character, which is always 0.
Then \(.*\)
matches the rest of the filename, which can be referenced by \2
.
The replacement string puts it all together using &
(the original
filename) and \1\2
which is every part of the filename except the 2nd
character, which was a 0.
This is a pretty cryptic way to do this, IMHO. If for some reason the rename command was not available and you wanted to use sed to do the rename (or perhaps you were doing something too complex for rename?), being more explicit in your regex would make it much more readable. Perhaps something like:
ls F00001-0708-*|sed 's/F0000\(.*\)/mv & F000\1/' | sh
Being able to see what's actually changing in the s/search/replacement/ makes it much more readable. Also it won't keep sucking characters out of your filename if you accidentally run it twice or something.
I was getting this from webpack lazy loading like this
import Loader from 'some-loader-component';
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
fallback: Loader, // warning
});
render() {
return <WishlistPageComponent />;
}
// changed to this then it's suddenly fine
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
fallback: '', // all good
});
aggregate(speed~dive,data=df,FUN=mean)
dive speed
1 dive1 0.7059729
2 dive2 0.5473777
After the first if statement instead of typing "if" type "elif" and then it should work.
Ex.
` while 1:
date=input("Example: March 21 | What is the date? ")
if date=="June 21":
sd="23.5° North Latitude
elif date=="March 21" | date=="September 21":
sd="0° Latitude"
elif date=="December 21":
sd="23.5° South Latitude"
elif sd:
print sd `
\n
creates a new line in Java. Don't use spaces before or after \n
.
Example: printing It creates\na new line
outputs
It creates
a new line.
Adding a new answer just as a reference for future researchers and as nobody mentioned that yet I think it's valid.
Another good option is ng-grid http://angular-ui.github.io/ng-grid/.
And there's a beta version (http://ui-grid.info/) available already with some improvements:
UPDATE:
It seems UI GRID is not beta anymore.
With the 3.0 release, the repository has been renamed from "ng-grid" to "ui-grid".
I tried all the aforementioned solutions and none works. I guess Instagram has accelerated their changes. I tried, however, the browser console method and played around a bit and found this command that gave me the user ID.
window._sharedData.entry_data.ProfilePage[0].graphql.user.id
You just visit a profile's page and enter this command in the console. You might need to refresh the page for this to work though. (I had to post this as an answer, because of my low reputation)
Spring has org.springframework.core.io.Resource which is designed for such situations. From context.xml you can pass classpath to the bean
<bean class="test.Test1">
<property name="path" value="classpath:/test/test1.xml" />
</bean>
and you get it in your bean as Resource:
public void setPath(Resource path) throws IOException {
File file = path.getFile();
System.out.println(file);
}
output
D:\workspace1\spring\target\test-classes\test\test1.xml
Now you can use it in new FileReader(file)
strncpy(otherString, someString, 5);
Don't forget to allocate memory for otherString.
You can do both tasks (the upload and the command execution) using WinSCP. Use WinSCP script like:
option batch abort
option confirm off
open your_session
put %1%
call script.sh
exit
Reference for the call
command:
https://winscp.net/eng/docs/scriptcommand_call
Reference for the %1%
syntax:
https://winscp.net/eng/docs/scripting#syntax
You can then run the script like:
winscp.exe /console /script=script_path\upload.txt /parameter file_to_upload.dat
Actually, you can put a shortcut to the above command to the Windows Explorer's Send To menu, so that you can then just right-click any file and go to the Send To > Upload using WinSCP and Execute Remote Command (=name of the shortcut).
For that, go to the folder %USERPROFILE%\SendTo
and create a shortcut with the following target:
winscp_path\winscp.exe /console /script=script_path\upload.txt /parameter %1
Just a little more clarification: A property without 'get','set' won't be able to be bound
I'm facing the case just like the asker's case. And I must have the following things in order for the bind to work properly:
//(1) Declare a property with 'get','set' in code behind
public partial class my_class:Window {
public String My_Property { get; set; }
...
//(2) Initialise the property in constructor of code behind
public partial class my_class:Window {
...
public my_class() {
My_Property = "my-string-value";
InitializeComponent();
}
//(3) Set data context in window xaml and specify a binding
<Window ...
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<TextBlock Text="{Binding My_Property}"/>
</Window>
http://sfml-dev.org/documentation/2.0/classsf_1_1Music.php
SFML does not have mp3 support as another has suggested. What I always do is use Audacity and make all my music into ogg, and leave all my sound effects as wav.
Loading and playing a wav is simple (crude example):
http://www.sfml-dev.org/tutorials/2.0/audio-sounds.php
#include <SFML/Audio.hpp>
...
sf::SoundBuffer buffer;
if (!buffer.loadFromFile("sound.wav")){
return -1;
}
sf::Sound sound;
sound.setBuffer(buffer);
sound.play();
Streaming an ogg music file is also simple:
#include <SFML/Audio.hpp>
...
sf::Music music;
if (!music.openFromFile("music.ogg"))
return -1; // error
music.play();
Based on @ganaraj 's answer, and @dnc253 's answer, I just made a simple "directive" for the tree structure having selecting, adding, deleting, and editing feature.
Jsfiddle: http://jsfiddle.net/yoshiokatsuneo/9dzsms7y/
HTML:
<script type="text/ng-template" id="tree_item_renderer.html">
<div class="node" ng-class="{selected: data.selected}" ng-click="select(data)">
<span ng-click="data.hide=!data.hide" style="display:inline-block; width:10px;">
<span ng-show="data.hide && data.nodes.length > 0" class="fa fa-caret-right">+</span>
<span ng-show="!data.hide && data.nodes.length > 0" class="fa fa-caret-down">-</span>
</span>
<span ng-show="!data.editting" ng-dblclick="edit($event)" >{{data.name}}</span>
<span ng-show="data.editting"><input ng-model="data.name" ng-blur="unedit()" ng-focus="f()"></input></span>
<button ng-click="add(data)">Add node</button>
<button ng-click="delete(data)" ng-show="data.parent">Delete node</button>
</div>
<ul ng-show="!data.hide" style="list-style-type: none; padding-left: 15px">
<li ng-repeat="data in data.nodes">
<recursive><sub-tree data="data"></sub-tree></recursive>
</li>
</ul>
</script>
<ul ng-app="Application" style="list-style-type: none; padding-left: 0">
<tree data='{name: "Node", nodes: [],show:true}'></tree>
</ul>
JavaScript:
angular.module("myApp",[]);
/* https://stackoverflow.com/a/14657310/1309218 */
angular.module("myApp").
directive("recursive", function($compile) {
return {
restrict: "EACM",
require: '^tree',
priority: 100000,
compile: function(tElement, tAttr) {
var contents = tElement.contents().remove();
var compiledContents;
return function(scope, iElement, iAttr) {
if(!compiledContents) {
compiledContents = $compile(contents);
}
compiledContents(scope,
function(clone) {
iElement.append(clone);
});
};
}
};
});
angular.module("myApp").
directive("subTree", function($timeout) {
return {
restrict: 'EA',
require: '^tree',
templateUrl: 'tree_item_renderer.html',
scope: {
data: '=',
},
link: function(scope, element, attrs, treeCtrl) {
scope.select = function(){
treeCtrl.select(scope.data);
};
scope.delete = function() {
scope.data.parent.nodes.splice(scope.data.parent.nodes.indexOf(scope.data), 1);
};
scope.add = function() {
var post = scope.data.nodes.length + 1;
var newName = scope.data.name + '-' + post;
scope.data.nodes.push({name: newName,nodes: [],show:true, parent: scope.data});
};
scope.edit = function(event){
scope.data.editting = true;
$timeout(function(){event.target.parentNode.querySelector('input').focus();});
};
scope.unedit = function(){
scope.data.editting = false;
};
}
};
});
angular.module("myApp").
directive("tree", function(){
return {
restrict: 'EA',
template: '<sub-tree data="data" root="data"></sub-tree>',
controller: function($scope){
this.select = function(data){
if($scope.selected){
$scope.selected.selected = false;
}
data.selected = true;
$scope.selected = data;
};
},
scope: {
data: '=',
}
}
});
You can use Git GUI on Windows, see instructions:
Recall that in Dijkstra's algorithm, once a vertex is marked as "closed" (and out of the open set) -it assumes that any node originating from it will lead to greater distance so, the algorithm found the shortest path to it, and will never have to develop this node again, but this doesn't hold true in case of negative weights.
Using CSS only:
#blockContainer {
display: -webkit-box;
display: -moz-box;
display: box;
-webkit-box-orient: vertical;
-moz-box-orient: vertical;
box-orient: vertical;
}
#blockA {
-webkit-box-ordinal-group: 2;
-moz-box-ordinal-group: 2;
box-ordinal-group: 2;
}
#blockB {
-webkit-box-ordinal-group: 3;
-moz-box-ordinal-group: 3;
box-ordinal-group: 3;
}
<div id="blockContainer">
<div id="blockA">Block A</div>
<div id="blockB">Block B</div>
<div id="blockC">Block C</div>
</div>
Use t
function:
t(colnames(df))
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "var1" "var2" "var3" "var4" "var5" "var6"
You just need a loop that iterates the number of times given by n
and prints a space each time. This would do:
while (n--) {
std::cout << ' ';
}
Go to phpMyAdmin/config.inc.php
edit the line
$cfg['Servers'][$i]['password'] = '';
to
$cfg['Servers'][$i]['password'] = 'yourpassword';
This problem might occur due to setting of a password to root, thus phpmyadmin is not able to connect to the mysql database.
And the last thing change
$cfg['Servers'][$i]['extension'] = 'mysql';
to
$cfg['Servers'][$i]['extension'] = 'mysqli';
Now restart your server. and see.
If your entity class isn't in the same package as your main class, you can use @EntityScan
annotation in the main class, specifying the Entity you want to save or package too. Like your model package.
About:
spring.jpa.hibernate.ddl-auto = create
You can use the option update
. It won't erase any data, and will create tables in the same way.
The easiest way to output a single character is to simply use the putchar
function. After all, that's it's sole purpose and it cannot do anything else. It cannot be simpler than that.
@S.Lott: You inspired me to write a timeit app.
I figured it would also vary based on the number of partitions (number of iterators within the container list) -- your comment didn't mention how many partitions there were of the thirty items. This plot is flattening a thousand items in every run, with varying number of partitions. The items are evenly distributed among the partitions.
Code (Python 2.6):
#!/usr/bin/env python2.6
"""Usage: %prog item_count"""
from __future__ import print_function
import collections
import itertools
import operator
from timeit import Timer
import sys
import matplotlib.pyplot as pyplot
def itertools_flatten(iter_lst):
return list(itertools.chain(*iter_lst))
def itertools_iterable_flatten(iter_iter):
return list(itertools.chain.from_iterable(iter_iter))
def reduce_flatten(iter_lst):
return reduce(operator.add, map(list, iter_lst))
def reduce_lambda_flatten(iter_lst):
return reduce(operator.add, map(lambda x: list(x), [i for i in iter_lst]))
def comprehension_flatten(iter_lst):
return list(item for iter_ in iter_lst for item in iter_)
METHODS = ['itertools', 'itertools_iterable', 'reduce', 'reduce_lambda',
'comprehension']
def _time_test_assert(iter_lst):
"""Make sure all methods produce an equivalent value.
:raise AssertionError: On any non-equivalent value."""
callables = (globals()[method + '_flatten'] for method in METHODS)
results = [callable(iter_lst) for callable in callables]
if not all(result == results[0] for result in results[1:]):
raise AssertionError
def time_test(partition_count, item_count_per_partition, test_count=10000):
"""Run flatten methods on a list of :param:`partition_count` iterables.
Normalize results over :param:`test_count` runs.
:return: Mapping from method to (normalized) microseconds per pass.
"""
iter_lst = [[dict()] * item_count_per_partition] * partition_count
print('Partition count: ', partition_count)
print('Items per partition:', item_count_per_partition)
_time_test_assert(iter_lst)
test_str = 'flatten(%r)' % iter_lst
result_by_method = {}
for method in METHODS:
setup_str = 'from test import %s_flatten as flatten' % method
t = Timer(test_str, setup_str)
per_pass = test_count * t.timeit(number=test_count) / test_count
print('%20s: %.2f usec/pass' % (method, per_pass))
result_by_method[method] = per_pass
return result_by_method
if __name__ == '__main__':
if len(sys.argv) != 2:
raise ValueError('Need a number of items to flatten')
item_count = int(sys.argv[1])
partition_counts = []
pass_times_by_method = collections.defaultdict(list)
for partition_count in xrange(1, item_count):
if item_count % partition_count != 0:
continue
items_per_partition = item_count / partition_count
result_by_method = time_test(partition_count, items_per_partition)
partition_counts.append(partition_count)
for method, result in result_by_method.iteritems():
pass_times_by_method[method].append(result)
for method, pass_times in pass_times_by_method.iteritems():
pyplot.plot(partition_counts, pass_times, label=method)
pyplot.legend()
pyplot.title('Flattening Comparison for %d Items' % item_count)
pyplot.xlabel('Number of Partitions')
pyplot.ylabel('Microseconds')
pyplot.show()
Edit: Decided to make it community wiki.
Note: METHODS
should probably be accumulated with a decorator, but I figure it'd be easier for people to read this way.
Use .on('input'...
to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.
For static and dynamic inputs:
$(document).on('input', '.my-class', function(){
alert('Input changed');
});
For static inputs only:
$('.my-class').on('input', function(){
alert('Input changed');
});
JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/
If you're pulling dynamic records it's better to have 1 php file that creates a json representation and not create a file each time.
my_json.php
$array = array(
'title' => $title,
'url' => $url
);
echo stripslashes(json_encode($array));
Then in your script set the path to the file my_json.php
The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql
No, just use the value directly:
begin
if (select count(*) from table) > 0 then
update table
end if;
end;
Note there is no need for an "else".
You can simply do it all within the update statement (ie no if
construct):
update table
set ...
where ...
and exists (select 'x' from table where ...)
I believe the author was looking for an equivalent method via the IDE that would generate the code behind and make sure all parameters were in place, etc. Found this from MS:
Creating Event Handlers on the Windows Forms Designer
Coming from a VB background myself, this is what I was looking for, here is the brief version for the click adverse:
- Click the form or control that you want to create an event handler for.
- In the Properties window, click the Events button
- In the list of available events, click the event that you want to create an event handler for.
- In the box to the right of the event name, type the name of the handler and press ENTER
Could you not have simply added:
align-items:center;
to a new class in your row div. Essentially:
<div class="row align_center">
.align_center { align-items:center; }
You should use the OpenFileDialog class like this
Dim fd As OpenFileDialog = New OpenFileDialog()
Dim strFileName As String
fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True
If fd.ShowDialog() = DialogResult.OK Then
strFileName = fd.FileName
End If
Then you can use the File class.
You could also do:
Regions.query({}, function(response) {
$scope.regions = response;
// Do stuff that depends on $scope.regions here
});
I also have it and while waiting on them to fix it, I added this shame css :
body { overflow-x: hidden;}
it's an horrible alternative, but it work. I'll be happy to remove it when they'll have fixed the issue.
An other alternative, as pointed out in the issue, is to override .row
:
.row {
margin-left: 0px;
margin-right: 0px;
}
I've written the following code in order to generate the mode.
MODE <- function(dataframe){
DF <- as.data.frame(dataframe)
MODE2 <- function(x){
if (is.numeric(x) == FALSE){
df <- as.data.frame(table(x))
df <- df[order(df$Freq), ]
m <- max(df$Freq)
MODE1 <- as.vector(as.character(subset(df, Freq == m)[, 1]))
if (sum(df$Freq)/length(df$Freq)==1){
warning("No Mode: Frequency of all values is 1", call. = FALSE)
}else{
return(MODE1)
}
}else{
df <- as.data.frame(table(x))
df <- df[order(df$Freq), ]
m <- max(df$Freq)
MODE1 <- as.vector(as.numeric(as.character(subset(df, Freq == m)[, 1])))
if (sum(df$Freq)/length(df$Freq)==1){
warning("No Mode: Frequency of all values is 1", call. = FALSE)
}else{
return(MODE1)
}
}
}
return(as.vector(lapply(DF, MODE2)))
}
Let's try it:
MODE(mtcars)
MODE(CO2)
MODE(ToothGrowth)
MODE(InsectSprays)
I also faced the same issue today in my running code. Well, I found a lot of answers here. But the important thing I want to mention is that this error message is quite ambiguous and doesn't explicitly point out the exact error.
Some faced it due to browser extensions, some due to incorrect URL patterns and I faced this due to an error in my formGroup instance used in a pop-up in that screen. So, I would suggest everyone that before making any new changes in your code, please debug your code and verify that you don't have any such errors. You will certainly find the actual reason by debugging.
If nothing else works then check your URL as that is the most common reason for this issue.
I wrote a function to do this in R. The method is the same as above, but I needed to do this a bunch of times in R, so I thought I'd share in case it helps anybody.
convertRange <- function(
oldValue,
oldRange = c(-16000.00, 16000.00),
newRange = c(0, 100),
returnInt = TRUE # the poster asked for an integer, so this is an option
){
oldMin <- oldRange[1]
oldMax <- oldRange[2]
newMin <- newRange[1]
newMax <- newRange[2]
newValue = (((oldValue - oldMin)* (newMax - newMin)) / (oldMax - oldMin)) + newMin
if(returnInt){
return(round(newValue))
} else {
return(newValue)
}
}
At date git prompts:
use "git rm --cached <file>..." to unstage
if files were not in the repo. It unstages the files keeping them there.use "git reset HEAD <file>..." to unstage
if the files were in the repo, and you are adding them as modified. It keeps the files as they are, and unstages them.At my knowledge you cannot undo the git add --
but you can unstage a list of files as mentioned above.
Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.
>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False
Edit
Further explanation: How does Python compare string and int?
I have solved it in a much simpler way
UIImage *placeholder = [UIImage imageNamed:@"OriginalImage.png"];
self.yourImageview.image = [UIImage imageWithCGImage:[placeholder CGImage] scale:(placeholder.scale * 1.5)
orientation:(placeholder.imageOrientation)];
multiplier of the scale will define the scalling of the image,more the multiplier smaller the image. so You can check what fits your screen.
Or you can also get the multiplire by dividing imagewidth/screenwidth.
I had this issue on a server of mine that was set up with it's regular IP and a failover IP. The failover IP did not point to the server at this time. I had to remove the failover IP from the server configuration in /etc/netplan/01-netcfg.yaml
. Pointing the failover IP to that server would have probably solved the issue as well.
I was trying to create a borderless window with WindowStyle="None"
but when I tested it, seems that appears a white bar in the top, after some research it appears to be a "Resize border", here is an image (I remarked in yellow):
After some research over the internet, and lots of difficult non xaml solutions, all the solutions that I found were code behind in C# and lots of code lines, I found indirectly the solution here: Maximum custom window loses drop shadow effect
<WindowChrome.WindowChrome>
<WindowChrome
CaptionHeight="0"
ResizeBorderThickness="5" />
</WindowChrome.WindowChrome>
Note : You need to use .NET 4.5 framework, or if you are using an older version use WPFShell, just reference the shell and use Shell:WindowChrome.WindowChrome
instead.
I used the WindowChrome
property of Window, if you use this that white "resize border" disappears, but you need to define some properties to work correctly.
CaptionHeight: This is the height of the caption area (headerbar) that allows for the Aero snap, double clicking behaviour as a normal title bar does. Set this to 0 (zero) to make the buttons work.
ResizeBorderThickness: This is thickness at the edge of the window which is where you can resize the window. I put to 5 because i like that number, and because if you put zero its difficult to resize the window.
After using this short code the result is this:
And now, the white border disappeared without using ResizeMode="NoResize"
and AllowsTransparency="True"
, also it shows a shadow in the window.
Later I will explain how to make to work the buttons (I didn't used images for the buttons) easily with simple and short code, Im new and i think that I can post to codeproject, because here I didn't find the place to post the tutorial.
Maybe there is another solution (I know that there are hard and difficult solutions for noobs like me) but this works for my personal projects.
Here is the complete code
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Concursos"
mc:Ignorable="d"
Title="Concuros" Height="350" Width="525"
WindowStyle="None"
WindowState="Normal"
ResizeMode="CanResize"
>
<WindowChrome.WindowChrome>
<WindowChrome
CaptionHeight="0"
ResizeBorderThickness="5" />
</WindowChrome.WindowChrome>
<Grid>
<Rectangle Fill="#D53736" HorizontalAlignment="Stretch" Height="35" VerticalAlignment="Top" PreviewMouseDown="Rectangle_PreviewMouseDown" />
<Button x:Name="Btnclose" Content="r" HorizontalAlignment="Right" VerticalAlignment="Top" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>
<Button x:Name="Btnmax" Content="2" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,0,35,0" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>
<Button x:Name="Btnmin" Content="0" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,0,70,0" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>
</Grid>
Thank you!
I just had to play with the divo's ConsoleSpinner
class. Mine is nowhere near as concise, but it just didn't sit well with me that users of that class have to write their own while(true)
loop. I'm shooting for an experience more like this:
static void Main(string[] args)
{
Console.Write("Working....");
ConsoleSpinner spin = new ConsoleSpinner();
spin.Start();
// Do some work...
spin.Stop();
}
And I realized it with the code below. Since I don't want my Start()
method to block, I don't want the user to have to worry about writing a while(spinFlag)
-like loop, and I want to allow multiple spinners at the same time I had to spawn a separate thread to handle the spinning. And that means the code has to be a lot more complicated.
Also, I haven't done that much multi-threading so it's possible (likely even) that I've left a subtle bug or three in there. But it seems to work pretty well so far:
public class ConsoleSpinner : IDisposable
{
public ConsoleSpinner()
{
CursorLeft = Console.CursorLeft;
CursorTop = Console.CursorTop;
}
public ConsoleSpinner(bool start)
: this()
{
if (start) Start();
}
public void Start()
{
// prevent two conflicting Start() calls ot the same instance
lock (instanceLocker)
{
if (!running )
{
running = true;
turner = new Thread(Turn);
turner.Start();
}
}
}
public void StartHere()
{
SetPosition();
Start();
}
public void Stop()
{
lock (instanceLocker)
{
if (!running) return;
running = false;
if (! turner.Join(250))
turner.Abort();
}
}
public void SetPosition()
{
SetPosition(Console.CursorLeft, Console.CursorTop);
}
public void SetPosition(int left, int top)
{
bool wasRunning;
//prevent other start/stops during move
lock (instanceLocker)
{
wasRunning = running;
Stop();
CursorLeft = left;
CursorTop = top;
if (wasRunning) Start();
}
}
public bool IsSpinning { get { return running;} }
/* --- PRIVATE --- */
private int counter=-1;
private Thread turner;
private bool running = false;
private int rate = 100;
private int CursorLeft;
private int CursorTop;
private Object instanceLocker = new Object();
private static Object console = new Object();
private void Turn()
{
while (running)
{
counter++;
// prevent two instances from overlapping cursor position updates
// weird things can still happen if the main ui thread moves the cursor during an update and context switch
lock (console)
{
int OldLeft = Console.CursorLeft;
int OldTop = Console.CursorTop;
Console.SetCursorPosition(CursorLeft, CursorTop);
switch (counter)
{
case 0: Console.Write("/"); break;
case 1: Console.Write("-"); break;
case 2: Console.Write("\\"); break;
case 3: Console.Write("|"); counter = -1; break;
}
Console.SetCursorPosition(OldLeft, OldTop);
}
Thread.Sleep(rate);
}
lock (console)
{ // clean up
int OldLeft = Console.CursorLeft;
int OldTop = Console.CursorTop;
Console.SetCursorPosition(CursorLeft, CursorTop);
Console.Write(' ');
Console.SetCursorPosition(OldLeft, OldTop);
}
}
public void Dispose()
{
Stop();
}
}
You say:
when i do
nan - inf
i dont get-inf
i getnan
This is because any operation containing NaN
as an operand would return NaN
.
A comparison with NaN
would return an unordered result.
>>> float('Inf') == float('Inf')
True
>>> float('NaN') == float('NaN')
False
The whole point of HttpOnly cookies is that they can't be accessed by JavaScript.
The only way (except for exploiting browser bugs) for your script to read them is to have a cooperating script on the server that will read the cookie value and echo it back as part of the response content. But if you can and would do that, why use HttpOnly cookies in the first place?
you can use this :
this.model = Object.assign(this.model, { newProp: 0 });
When elements are positioned outside the normal flow, they can overlap other elements.
according to Overlapping Elements section on http://web.archive.org/web/20130501103219/http://w3schools.com/css/css_positioning.asp
There are a few ways to go about this. One option would be to use inputfile.read()
instead of inputfile.readlines()
- you'd need to write separate code to strip the first four lines, but if you want the final output as a single string anyway, this might make the most sense.
A second, simpler option would be to rejoin the strings after striping the first four lines with my_text = ''.join(my_text)
. This is a little inefficient, but if speed isn't a major concern, the code will be simplest.
Finally, if you actually want the output as a list of strings instead of a single string, you can just modify your data parser to iterate over the list. That might looks something like this:
def data_parser(lines, dic):
for i, j in dic.iteritems():
for (k, line) in enumerate(lines):
lines[k] = line.replace(i, j)
return lines
I just wanted to add an additional option: In your input add the form tag and specify the name of a form that doesn't exist on your page:
<input form="fakeForm" type="text" readonly value="random value" />
This is the same solution as you have probably seen already, but by doing it this way it's more clearer:
>>> num = 3.141592654
>>> print(f"Number: {num:.2f}")
Empty strings are falsey, so you can just write:
if ($a) {
echo 'text';
}
Although if you're asking if a particular substring exists in that string, you can use strpos()
to do that:
if (strpos($a, 'some text') !== false) {
echo 'text';
}
According to the standard (§6.4.4.4/10)
The value of an integer character constant containing more than one character (e.g., 'ab'), [...] is implementation-defined.
long x = '\xde\xad\xbe\xef'; // yes, single quotes
This is valid ISO 9899:2011 C. It compiles without warning under gcc
with -Wall
, and a “multi-character character constant” warning with -pedantic
.
From Wikipedia:
Multi-character constants (e.g. 'xy') are valid, although rarely useful — they let one store several characters in an integer (e.g. 4 ASCII characters can fit in a 32-bit integer, 8 in a 64-bit one). Since the order in which the characters are packed into one int is not specified, portable use of multi-character constants is difficult.
For portability sake, don't use multi-character constants with integral types.
In this case, they are the same. None
is a singleton object (there only ever exists one None
).
is
checks to see if the object is the same object, while == just checks if they are equivalent.
For example:
p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they are equivalent
But since there is only one None
, they will always be the same, and is
will return True.
p = None
q = None
p is q # True because they are both pointing to the same "None"
I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.
You have to write the query adding "[]" to foo like this:
foo[]=val1&foo[]=val2&foo[]=val3
Another solution is to use the query method:
import pandas as pd
from random import randint
df = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)],
'B': [randint(1, 9) * 10 for x in xrange(10)],
'C': [randint(1, 9) * 100 for x in xrange(10)]})
print df
A B C
0 7 20 300
1 7 80 700
2 4 90 100
3 4 30 900
4 7 80 200
5 7 60 800
6 3 80 900
7 9 40 100
8 6 40 100
9 3 10 600
print df.query('B > 50 and C != 900')
A B C
1 7 80 700
2 4 90 100
4 7 80 200
5 7 60 800
Now if you want to change the returned values in column A you can save their index:
my_query_index = df.query('B > 50 & C != 900').index
....and use .iloc
to change them i.e:
df.iloc[my_query_index, 0] = 5000
print df
A B C
0 7 20 300
1 5000 80 700
2 5000 90 100
3 4 30 900
4 5000 80 200
5 5000 60 800
6 3 80 900
7 9 40 100
8 6 40 100
9 3 10 600
Instead of minutes-past-midnight we store it as 24 hours clock, as an SMALLINT.
09:12 = 912 14:15 = 1415
when converting back to "human readable form" we just insert a colon ":" two characters from the right. Left-pad with zeros if you need to. Saves the mathematics each way, and uses a few fewer bytes (compared to varchar), plus enforces that the value is numeric (rather than alphanumeric)
Pretty goofy though ... there should have been a TIME datatype in MS SQL for many a year already IMHO ...
It is used in the stack unwiding tables, which you can see for instance in the assembly output of my answer to another question. As mentioned on that answer, its use is defined by the Itanium C++ ABI, where it is called the Personality Routine.
The reason it "works" by defining it as a global NULL void pointer is probably because nothing is throwing an exception. When something tries to throw an exception, then you will see it misbehave.
Of course, if nothing is using exceptions, you can disable them with -fno-exceptions
(and if nothing is using RTTI, you can also add -fno-rtti
). If you are using them, you have to (as other answers already noted) link with g++
instead of gcc
, which will add -lstdc++
for you.
Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337
You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties
Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0
only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden
, you can eliminate this problem:
div {_x000D_
width:100px;_x000D_
height:20px;_x000D_
}_x000D_
.menu {_x000D_
visibility:hidden;_x000D_
opacity:0;_x000D_
transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
_x000D_
background:#eee;_x000D_
width:100px;_x000D_
margin:0;_x000D_
padding:5px;_x000D_
list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
visibility:visible;_x000D_
opacity:1;_x000D_
}
_x000D_
<div>_x000D_
<a href="#">Open Menu</a>_x000D_
<ul class="menu">_x000D_
<li><a href="#">Item</a></li>_x000D_
<li><a href="#">Item</a></li>_x000D_
<li><a href="#">Item</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
Had problems even when init.py existed in subfolder and all that was missing was adding 'as' after import
from folder.file import Class as Class
import folder.file as functions
Scikit learn recently introduced the plot_tree
method to make this very easy (new in version 0.21 (May 2019)). Documentation here.
Here's the minimum code you need:
from sklearn import tree
plt.figure(figsize=(40,20)) # customize according to the size of your tree
_ = tree.plot_tree(your_model_name, feature_names = X.columns)
plt.show()
plot_tree
supports some arguments to beautify the tree. For example:
from sklearn import tree
plt.figure(figsize=(40,20))
_ = tree.plot_tree(your_model_name, feature_names = X.columns,
filled=True, fontsize=6, rounded = True)
plt.show()
If you want to save the picture to a file, add the following line before plt.show()
:
plt.savefig('filename.png')
If you want to view the rules in text format, there's an answer here. It's more intuitive to read.
This fix worked very well for me:
Add the following to to your ~/.profile
export DYLD_LIBRARY_PATH=/usr/local/mysql/lib:$DYLD_LIBRARY_PATH
http://www.rickwargo.com/2010/12/16/installing-mysql-5-5-on-os-x-10-6-snow-leopard-and-rails-3/
If you just want to kill any/all java processes, then all you need is;
killall java
If, however, you want to kill the wskInterface process in particular, then you're most of the way there, you just need to strip out the process id;
PID=`ps -ef | grep wskInterface | awk '{ print $2 }'`
kill -9 $PID
Should do it, there is probably an easier way though...
There isn't a 1-1 correspondence between IPv4 and IPv6 addresses (nor between IP addresses and devices), so what you're asking for generally isn't possible.
There is a particular range of IPv6 addresses that actually represent the IPv4 address space, but general IPv6 addresses will not be from this range.
PHP's string length is limited by the way strings are represented in PHP; memory does not have anything to do with it.
According to phpinternalsbook.com, strings are stored in struct { char *val; int len; } and since the maximum size of an int in C is 4 bytes, this effectively limits the maximum string size to 2GB.
I'm using gson 2.2.3
public class Main {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
JsonReader jsonReader = new JsonReader(new FileReader("jsonFile.json"));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equals("descriptor")) {
readApp(jsonReader);
}
}
jsonReader.endObject();
jsonReader.close();
}
public static void readApp(JsonReader jsonReader) throws IOException{
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
System.out.println(name);
if (name.contains("app")){
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String n = jsonReader.nextName();
if (n.equals("name")){
System.out.println(jsonReader.nextString());
}
if (n.equals("age")){
System.out.println(jsonReader.nextInt());
}
if (n.equals("messages")){
jsonReader.beginArray();
while (jsonReader.hasNext()) {
System.out.println(jsonReader.nextString());
}
jsonReader.endArray();
}
}
jsonReader.endObject();
}
}
jsonReader.endObject();
}
}
Here is an example of bubbleSort, and Time Complexity is O(n).
int[] bubbleSort(int[] numbers) {
if(numbers == null || numbers.length == 1) {
return numbers;
}
boolean isSorted = false;
while(!isSorted) {
isSorted = true;
for(int i = 0; i < numbers.length - 1; i++) {
if(numbers[i] > numbers[i + 1]) {
int hold = numbers[i + 1];
numbers[i + 1] = numbers[i];
numbers[i] = hold;
isSorted = false;
}
}
}
return numbers;
}
yes, these are the well-known quantifiers used in math. Another example is ? which reads as "exists".
foreach($results['data'] as $result) {
echo $result['type'], '<br />';
}
or echo $results['data'][1]['type'];
if you are looking for a script to avoid submitting form when some errors found, this method should work
function verifyData(){
if (document.MyForm.FormInput.value.length == "") {
alert("Write something!");
}
else {
document.MyForm.submit();
}
}
change the Submit Button type to "button"
<input value="Save" type="button" onClick="verifyData()">
hope this help.
I'd recommend using ActiveRecord::Base.connection.exec_query
instead of ActiveRecord::Base.connection.execute
which returns a ActiveRecord::Result
(available in rails 3.1+) which is a bit easier to work with.
Then you can access it in various the result in various ways like .rows
, .each
, or .to_hash
From the docs:
result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>
# Get the column names of the result:
result.columns
# => ["id", "title", "body"]
# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
[2, "title_2", "body_2"],
...
]
# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
{"id" => 2, "title" => "title_2", "body" => "body_2"},
...
]
# ActiveRecord::Result also includes Enumerable.
result.each do |row|
puts row['title'] + " " + row['body']
end
note: copied my answer from here
Installig Eclispe ADT from market place solved this problem for me.
If you don't want to close and reopen the file, to avoid race conditions, you could truncate
it:
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()
The functionality will likely also be cleaner and safer using open
as a context manager, which will close the file handler, even if an error occurs!
with open(filename, 'r+') as f:
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
if you like to display that time in seconds:
<?php
class debugTimer
{
private $startTime;
private $callsCounter;
function __construct()
{
$this->startTime = microtime(true);
$this->callsCounter = 0;
}
public function getTimer(): float
{
$timeEnd = microtime(true);
$time = $timeEnd - $this->startTime;
$this->callsCounter++;
return $time;
}
public function getCallsNumber(): int
{
return $this->callsCounter;
}
}
$timer = new debugTimer();
usleep(100);
echo '<br />\n
' . $timer->getTimer() . ' seconds before call #' . $timer->getCallsNumber();
usleep(100);
echo '<br />\n
' . $timer->getTimer() . ' seconds before call #' . $timer->getCallsNumber();
Here's one way:
CString str;
str.Format("%d", 5);
In your case, try _T("%d")
or L"%d"
rather than "%d"
The best way to connect to the remote server and execute commands is by using "wmiexec.py"
Just run pip install impacket
Which will create "wmiexec.py" file under the scripts folder in python
Inside the python > Scripts > wmiexec.py
we need to run the wmiexec.py in the following way
python <wmiexec.py location> TargetUser:TargetPassword@TargetHostname "<OS command>"
Pleae change the wmiexec.py location according to yours
Like im using python 3.8.5 and my wmiexec.py location will be C:\python3.8.5\Scripts\wmiexec.py
python C:\python3.8.5\Scripts\wmiexec.py TargetUser:TargetPassword@TargetHostname "<OS command>"
Modify TargetUser, TargetPassword ,TargetHostname and OS command according to your remote machine
Note: Above method is used to run the commands on remote server.
But if you need to capture the output from remote server we need to create an python code.
import subprocess
command = 'C:\\Python36\\python.exe C:\\Python36\\Scripts\\wmiexec.py TargetUser:TargetPassword@TargetHostname "ipconfig"'
command = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
stdout= command.communicate()[0]
print (stdout)
Modify the code accordingly and run it.
UPDATE [Sun 08/26/2012] This answer has become so popular that I decided to make it into a full-fledged blog/tutorial
Please visit My Blog Here to see the latest in easy access information to working with tabs in jQueryUI
Also included (in the blog too) is a jsFiddle
¡¡¡ Update! Please note: In newer versions of jQueryUI (1.9+), ui-tabs-selected
has been replaced with ui-tabs-active
. !!!
I know this thread is old, but something I didn't see mentioned was how to get the "selected tab" (Currently dropped down panel) from somewhere other than the "tab events".
I do have a simply way ...
var curTab = $('.ui-tabs-panel:not(.ui-tabs-hide)');
And to easily get the index, of course there is the way listed on the site ...
var $tabs = $('#example').tabs();
var selected = $tabs.tabs('option', 'selected'); // => 0
However, you could use my first method to get the index and anything you want about that panel pretty easy ...
var curTab = $('.ui-tabs-panel:not(.ui-tabs-hide)'),
curTabIndex = curTab.index(),
curTabID = curTab.prop("id"),
curTabCls = curTab.attr("class");
// etc ....
PS. If you use an iframe variable then .find('.ui-tabs-panel:not(.ui-tabs-hide)'), you will find it easy to do this for selected tabs in frames as well. Remember, jQuery already did all the hard work, no need to reinvent the wheel!
Just to expand (updated)
Question was brought up to me, "What if there are more than one tabs areas on the view?" Again, just think simple, use my same setup but use an ID to identify which tabs you want to get hold of.
For example, if you have:
$('#example-1').tabs();
$('#example-2').tabs();
And you want the current panel of the second tab set:
var curTabPanel = $('#example-2 .ui-tabs-panel:not(.ui-tabs-hide)');
And if you want the ACTUAL tab and not the panel (really easy, which is why I ddn't mention it before but I suppose I will now, just to be thorough)
// for page with only one set of tabs
var curTab = $('.ui-tabs-selected'); // '.ui-tabs-active' in jQuery 1.9+
// for page with multiple sets of tabs
var curTab2 = $('#example-2 .ui-tabs-selected'); // '.ui-tabs-active' in jQuery 1.9+
Again, remember, jQuery did all the hard work, don't think so hard.
It works fine for me using a CSS grid. Initially fix the container and then give overflow-y: auto;
for the centre content which has to get scrolled i.e other than header and footer.
.container{
height: 100%;
left: 0;
position: fixed;
top: 0;
width: 100%;
display: grid;
grid-template-rows: 5em auto 3em;
}
header{
grid-row: 1;
background-color: rgb(148, 142, 142);
justify-self: center;
align-self: center;
width: 100%;
}
.body{
grid-row: 2;
overflow-y: auto;
}
footer{
grid-row: 3;
background: rgb(110, 112, 112);
}
_x000D_
<div class="container">
<header><h1>Header</h1></header>
<div class="body">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
<footer><h3>Footer</h3></footer>
</div>
_x000D_
TLS (Transport Level Security) is the slightly broader term that has replaced SSL (Secure Sockets Layer) in securing HTTP communications. So what you are being asked to do is enable SSL.
There's no (safe) way to pause execution. You can, however, do something like this using setTimeout:
function writeNext(i)
{
document.write(i);
if(i == 5)
return;
setTimeout(function()
{
writeNext(i + 1);
}, 2000);
}
writeNext(1);
The closest you'll get is :active
:
#btnLeft:active {
width: 70px;
height: 74px;
}
However this will only apply the style when the mouse button is held down. The only way to apply a style and keep it applied onclick is to use a bit of JavaScript.
You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.
Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).
EDIT:
Here is some code:
For the UDF:
Public Function UDF_Date(ByVal data) As Date
UDF_Date = Now()
End Function
As Formula in D2:
=UDF_Date(C2)
You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.
And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.
Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.
Addendum:
Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:
The usage of the UDF is the same as described above.
The UDF works only for single cell input ranges.
The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.
If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.
The code might brake for cell-values for which conversion to string is non-deterministic.
The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.
Public Function UDF_Date(ByVal inData As Range) As Date
Dim wb As Workbook
Dim dProps As DocumentProperties
Dim pValue As DocumentProperty
Dim pDate As DocumentProperty
Dim sName As String
Dim sNameDate As String
Dim bDate As Boolean
Dim bValue As Boolean
Dim bChanged As Boolean
bDate = True
bValue = True
bChanged = False
Dim sVal As String
Dim dDate As Date
sName = inData.Address & "_" & inData.Worksheet.Name
sNameDate = sName & "_dat"
sVal = CStr(inData.Value)
dDate = Now()
Set wb = inData.Worksheet.Parent
Set dProps = wb.CustomDocumentProperties
On Error Resume Next
Set pValue = dProps.Item(sName)
If Err.Number <> 0 Then
bValue = False
Err.Clear
End If
On Error GoTo 0
If Not bValue Then
bChanged = True
Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
Else
bChanged = pValue.Value <> sVal
If bChanged Then
pValue.Value = sVal
End If
End If
On Error Resume Next
Set pDate = dProps.Item(sNameDate)
If Err.Number <> 0 Then
bDate = False
Err.Clear
End If
On Error GoTo 0
If Not bDate Then
Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
End If
If bChanged Then
pDate.Value = dDate
Else
dDate = pDate.Value
End If
UDF_Date = dDate
End Function
Make the insertion of the date conditional upon the range.
This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.
Adapted from this tip and @Paul S answer
Private Sub Worksheet_Change(ByVal Target As Range)
Dim R1 As Range
Dim R2 As Range
Dim InRange As Boolean
Set R1 = Range(Target.Address)
Set R2 = Range("C2:C20")
Set InterSectRange = Application.Intersect(R1, R2)
InRange = Not InterSectRange Is Nothing
Set InterSectRange = Nothing
If InRange = True Then
R1.Offset(0, 1).Value = Now()
End If
Set R1 = Nothing
Set R2 = Nothing
End Sub
There is really no reason to dig through paths; the IDE hands it to you (at least with version 1.5.1).
In the Build
menu, select Build APK
:
A dialog will appear:
If you are using a newer version of Android Studio, it might look like this:
Clicking the Show in Explorer
or locate
link, you will be presented with a file explorer positioned somewhere near wherever Android Studio put the APK file:
But in AS 3, when you click locate
, it puts you at the app
level. You need to go into the release
folder to get your APK
file.
Try this code:
import subprocess
def process_exists(process_name):
progs = str(subprocess.check_output('tasklist'))
if process_name in progs:
return True
else:
return False
And to check if the process is running:
if process_exists('example.exe'):
#do something
// This pair of functions convert HSL to RGB and vice-versa.
// It's pretty optimized for execution speed
typedef unsigned char BYTE
typedef struct _RGB
{
BYTE R;
BYTE G;
BYTE B;
} RGB, *pRGB;
typedef struct _HSL
{
float H; // color Hue (0.0 to 360.0 degrees)
float S; // color Saturation (0.0 to 1.0)
float L; // Luminance (0.0 to 1.0)
float V; // Value (0.0 to 1.0)
} HSL, *pHSL;
float *fMin (float *a, float *b)
{
return *a <= *b? a : b;
}
float *fMax (float *a, float *b)
{
return *a >= *b? a : b;
}
void RGBtoHSL (pRGB rgb, pHSL hsl)
{
// See https://en.wikipedia.org/wiki/HSL_and_HSV
// rgb->R, rgb->G, rgb->B: [0 to 255]
float r = (float) rgb->R / 255;
float g = (float) rgb->G / 255;
float b = (float) rgb->B / 255;
float *min = fMin(fMin(&r, &g), &b);
float *max = fMax(fMax(&r, &g), &b);
float delta = *max - *min;
// L, V [0.0 to 1.0]
hsl->L = (*max + *min)/2;
hsl->V = *max;
// Special case for H and S
if (delta == 0)
{
hsl->H = 0.0f;
hsl->S = 0.0f;
}
else
{
// Special case for S
if((*max == 0) || (*min == 1))
hsl->S = 0;
else
// S [0.0 to 1.0]
hsl->S = (2 * *max - 2*hsl->L)/(1 - fabsf(2*hsl->L - 1));
// H [0.0 to 360.0]
if (max == &r) hsl->H = fmod((g - b)/delta, 6); // max is R
else if (max == &g) hsl->H = (b - r)/delta + 2; // max is G
else hsl->H = (r - g)/delta + 4; // max is B
hsl->H *= 60;
}
}
void HSLtoRGB (pHSL hsl, pRGB rgb)
{
// See https://en.wikipedia.org/wiki/HSL_and_HSV
float a, k, fm1, fp1, f1, f2, *f3;
// L, V, S: [0.0 to 1.0]
// rgb->R, rgb->G, rgb->B: [0 to 255]
fm1 = -1;
fp1 = 1;
f1 = 1-hsl->L;
a = hsl->S * *fMin(&hsl->L, &f1);
k = fmod(0 + hsl->H/30, 12);
f1 = k - 3;
f2 = 9 - k;
f3 = fMin(fMin(&f1, &f2), &fp1) ;
rgb->R = (BYTE) (255 * (hsl->L - a * *fMax(f3, &fm1)));
k = fmod(8 + hsl->H/30, 12);
f1 = k - 3;
f2 = 9 - k;
f3 = fMin(fMin(&f1, &f2), &fp1) ;
rgb->G = (BYTE) (255 * (hsl->L - a * *fMax(f3, &fm1)));
k = fmod(4 + hsl->H/30, 12);
f1 = k - 3;
f2 = 9 - k;
f3 = fMin(fMin(&f1, &f2), &fp1) ;
rgb->B = (BYTE) (255 * (hsl->L - a * *fMax(f3, &fm1)));
}
I figured out how to use multiple left outer joins in VB.NET using LINQ to SQL:
Dim db As New ContractDataContext()
Dim query = From o In db.Orders _
Group Join v In db.Vendors _
On v.VendorNumber Equals o.VendorNumber _
Into ov = Group _
From x In ov.DefaultIfEmpty() _
Group Join s In db.Status _
On s.Id Equals o.StatusId Into os = Group _
From y In os.DefaultIfEmpty() _
Where o.OrderNumber >= 100000 And o.OrderNumber <= 200000 _
Select Vendor_Name = x.Name, _
Order_Number = o.OrderNumber, _
Status_Name = y.StatusName
The Instant
class doesn't contain Zone information, it only stores timestamp in milliseconds from UNIX epoch, i.e. 1 Jan 1070 from UTC.
So, formatter can't print a date because date always printed for concrete time zone.
You should set time zone to formatter and all will be fine, like this :
Instant instant = Instant.ofEpochMilli(92554380000L);
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.UK).withZone(ZoneOffset.UTC);
assert formatter.format(instant).equals("07/12/72 05:33");
assert instant.toString().equals("1972-12-07T05:33:00Z");
encodeURIComponent(string) will do it:
encodeURIComponent("Robert'); DROP TABLE Students;--")
//>> "Robert')%3B%20DROP%20TABLE%20Students%3B--"
Passing SQL around in a query string might not be a good plan though,
You can use a combination of UCASE()
, MID()
and CONCAT()
:
SELECT CONCAT(UCASE(MID(name,1,1)),MID(name,2)) AS name FROM names;
This is may be late but for those who are still looking for answer for this I found a project on git hub and this is the only one that actually fit my needs. android-materialshadowninepatch
Just add this line on your build.gradle dependency
compile 'com.h6ah4i.android.materialshadowninepatch:materialshadowninepatch:0.6.3'
cheers. thumbs up for the creator ! happycodings
Save this code in drawable folder with "bg_button.xml" and call "@drawable/bg_button" as background of button in your xml:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape>
<solid
android:color="#004F81" />
<stroke
android:width="1dp"
android:color="#222222" />
<corners
android:radius="7dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="#89cbee"
android:endColor="#004F81"
android:angle="270" />
<stroke
android:width="1dp"
android:color="#4aa5d4" />
<corners
android:radius="7dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
</selector>