For what I understand, VSCode is not in AppData anymore.
So Set the default git editor by executing that command in a command prompt window:
git config --global core.editor "'C:\Program Files (x86)\Microsoft VS Code\code.exe' -w"
The parameter -w
, --wait
is to wait for window to be closed before returning. Visual Studio Code is base on Atom Editor. if you also have atom installed execute the command atom --help
. You will see the last argument in the help is wait.
Next time you do a git rebase -i HEAD~3
it will popup Visual Studio Code. Once VSCode is close then Git will take back the lead.
Note: My current version of VSCode is 0.9.2
I hope that help.
Sometimes spaces in path create a problem. You can add e.g. -vm C:\progra~1\Java\jre1.8.0_112\bin\javaw.exe
I got the same issue while running the skiprows while reading the csv file. I was doning skip_rows=1 this will not work
Simple example gives an idea how to use skiprows while reading csv file.
import pandas as pd
#skiprows=1 will skip first line and try to read from second line
df = pd.read_csv('my_csv_file.csv', skiprows=1) ## pandas as pd
#print the data frame
df
Here are a few options:
Step-by-Step Guide to Reverse Engineering Code into UML Diagrams with Microsoft Visio 2000 - http://msdn.microsoft.com/en-us/library/aa140255(office.10).aspx
BoUML - http://bouml.fr/features.html
StarUML - http://staruml.sourceforge.net/en/
Reverse engineering of the UML class diagram from C++ code in presence of weakly typed containers (2001) - http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.27.9064
Umbrello UML Modeller - http://uml.sourceforge.net/
A list of other tools to look at - http://plg.uwaterloo.ca/~migod/uml.html
You can do the following:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int arr[];
Scanner scan = new Scanner(System.in);
// If you want to take 5 numbers for user and store it in an int array
for(int i=0; i<5; i++) {
System.out.print("Enter number " + (i+1) + ": ");
arr[i] = scan.nextInt(); // Taking user input
}
// For printing those numbers
for(int i=0; i<5; i++)
System.out.println("Number " + (i+1) + ": " + arr[i]);
}
}
You are not seeding the number.
Use This:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
cout << (rand() % 100) << endl;
return 0;
}
You only need to seed it once though. Basically don't seed it every random number.
Center using a LinearLayout:
<LinearLayout
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<ImageButton
android:id="@+id/btnFindMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/findme" />
</LinearLayout>
Core-js did not work for me as it caused other issues, however, simply installing the latest version of npm i @types/es6-promise --save-dev
got rid of the issues. The issues for me stemmed from compiling an sdk that was using rxjs. Here is the error I was getting:
`node_modules/rxjs/Observable.d.ts(59,60): error TS2693: Promise only refers to a type, but is being used as a value here.`
I know this is an old question but thought I'd share how I resolved the issue.
If you're using Visual Studio and this error occurs, you can try to attach to process (CTRL+ALT+P) and find the "(program).exe" process. When you try to attach to it, an error will display stating that it failed to attach which removes the process from "running" (even though it's not...) You'll also be able to delete the (program).exe from your Debug folder.
Hope this helps someone! :)
<option value="" selected style="display:none">Please select one item</option>
Using selected
and using display: none;
for hidden item in list.
This might have been asked before. See Can I add jars to maven 2 build classpath without installing them?
In a nutshell: include your jar as dependency with system scope. This requires specifying the absolute path to the jar.
See also http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html
Binding the scroll event after the ul has loaded using ajax has solved the issue. In my findings $(document).on( 'scroll', '#id', function () {...}) is not working and binding the scroll event after the ajax load found working.
$("#ulId").bind('scroll', function() {
console.log('Event worked');
});
You may unbind the event after removing or replacing the ul.
Hope it may help someone.
If you're using MAMP, key in your IP address (let's say 192.0.0.63) in your iPhone Safari browser, followed by the port number 8888 (e.g. 192.0.0.63:8888) and you will be able to see your local site in your iPhone.
And if you're using a WAMP server, again in your iPhone safari browser just key in the IP address (let's say 192.0.0.63) and that's it. But don't forget to remove the deny from all
from the httpd.conf file for your WAMP server. If you look for the line allow from 127.0.0.1
, above it or below of it you will see deny from all
; just delete this line and restart your WAMP server and that should to the job.
physical collection of Class, interface, enum etc which is in IL code. Which can be .EXE or .DLL file .EXE is executable file and .DLL can dynamically used in any .net Supported language.
You can do Your own Animation style as an xml file like this(put it in anim folder):
left to right:
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate android:fromXDelta="-100%" android:toXDelta="0%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="500"/>
</set>
right to left:
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
android:fromXDelta="0%" android:toXDelta="100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="500" />
</set>
here You can set Your own values at duration, maybe it depends on the phone model how the animation will look like, try some values out if it looks not good.
and then You can call it in Your activity:
Intent animActivity = new Intent(this,YourStartAfterAnimActivity.class);
startActivity(nextActivity);
overridePendingTransition(R.anim.your_left_to_right, R.anim.your_right_to_left);
To redirect your logs output to a file, you need to use the FileAppender and need to define other file details in your log4j.properties/xml file. Here is a sample properties file for the same:
# Root logger option
log4j.rootLogger=INFO, file
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Follow this tutorial to learn more about log4j usage:
http://www.mkyong.com/logging/log4j-log4j-properties-examples/
Imo, the best way to parse your JSON response with GSON would be creating classes that "match" your response and then use Gson.fromJson()
method.
For example:
class Response {
Map<String, App> descriptor;
// standard getters & setters...
}
class App {
String name;
int age;
String[] messages;
// standard getters & setters...
}
Then just use:
Gson gson = new Gson();
Response response = gson.fromJson(yourJson, Response.class);
Where yourJson
can be a String
, any Reader
, a JsonReader
or a JsonElement
.
Finally, if you want to access any particular field, you just have to do:
String name = response.getDescriptor().get("app3").getName();
You can always parse the JSON manually as suggested in other answers, but personally I think this approach is clearer, more maintainable in long term and it fits better with the whole idea of JSON.
Or you can just initialize inline in the controller. If you use an init function internal to the controller, it doesn't need to be defined in the scope. In fact, it can be self executing:
function MyCtrl($scope) {
$scope.isSaving = false;
(function() { // init
if (true) { // $routeParams.Id) {
//get an existing object
} else {
//create a new object
}
})()
$scope.isClean = function () {
return $scope.hasChanges() && !$scope.isSaving;
}
$scope.hasChanges = function() { return false }
}
Since I reached here while searching to join on a specific property of a list of objects (and not the ToString() of it) here's an addition to the accepted answer:
var commaDelimited = string.Join(",", students.Where(i => i.Category == studentCategory)
.Select(i => i.FirstName));
In Rails 3
Adding Rails.env = ActiveSupport::StringInquirer.new('production')
into the application.rb and rails s
will work same as rails server -e production
module BlacklistAdmin
class Application < Rails::Application
config.encoding = "utf-8"
Rails.env = ActiveSupport::StringInquirer.new('production')
config.filter_parameters += [:password]
end
end
Whilst I recommend hyphens, I shall also postulate an answer that isn't on your list:
Nothing At All
/quotationrequests/
, /purchaseorders/
and so on.?q=foo+bar
In windows the default is: C:\Program Files\Java\jdk1.6.0_14
(where the numbers may differ, as they're the version).
"start" is a name of a script, in npm you run scripts like this npm run scriptName
, npm start
is also a short for npm run start
As for "react-scripts" this is a script related specifically to create-react-app
Sad side note: I decided to use C++ IO to be consistent with boost based code. From answers to this question I chose while (std::getline(std::cin, line))
. Using g++ version 4.5.3 (-O3) in cygwin (mintty) i got 2 MB/s throughput. Microsoft Visual C++ 2010 (/O2) made it 40 MB/s for the same code.
After rewriting the IO to pure C while (fgets(buf, 100, stdin))
the throughput jumped to 90 MB/s in both tested compilers. That makes a difference for any input bigger than 10 MB...
To allow user ec2-user
(Amazon AWS) write access to the public web directory (/var/www/html),
enter this command via Putty or Terminal, as the root user sudo
:
chown -R ec2-user /var/www/html
Make sure permissions on that entire folder were correct:
chmod -R 755 /var/www/html
Doc's:
Setting up amazon ec2-instances
Connect to Amazon EC2 file directory using Filezilla and SFTP (Video)
:last
is not part of the css spec, this is jQuery specific.
you should be looking for last-child
var first = div.querySelector('[move_id]:first-child');
var last = div.querySelector('[move_id]:last-child');
I followed configparser approach and it worked quite well for me. Created one PropertyReader file and used config parser there to ready property to corresponding to each section.
**Used Python 2.7
Content of PropertyReader.py file:
#!/usr/bin/python
import ConfigParser
class PropertyReader:
def readProperty(self, strSection, strKey):
config = ConfigParser.RawConfigParser()
config.read('ConfigFile.properties')
strValue = config.get(strSection,strKey);
print "Value captured for "+strKey+" :"+strValue
return strValue
Content of read schema file:
from PropertyReader import *
class ReadSchema:
print PropertyReader().readProperty('source1_section','source_name1')
print PropertyReader().readProperty('source2_section','sn2_sc1_tb')
Content of .properties file:
[source1_section]
source_name1:module1
sn1_schema:schema1,schema2,schema3
sn1_sc1_tb:employee,department,location
sn1_sc2_tb:student,college,country
[source2_section]
source_name1:module2
sn2_schema:schema4,schema5,schema6
sn2_sc1_tb:employee,department,location
sn2_sc2_tb:student,college,country
Here is an example using a 3rd party wrapper library for Vue called vue-moment
.
In addition to binding Moment instance into Vue's root scope, this library includes moment
and duration
filters.
This example includes localization and is using ES6 module imports, an official standard, instead of NodeJS's CommonJS module system requires.
import Vue from 'vue';
import moment from 'moment';
import VueMoment from 'vue-moment';
// Load Locales ('en' comes loaded by default)
require('moment/locale/es');
// Choose Locale
moment.locale('es');
Vue.use(VueMoment, { moment });
Now you can use the Moment instance directly in your Vue templates without any additional markup:
<small>Copyright {{ $moment().year() }}</small>
Or the filters:
<span>{{ 3600000 | duration('humanize') }}</span>
<!-- "an hour" -->
<span>{{ [2, 'years'] | duration('add', 1, 'year') | duration('humanize') }}</span>
<!-- "3 years" -->
I would suggest using the keyup event something like below:
$('elementName').keyup(function() {
alert("Key up detected");
});
There are a few ways of achieving the same result so I guess it's down to preference and depends on how you want it to work exactly.
Update: This only works for manual input not copy and paste.
For copy and paste I would recommend the following:
$('elementName').on('input',function(e){
// Code here
});
As of Bootstrap 4 the following class was added to achieve this for you without JavaScript.
modal-dialog-centered
You can find their documentation here.
Thanks v.d for pointing out you need to add both .modal-dialog-centered to .modal-dialog to vertically center the modal.
You need to use DateTime.ParseExact
with format "dd/MM/yyyy"
DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Its safer if you use d/M/yyyy
for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.
Your date format day/Month/Year
might be an acceptable date format for some cultures. For example for Canadian Culture en-CA
DateTime.Parse
would work like:
DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));
Or
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture
Both the above lines would work because the the string's format is acceptable for en-CA
culture. Since you are not supplying any culture to your DateTime.Parse
call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.
Another method for parsing is using DateTime.TryParseExact
DateTime dt;
if (DateTime.TryParseExact("24/01/2013",
"d/M/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//valid date
}
else
{
//invalid date
}
The TryParse
group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool
value indicating success or failure in parsing.
Notice that I have used single d
and M
for day and month respectively. Single d
and M
works for both single/double digits day and month. So for the format d/M/yyyy
valid values could be:
For further reading you should see: Custom Date and Time Format Strings
WARNING: Do not run this on a production machine.
On a Linux box:
redis-cli KEYS "*" | wc -l
Note: As mentioned in comments below, this is an O(N) operation, so on a large DB with many keys you should not use this. For smaller deployments, it should be fine.
try this it is working
MySqlCommand dbcmd = _conn.CreateCommand();
dbcmd.CommandText = sqlCommandString;
dbcmd.ExecuteNonQuery();
long imageId = dbcmd.LastInsertedId;
the below lines would also work
!python script.py
There are ready-made shortcuts (syntactic sugar) to the function wrapper @CMS answered with. (Below assuming that the context you want is this.tip
.)
For virtually all javascript development (in 2020) you can use fat arrow functions, which are part of the ECMAScript 2015 (Harmony/ES6/ES2015) specification.
An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the
this
value [...].
(param1, param2, ...rest) => { statements }
In your case, try this:
if (this.options.destroyOnHide) {
setTimeout(() => { this.tip.destroy(); }, 1000);
}
If you target browser compatible with ECMA-262, 5th edition (ECMAScript 5) or Node.js, which (in 2020) means all common browsers as well as older browsers, you could use Function.prototype.bind
. You can optionally pass any function arguments to create partial functions.
fun.bind(thisArg[, arg1[, arg2[, ...]]])
Again, in your case, try this:
if (this.options.destroyOnHide) {
setTimeout(this.tip.destroy.bind(this.tip), 1000);
}
The same functionality has also been implemented in Prototype (any other libraries?).
Function.prototype.bind
can be implemented like this if you want custom backwards compatibility (but please observe the notes).
If you are already using jQuery 1.4+, there's a ready-made function for explicitly setting the this
context of a function.
jQuery.proxy(): Takes a function and returns a new one that will always have a particular context.
$.proxy(function, context[, additionalArguments])
In your case, try this:
if (this.options.destroyOnHide) {
setTimeout($.proxy(this.tip.destroy, this.tip), 1000);
}
It's available in Underscore.js, as well as lodash, as _.bind(...)
1,2
bind Bind a function to an object, meaning that whenever the function is called, the value of
this
will be the object. Optionally, bind arguments to the function to pre-fill them, also known as partial application.
_.bind(function, object, [*arguments])
In your case, try this:
if (this.options.destroyOnHide) {
setTimeout(_.bind(this.tip.destroy, this.tip), 1000);
}
Interesting blog post here:
http://geekswithblogs.net/cskardon/archive/2008/06/23/dispose-of-a-wpf-usercontrol-ish.aspx
It mentions subscribing to Dispatcher.ShutdownStarted to dispose of your resources.
I spent some time working on it and finally realized that when the background is dark, shadow is not visible
(As of July 31, 2017)
SWIFT 3
self.yourCustomView.removeFromSuperview()
self.yourCustomViewParentView.addSubview(self.yourCustomView)
Objective C
[self.yourCustomView removeFromSuperview];
[self.yourCustomViewParentView addSubview:self.yourCustomView];
This is the easiest way to quickly remove all constraints that exist on a UIView. Just be sure to add the UIView back with it's new constraints or new frame afterwards =)
Its easy to switch between prefork or worker mpm in Apache 2.4 on RHEL7
Check MPM type by executing
sudo httpd -V
Server version: Apache/2.4.6 (Red Hat Enterprise Linux)
Server built: Jul 26 2017 04:45:44
Server's Module Magic Number: 20120211:24
Server loaded: APR 1.4.8, APR-UTIL 1.5.2
Compiled using: APR 1.4.8, APR-UTIL 1.5.2
Architecture: 64-bit
Server MPM: prefork
threaded: no
forked: yes (variable process count)
Server compiled with....
-D APR_HAS_SENDFILE
-D APR_HAS_MMAP
-D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
-D APR_USE_SYSVSEM_SERIALIZE
-D APR_USE_PTHREAD_SERIALIZE
-D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
-D APR_HAS_OTHER_CHILD
-D AP_HAVE_RELIABLE_PIPED_LOGS
-D DYNAMIC_MODULE_LIMIT=256
-D HTTPD_ROOT="/etc/httpd"
-D SUEXEC_BIN="/usr/sbin/suexec"
-D DEFAULT_PIDLOG="/run/httpd/httpd.pid"
-D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
-D DEFAULT_ERRORLOG="logs/error_log"
-D AP_TYPES_CONFIG_FILE="conf/mime.types"
-D SERVER_CONFIG_FILE="conf/httpd.conf"
Now to change MPM edit following file and uncomment required MPM
/etc/httpd/conf.modules.d/00-mpm.conf
# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:
# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#
#LoadModule mpm_worker_module modules/mod_mpm_worker.so
# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#
#LoadModule mpm_event_module modules/mod_mpm_event.so
This can be caused by not having administrator permissions for Oracle Client
. Add this in App.config
file:
<IPermission class="Oracle.DataAccess.Client.OraclePermission,
Oracle.DataAccess, Version=2.111.7.20, Culture=neutral,
PublicKeyToken=89b483f429c47342" version= "1" Unrestricted="true"/>
You can place your json to js file and save it to global variable. It is not asynchronous, but it can help.
To make it short - there's no way to unit test Spring Data JPA repositories reasonably for a simple reason: it's way to cumbersome to mock all the parts of the JPA API we invoke to bootstrap the repositories. Unit tests don't make too much sense here anyway, as you're usually not writing any implementation code yourself (see the below paragraph on custom implementations) so that integration testing is the most reasonable approach.
We do quite a lot of upfront validation and setup to make sure you can only bootstrap an app that has no invalid derived queries etc.
CriteriaQuery
instances for derived queries to make sure the query methods do not contain any typos. This requires working with the Criteria API as well as the meta.model.EntityManager
to create a Query
instance for those (which effectively triggers query syntax validation).Metamodel
for meta-data about the domain types handled to prepare is-new checks etc.All stuff that you'd probably defer in a hand-written repository which might cause the application to break at runtime (due to invalid queries etc.).
If you think about it, there's no code you write for your repositories, so there's no need to write any unittests. There's simply no need to as you can rely on our test base to catch basic bugs (if you still happen to run into one, feel free to raise a ticket). However, there's definitely need for integration tests to test two aspects of your persistence layer as they are the aspects that related to your domain:
This is usually done by using an in-memory database and test cases that bootstrap a Spring ApplicationContext
usually through the test context framework (as you already do), pre-populate the database (by inserting object instances through the EntityManager
or repo, or via a plain SQL file) and then execute the query methods to verify the outcome of them.
Custom implementation parts of the repository are written in a way that they don't have to know about Spring Data JPA. They are plain Spring beans that get an EntityManager
injected. You might of course wanna try to mock the interactions with it but to be honest, unit-testing the JPA has not been a too pleasant experience for us as well as it works with quite a lot of indirections (EntityManager
-> CriteriaBuilder
, CriteriaQuery
etc.) so that you end up with mocks returning mocks and so on.
Those are two different approaches:
kubectl create
is what we call Imperative Management. On this approach you tell the Kubernetes API what you want to create, replace or delete, not how you want your K8s cluster world to look like.
kubectl apply
is part of the Declarative Management approach, where changes that you may have applied to a live object (i.e. through scale
) are "maintained" even if you apply
other changes to the object.
You can read more about imperative and declarative management in the Kubernetes Object Management documentation.
This is the easiest setup on a Linux Ubuntu machine I have come across. Crazy to see all the queries live.
Find and open your MySQL configuration file, usually /etc/mysql/my.cnf on Ubuntu. Look for the section that says “Logging and Replication”
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
log = /var/log/mysql/mysql.log
Just uncomment the “log” variable to turn on logging. Restart MySQL with this command:
sudo /etc/init.d/mysql restart
Now we’re ready to start monitoring the queries as they come in. Open up a new terminal and run this command to scroll the log file, adjusting the path if necessary.
tail -f /var/log/mysql/mysql.log
Now run your application. You’ll see the database queries start flying by in your terminal window. (make sure you have scrolling and history enabled on the terminal)
FROM http://www.howtogeek.com/howto/database/monitor-all-sql-queries-in-mysql/
when i run
from c in Customers
where c.CustomerID == 1
where c.CustomerID == 2
where c.CustomerID == 3
select c
and
from c in Customers
where c.CustomerID == 1 &&
c.CustomerID == 2 &&
c.CustomerID == 3
select c customer table in linqpad
against my Customer table it output the same sql query
-- Region Parameters
DECLARE @p0 Int = 1
DECLARE @p1 Int = 2
DECLARE @p2 Int = 3
-- EndRegion
SELECT [t0].[CustomerID], [t0].[CustomerName]
FROM [Customers] AS [t0]
WHERE ([t0].[CustomerID] = @p0) AND ([t0].[CustomerID] = @p1) AND ([t0].[CustomerID] = @p2)
so in translation to sql there is no difference and you already have seen in other answers how they will be converted to lambda expressions
Use like this. Here is the online compilation of the code. Take a look http://ideone.com/MJJwtc
public static void swap(List list,
int i,
int j)
Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)
Parameters: list - The list in which to swap elements. i - the index of one element to be swapped. j - the index of the other element to be swapped.
Read The official Docs of collection
import java.util.*;
import java.lang.*;
class Main {
public static void main(String[] args) throws java.lang.Exception
{
//create an ArrayList object
ArrayList words = new ArrayList();
//Add elements to Arraylist
words.add("A");
words.add("B");
words.add("C");
words.add("D");
words.add("E");
System.out.println("Before swaping, ArrayList contains : " + words);
/*
To swap elements of Java ArrayList use,
static void swap(List list, int firstElement, int secondElement)
method of Collections class. Where firstElement is the index of first
element to be swapped and secondElement is the index of the second element
to be swapped.
If the specified positions are equal, list remains unchanged.
Please note that, this method can throw IndexOutOfBoundsException if
any of the index values is not in range. */
Collections.swap(words, 0, words.size() - 1);
System.out.println("After swaping, ArrayList contains : " + words);
}
}
Oneline compilation example http://ideone.com/MJJwtc
var myObj = [];
myObj['Base'] = [];
myObj['Base']['Base.panel.panel_base'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'', AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
myObj['Base']['Base.panel.panel_top'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'',AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
myObj['SC1'] = [];
myObj['SC1']['Base.panel.panel_base'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'', AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
myObj['SC1']['Base.panel.panel_top'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'',AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
console.log(myObj);
if ('Base' in myObj) {
console.log('Base found');
if ('Base.panel.panel_base' in myObj['Base']) {
console.log('Base.panel.panel_base found');
console.log('old value: ' + myObj['Base']['Base.panel.panel_base'].Context);
myObj['Base']['Base.panel.panel_base'] = 'new Value';
console.log('new value: ' + myObj['Base']['Base.panel.panel_base']);
}
}
Output:
The array operation works. There is no problem.
Iteration:
Object.keys(myObj['Base']).forEach(function(key, index) {
var value = objcons['Base'][key];
}, myObj);
One and/or multiple of those should help:
Add C:\Python27\
to your PATH
variable (considering you have Python installed in this directory)
How to set PATH
env variable: http://www.computerhope.com/issues/ch000549.htm
Restart your console and/or Windows after setting variable.
In the same section as above ("Environment Variables"), add new variable with name PYTHON
and value C:\Python27\python.exe
Restart your console and/or Windows after setting variable.
Open Windows command line (cmd
) in Admin mode.
Change directory to your Python installation path: cd C:\Python27
Make symlink needed for some installations: mklink python2.7.exe python.exe
Please note that you should have Python 2.x, NOT 3.x, to run node-gyp
based installations!
The text below says about Unix, but Windows version also requires Python 2.x:
You can install with npm:
$ npm install -g node-gyp
You will also need to install:
On Unix:
python (v2.7 recommended, v3.x.x is not supported)
make
A proper C/C++ compiler toolchain, like GCC
This article may also help: https://github.com/nodejs/node-gyp#installation
Because that syntax simply isn't defined? Besides, x < y
evaluates as a bool, so what does bool < int
mean? It isn't really an overhead; besides, you could write a utility method if you really want - isBetween(10,x,20)
- I wouldn't myself, but hey...
There are a lot of ways to do so, for example:
in case you have not pushed the commit publicly yet:
git reset HEAD~1 --soft
That's it, your commit changes will be in your working directory, whereas the LAST commit will be removed from your current branch. See git reset man
In case you did push publicly (on a branch called 'master'):
git checkout -b MyCommit //save your commit in a separate branch just in case (so you don't have to dig it from reflog in case you screw up :) )
revert commit normally and push
git checkout master
git revert a8172f36 #hash of the commit you want to destroy
# this introduces a new commit (say, it's hash is 86b48ba) which removes changes, introduced in the commit in question (but those changes are still visible in the history)
git push origin master
now if you want to have those changes as you local changes in your working copy ("so that your local copy keeps the changes made in that commit") - just revert the revert commit with --no-commit
option:
git revert --no-commit 86b48ba (hash of the revert commit).
I've crafted a small example: https://github.com/Isantipov/git-revert/commits/master
You can also use:
Get-WmiObject -Class "Win32_computersystem" | Select *
This will show the same result as Format-List * used in the other answers here.
How about not using strings at all...
This should work for any number of digits...
int[] nums = {1, 0, 2, 2, 1};
int retval = 0;
for (int digit : nums)
{
retval *= 10;
retval += digit;
}
System.out.println("Return value is: " + retval);
The simple option is just to set the forms's AcceptButton to the button you want pressed (usually "OK" etc):
TextBox tb = new TextBox();
Button btn = new Button { Dock = DockStyle.Bottom };
btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
Application.Run(new Form { AcceptButton = btn, Controls = { tb, btn } });
If this isn't an option, you can look at the KeyDown event etc, but that is more work...
TextBox tb = new TextBox();
Button btn = new Button { Dock = DockStyle.Bottom };
btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
tb.KeyDown += (sender,args) => {
if (args.KeyCode == Keys.Return)
{
btn.PerformClick();
}
};
Application.Run(new Form { Controls = { tb, btn } });
A quick way to fix this if you're using a Mac is to sign out of the OSX app and log back in.
Find root build.gradle
file and add google maven repo inside allprojects
tag
repositories {
mavenLocal()
mavenCentral()
maven { // <-- Add this
url 'https://maven.google.com/'
name 'Google'
}
}
It's better to use specific version instead of variable version
compile 'com.android.support:appcompat-v7:27.0.0'
If you're using Android Plugin for Gradle 3.0.0 or latter version
repositories {
mavenLocal()
mavenCentral()
google() //---> Add this
}
and inject dependency in this way :
implementation 'com.android.support:appcompat-v7:27.0.0'
Important part in dependency is: ${pom.basedir} (instead of just ${basedir})
<dependency>
<groupId>org.example</groupId>
<artifactId>example</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${pom.basedir}/src/lib/example.jar</systemPath>
</dependency>
Instead of adding any tag which is never a good solution. You can always use margin
property with the required element.
You can add the margin on row class itself. So it will affect globally.
.row{
margin-top: 30px;
margin-bottom: 30px
}
Update: Better solution in all cases would be to introduce a new class and then use it along with .row
class.
.row-m-t{
margin-top : 20px
}
Then use it wherever you want
<div class="row row-m-t"></div>
I use ? and ?, but they might not work for you. I use alt 11551 for the first one and 11550 for the second one. You can always copy paste them if the ascii isnt the same for your system.
Specify the /g
(global) flag on the regular expression to replace all matches instead of just the first:
string.replace(/_/g, ' ').replace(/#/g, '')
To replace one character with one thing and a different character with something else, you can't really get around needing two separate calls to replace
. You can abstract it into a function as Doorknob did, though I would probably have it take an object with old/new as key/value pairs instead of a flat array.
You can also pass in an object array as well, like so:
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
object[] o = { "Ravi", 500 };
dt.Rows.Add(o);
Or even:
dt.Rows.Add(new object[] { "Ravi", 500 });
In addition to the headers consider serving your page via https. Many browsers will not cache https by default.
Check the php version, If you installed php 7.0 version
sudo apt-get install php7.0-curl
sudo service apache2 restart
If you installed php 5.6 version
sudo apt-get install php5-curl
sudo service apache2 restart
It might be that the package "Combinations" is not updated anymore and does not work with a recent version of R (I was also unable to install it on R 2.13.1 on windows). The package "combinat" installs without problem for me and might be a solution for you depending on what exactly you're trying to do.
Let's say that your time value is in cell A1
then in A2
you can put:
=A1*1000*60*60*24
or simply:
=A1*86400000
What I am doing is taking the decimal value of the time and multiply it by 1000 (milliseconds) and 60 (seconds) and 60 (minutes) and 24 (hours).
You will then need to format cell A2
as General for it to be in milliseconds format.
If your time is a text value then use:
=TIMEVALUE(A1)*86400000
UPDATE
Per @dandfra's comment this solution may not work in the Italian version of Excel.
Change your maximum size,
label1.MaximumSize = new Size(100, 0);
And set your autosize to true.
label1.AutoSize = true;
That's it!
I got similar exception in Eclipse. This was due to java.lang.StackOverflowError
error. I had overriden toString()
method in child class, having JoinColumn
, which was returning string using object of parentclass, resulting in circular dependency. Try to remove that object from toString()
, and it will work.
closest()
selects the first element that matches the selector, up from the DOM tree. Begins from the current element and travels up.
parent()
selects one element up (single level up) the DOM tree.
parents()
method is similar toparent()
but selects all the matching elements up the DOM tree. Begins from the parent element and travels up.
The difference is that one (Forms timeout) has to do with authenticating the user and the other (Session timeout) has to do with how long cached data is stored on the server. So they are very independent things, so one does not take precedence over the other.
Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.
Please note that MVC 3 onwards the persistence behavior of TempData has changed, now the value in TempData is persisted until it is read, and not just for the next request.
The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request. https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx
These sites were very helpful, almost, mergetool and difftool. I used the global configuration, but can be used by repository without problems. You just need to execute the following commands:
git config --global merge.tool kdiff3
git config --global mergetool.kdiff3.path "C:/Program Files/KDiff3/bin/kdiff3.exe"
git config --global mergetool.kdiff3.trustExitCode false
git config --global diff.guitool kdiff3
git config --global difftool.kdiff3.path "C:/Program Files/KDiff3/bin/kdiff3.exe"
git config --global difftool.kdiff3.trustExitCode false
Note that the latest version kdiff3 moved the executable from the root of the application folder C:/Program Files/KDiff3 into the bin/ folder inside the application folder. If you're using an older version, remove "bin/" from the paths above.
The use of the trustExitCode
option depends on what you want to do when diff tool returns. From documentation:
git-difftool invokes a diff tool individually on each file. Errors reported by the diff tool are ignored by default. Use --trust-exit-code to make git-difftool exit when an invoked diff tool returns a non-zero exit code.
An idea would be that display:flex;
with flex-direction: row;
is filling the container
div with .flex-1
and .flex-2
, but that does not mean that .flex-2
has a default height:100%;
, even if it is extended to full height.
And to have a child element (.flex-2-child
) with height:100%;
, you'll need to set the parent to height:100%;
or use display:flex;
with flex-direction: row;
on the .flex-2
div too.
From what I know, display:flex
will not extend all your child elements height to 100%.
A small demo, removed the height from .flex-2-child
and used display:flex;
on .flex-2
:
http://jsfiddle.net/2ZDuE/3/
Actually, I have got this error a while ago. There are two ways to make this to work, as per my knowledge.
Wanted to share what caused the error in my case. Spend couple hours to figure this out, so hopefully it will help to save someone some time.
Strangely enough, the error was raised with the Enable drop directory quota
setting being enabled for the domain.
I am not the expert and don't know the technical explanation, but unticking the mentioned setting sorted the problem.
To stay in the same idea of routing. I use this code :
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
Similar to http://enable-cors.org/server_expressjs.html example
The most important consideration is whether the item in question should be able to be traversed more than once. This is because you can always rewind an Iterable by calling iterator() again, but there is no way to rewind an Iterator.
Here is a link to an Online automator to convert CSV files to SQL Insert Into statements:
You can use Console.SetCursorPosition
to set the position of the cursor and then write at the current position.
Here is an example showing a simple "spinner":
static void Main(string[] args)
{
var spin = new ConsoleSpinner();
Console.Write("Working....");
while (true)
{
spin.Turn();
}
}
public class ConsoleSpinner
{
int counter;
public void Turn()
{
counter++;
switch (counter % 4)
{
case 0: Console.Write("/"); counter = 0; break;
case 1: Console.Write("-"); break;
case 2: Console.Write("\\"); break;
case 3: Console.Write("|"); break;
}
Thread.Sleep(100);
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
}
}
Note that you will have to make sure to overwrite any existing output with new output or blanks.
Update: As it has been criticized that the example moves the cursor only back by one character, I will add this for clarification: Using SetCursorPosition
you may set the cursor to any position in the console window.
Console.SetCursorPosition(0, Console.CursorTop);
will set the cursor to the beginning of the current line (or you can use Console.CursorLeft = 0
directly).
In the case of supervised learning, you may want to split both X and y (where X is your input and y the ground truth output). You just have to pay attention to shuffle X and y the same way before splitting.
Here, either X and y are in the same dataframe, so we shuffle them, separate them and apply the split for each (just like in chosen answer), or X and y are in two different dataframes, so we shuffle X, reorder y the same way as the shuffled X and apply the split to each.
# 1st case: df contains X and y (where y is the "target" column of df)
df_shuffled = df.sample(frac=1)
X_shuffled = df_shuffled.drop("target", axis = 1)
y_shuffled = df_shuffled["target"]
# 2nd case: X and y are two separated dataframes
X_shuffled = X.sample(frac=1)
y_shuffled = y[X_shuffled.index]
# We do the split as in the chosen answer
X_train, X_validation, X_test = np.split(X_shuffled, [int(0.6*len(X)),int(0.8*len(X))])
y_train, y_validation, y_test = np.split(y_shuffled, [int(0.6*len(X)),int(0.8*len(X))])
public boolean empty() {
boolean isEmpty = true;
int i = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] != 0) {
i++;
}
}
if (i != 0) {
isEmpty = false;
}
return isEmpty;
}
This is as close as I got to checking if an int array is empty. Although this will not work when the ints in the array are actually zero. It'll work for {1,2,3}, and it'll still return false if {2,0} but {0} will return true
Time ( 'now', 'localtime' )
and Date ( 'now', 'localtime' )
works.
Maybe you have a hardware problem.
I had the same problem on my old system (AMD 1800 MHz CPU ,1GB RAM ,Windows 7 Ultimate) ,until I changed the 2x 512 MB RAM to 2x 1GB RAM. Haven't had any problems since. Also other (minor) problems disappeared. Guess those two 512 MB modules didn't like each other that much ,because 2x 512 MB + 1GB or 1x 512 MB + 2x 1GB didn't work properly either.
I just wrote a script that lets you achieve this. It gives you two global functions: hasEvent(Node elm, String event)
and getEvents(Node elm)
which you can utilize. Be aware that it modifies the EventTarget
prototype method add/RemoveEventListener
, and does not work for events added through HTML markup or javascript syntax of elm.on_event = ...
Script:
var hasEvent,getEvents;!function(){function b(a,b,c){c?a.dataset.events+=","+b:a.dataset.events=a.dataset.events.replace(new RegExp(b),"")}function c(a,c){var d=EventTarget.prototype[a+"EventListener"];return function(a,e,f,g,h){this.dataset.events||(this.dataset.events="");var i=hasEvent(this,a);return c&&i||!c&&!i?(h&&h(),!1):(d.call(this,a,e,f),b(this,a,c),g&&g(),!0)}}hasEvent=function(a,b){var c=a.dataset.events;return c?new RegExp(b).test(c):!1},getEvents=function(a){return a.dataset.events.replace(/(^,+)|(,+$)/g,"").split(",").filter(function(a){return""!==a})},EventTarget.prototype.addEventListener=c("add",!0),EventTarget.prototype.removeEventListener=c("remove",!1)}();
for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.
Another simple solution is to add jackson-databind dependency in POM.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
Keep Rest of the code as it is.
As it turns out, one should not forget to include jacson dependency into the pom file. This solved the issue for me:
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
change database collation:
ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
change table collation:
ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
change column collation:
ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
utf8mb4_0900_ai_ci
mean?3 bytes -- utf8
4 bytes -- utf8mb4 (new)
v4.0 -- _unicode_
v5.20 -- _unicode_520_
v9.0 -- _0900_ (new)
_bin -- just compare the bits; don't consider case folding, accents, etc
_ci -- explicitly case insensitive (A=a) and implicitly accent insensitive (a=á)
_ai_ci -- explicitly case insensitive and accent insensitive
_as (etc) -- accent-sensitive (etc)
_bin -- simple, fast
_general_ci -- fails to compare multiple letters; eg ss=ß, somewhat fast
... -- slower
_0900_ -- (8.0) much faster because of a rewrite
More info:
You guys are really giving me a headache. What you can do is make your layer-list drawable via xml first (meaning a background as the first layer, a drawable that represents secondary progress as the second layer, and another drawable that represents the primary progress as the last layer), then change the color on the code by doing the following:
public void setPrimaryProgressColor(int colorInstance) {
if (progressBar.getProgressDrawable() instanceof LayerDrawable) {
Log.d(mLogTag, "Drawable is a layer drawable");
LayerDrawable layered = (LayerDrawable) progressBar.getProgressDrawable();
Drawable circleDrawableExample = layered.getDrawable(<whichever is your index of android.R.id.progress>);
circleDrawableExample.setColorFilter(colorInstance, PorterDuff.Mode.SRC_IN);
progressBar.setProgressDrawable(layered);
} else {
Log.d(mLogTag, "Fallback in case it's not a LayerDrawable");
progressBar.getProgressDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
}
This method will give you the best flexibility of having the measurement of your original drawable declared on the xml, WITH NO MODIFICATION ON ITS STRUCTURE AFTERWARDS, especially if you need to have the xml file screen folder specific, then just modifying ONLY THE COLOR via the code. No re-instantiating a new ShapeDrawable from scratch whatsoever.
If any1 in 2017 is wondering how to do this programmatically, there is a way that i don't see in the answers
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
you can use mongo query like this yearMonthDayhms: { $dateToString: { format: "%Y-%m-%d-%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}
HourMinute: { $dateToString: { format: "%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}
UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;
> but I don't know how to retrieve the list members from the hash in alphabetical order.
Not really your main question, but for future reference Rod's answer using sorted
can be used for traversing a dict
's keys in sorted order:
for key in sorted(my_dict.keys()):
print key, my_dict[key]
...
and also because tuple
's are ordered by the first member of the tuple, you can do the same with items
:
for key, val in sorted(my_dict.items()):
print key, val
...
here's the best solution to your question: inside the form you have these code:
<li><a href="#">Singup</a></li>
<button type="submit" id="haha"></button>
in the CSS file, do this:
button{
display: none;
}
in JS you do this:
$("a").click(function(){
$("button").trigger("click");
})
There you go.
In my case there there is no selected java sdk version in project structure-
I had to select the -
1.Source Compatibility (1.7)
2.Target Compatibility (1.7)
as shown in image.
I use Iesi.Collections http://www.codeproject.com/KB/recipes/sets.aspx
It's used in lot of OSS projects, I first came across it in NHibernate
Suppose you are going to create a test-context.xml which is independent from app-context.xml for testing, put test-context.xml under /src/test/resources. In the test class, have the @ContextConfiguration annotation on top of the class definition.
@ContextConfiguration(locations = "/test-context.xml")
public class MyTests {
...
}
Spring document Context management
Modify your log4j.properties
file accordingly:
log4j.rootLogger=TRACE,stdout
...
log4j.logger.debugLog=TRACE,debugLog
log4j.logger.reportsLog=DEBUG,reportsLog
Change the log levels for each logger depending to your needs.
My new answer is to use ffmpeg to transcode the .mov
like ffmpeg -i sourceFile.mov destinationFile.mp4
. Do same for the webm format.
OLD Answer: Here's what you do:
<video controls>
<source src="somevideo.webm" type="video/webm">
<source src="somevideo.mp4" type="video/mp4">
I'm sorry; your browser doesn't support HTML5 video in WebM with VP8/VP9 or MP4 with H.264.
<!-- You can embed a Flash player here, to play your mp4 video in older browsers -->
</video>
<video>
element with CSS to suit your needs. For example Materializecss has a simple helper class to render the video nicely across device types.You need to add playsinline autoplay muted loop
, chrome do not allow a video to autostart if it is not muted, also right now I dont know why it is not working in all android devices, im trying to look if it's a version specific, If I found something I'll let you know
Chrome issue: After some research i have found that it doesnt work on chrome sometimes because in responsive you can activate the data saver, and it blocks any video to autostart
Have you tried simply 'reboot' with adb?
adb reboot
Also you can run complete shell scripts (e.g. to reboot your emulator) via adb:
adb shell <command>
The official docs can be found here.
How do I remove unwanted parts from strings in a column?
6 years after the original question was posted, pandas now has a good number of "vectorised" string functions that can succinctly perform these string manipulation operations.
This answer will explore some of these string functions, suggest faster alternatives, and go into a timings comparison at the end.
.str.replace
Specify the substring/pattern to match, and the substring to replace it with.
pd.__version__
# '0.24.1'
df
time result
1 09:00 +52A
2 10:00 +62B
3 11:00 +44a
4 12:00 +30b
5 13:00 -110a
df['result'] = df['result'].str.replace(r'\D', '')
df
time result
1 09:00 52
2 10:00 62
3 11:00 44
4 12:00 30
5 13:00 110
If you need the result converted to an integer, you can use Series.astype
,
df['result'] = df['result'].str.replace(r'\D', '').astype(int)
df.dtypes
time object
result int64
dtype: object
If you don't want to modify df
in-place, use DataFrame.assign
:
df2 = df.assign(result=df['result'].str.replace(r'\D', ''))
df
# Unchanged
.str.extract
Useful for extracting the substring(s) you want to keep.
df['result'] = df['result'].str.extract(r'(\d+)', expand=False)
df
time result
1 09:00 52
2 10:00 62
3 11:00 44
4 12:00 30
5 13:00 110
With extract
, it is necessary to specify at least one capture group. expand=False
will return a Series with the captured items from the first capture group.
.str.split
and .str.get
Splitting works assuming all your strings follow this consistent structure.
# df['result'] = df['result'].str.split(r'\D').str[1]
df['result'] = df['result'].str.split(r'\D').str.get(1)
df
time result
1 09:00 52
2 10:00 62
3 11:00 44
4 12:00 30
5 13:00 110
Do not recommend if you are looking for a general solution.
If you are satisfied with the succinct and readable
str
accessor-based solutions above, you can stop here. However, if you are interested in faster, more performant alternatives, keep reading.
In some circumstances, list comprehensions should be favoured over pandas string functions. The reason is because string functions are inherently hard to vectorize (in the true sense of the word), so most string and regex functions are only wrappers around loops with more overhead.
My write-up, Are for-loops in pandas really bad? When should I care?, goes into greater detail.
The str.replace
option can be re-written using re.sub
import re
# Pre-compile your regex pattern for more performance.
p = re.compile(r'\D')
df['result'] = [p.sub('', x) for x in df['result']]
df
time result
1 09:00 52
2 10:00 62
3 11:00 44
4 12:00 30
5 13:00 110
The str.extract
example can be re-written using a list comprehension with re.search
,
p = re.compile(r'\d+')
df['result'] = [p.search(x)[0] for x in df['result']]
df
time result
1 09:00 52
2 10:00 62
3 11:00 44
4 12:00 30
5 13:00 110
If NaNs or no-matches are a possibility, you will need to re-write the above to include some error checking. I do this using a function.
def try_extract(pattern, string):
try:
m = pattern.search(string)
return m.group(0)
except (TypeError, ValueError, AttributeError):
return np.nan
p = re.compile(r'\d+')
df['result'] = [try_extract(p, x) for x in df['result']]
df
time result
1 09:00 52
2 10:00 62
3 11:00 44
4 12:00 30
5 13:00 110
We can also re-write @eumiro's and @MonkeyButter's answers using list comprehensions:
df['result'] = [x.lstrip('+-').rstrip('aAbBcC') for x in df['result']]
And,
df['result'] = [x[1:-1] for x in df['result']]
Same rules for handling NaNs, etc, apply.
Graphs generated using perfplot. Full code listing, for your reference. The relevant functions are listed below.
Some of these comparisons are unfair because they take advantage of the structure of OP's data, but take from it what you will. One thing to note is that every list comprehension function is either faster or comparable than its equivalent pandas variant.
Functions
def eumiro(df): return df.assign( result=df['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC'))) def coder375(df): return df.assign( result=df['result'].replace(r'\D', r'', regex=True)) def monkeybutter(df): return df.assign(result=df['result'].map(lambda x: x[1:-1])) def wes(df): return df.assign(result=df['result'].str.lstrip('+-').str.rstrip('aAbBcC')) def cs1(df): return df.assign(result=df['result'].str.replace(r'\D', '')) def cs2_ted(df): # `str.extract` based solution, similar to @Ted Petrou's. so timing together. return df.assign(result=df['result'].str.extract(r'(\d+)', expand=False)) def cs1_listcomp(df): return df.assign(result=[p1.sub('', x) for x in df['result']]) def cs2_listcomp(df): return df.assign(result=[p2.search(x)[0] for x in df['result']]) def cs_eumiro_listcomp(df): return df.assign( result=[x.lstrip('+-').rstrip('aAbBcC') for x in df['result']]) def cs_mb_listcomp(df): return df.assign(result=[x[1:-1] for x in df['result']])
I managed to get rid of this error (in my case using Ogre3D + Bullet) by changing the dependency libraries to the debug versions in Project Properties -> Linker -> Input -> Additional Dependencies (VC10).
I changed BulletCollision.lib to BulletCollision_debug.lib (for debug configuration) and it compiled.
Not to be blunt but it means exactly what it says. One of your object references is NULL. You'll see this when you try and access the property or method of a NULL'd object.
Try this:
UITextField *theTextFiels=[[UITextField alloc]initWithFrame:CGRectMake(40, 40, 150, 30)];
theTextFiels.borderStyle=UITextBorderStyleNone;
theTextFiels.layer.cornerRadius=8.0f;
theTextFiels.layer.masksToBounds=YES;
theTextFiels.backgroundColor=[UIColor redColor];
theTextFiels.layer.borderColor=[[UIColor blackColor]CGColor];
theTextFiels.layer.borderWidth= 1.0f;
[self.view addSubview:theTextFiels];
[theTextFiels release];
and import QuartzCore:
#import <QuartzCore/QuartzCore.h>
// Javascript Countdown_x000D_
// Version 1.01 6/7/07 (1/20/2000)_x000D_
// by TDavid at http://www.tdscripts.com/_x000D_
var now = new Date();_x000D_
var theevent = new Date("Nov 13 2017 22:05:01");_x000D_
var seconds = (theevent - now) / 1000;_x000D_
var minutes = seconds / 60;_x000D_
var hours = minutes / 60;_x000D_
var days = hours / 24;_x000D_
ID = window.setTimeout("update();", 1000);_x000D_
_x000D_
function update() {_x000D_
now = new Date();_x000D_
seconds = (theevent - now) / 1000;_x000D_
seconds = Math.round(seconds);_x000D_
minutes = seconds / 60;_x000D_
minutes = Math.round(minutes);_x000D_
hours = minutes / 60;_x000D_
hours = Math.round(hours);_x000D_
days = hours / 24;_x000D_
days = Math.round(days);_x000D_
document.form1.days.value = days;_x000D_
document.form1.hours.value = hours;_x000D_
document.form1.minutes.value = minutes;_x000D_
document.form1.seconds.value = seconds;_x000D_
ID = window.setTimeout("update();", 1000);_x000D_
}
_x000D_
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>_x000D_
</p>_x000D_
<form name="form1">_x000D_
<p>Days_x000D_
<input type="text" name="days" value="0" size="3">Hours_x000D_
<input type="text" name="hours" value="0" size="4">Minutes_x000D_
<input type="text" name="minutes" value="0" size="7">Seconds_x000D_
<input type="text" name="seconds" value="0" size="7">_x000D_
</p>_x000D_
</form>
_x000D_
I would use TreeMap
, which implements SortedMap
. It is designed exactly for that.
Example:
Map<Integer, String> map = new TreeMap<Integer, String>();
// Add Items to the TreeMap
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
// Iterate over them
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
See the Java tutorial page for SortedMap.
And here a list of tutorials related to TreeMap.
This is an old, but still relevant question, and while the answers here are helpful no one answer fully addressed both of the OP's questions.
1. Do I have to install ODP.NET and Oracle client on the computer that I want to run my application?
YES - if you are using ODP.NET, Unmanaged. This is the version that you typically install when you choose "Oracle Data Provider for .NET" in the Oracle Client installer (for example). You Download this from Oracle (just google it: Oracle URLs change often).
But If you are using ODP.NET, Managed (and you probably want to use this one this instead) then No, you only need to install (or deploy) ODP.NET, Managed with the app, not the full Oracle Client. See below for details.
2. If yes, is there other way that I don't have to install them but still can run my application?
Yes, there is at least one way. And it is the Managed port of ODP.NET.
Unfortunately the usual workarounds, including ODBC, Microsoft's Oracle Provider for .NET (yes, that old, deprecated one), and the ODP.NET, Unmanaged DLL all require the Oracle client to be installed. It wasn't until our friends at Oracle gave us a nice little (~5MB) DLL that is also Managed. This means no more having to depoy 32-bit and 64-bit versions to go with 32-bit and 64-bit Oracle clients! And no more issues with assembly binding where you build against 10.0.2.1 (or whatever) but your customers install a range of clients from 9i all the way to 12c, including the 'g' ones in the middle) because you can just ship it with your app, and manage it via nuget.
But if you use ODP.NET, Managed which is available as a nuget package, then you do not need to install the Oracle Client. You only need the ODP.NET, Managed DLL. And if you were previously using the ODP.NET, Unmanaged DLL, it is very easy to switch: simply change all your references to the Managed ODP.NET (.csproj files in csharp, etc.), and then change any using
statements, for example: using Oracle.DataAccess.Client
becomes using Oracle.ManagedDataAccess.Client
and that's it! (Unless you were supposedly using some of the more advanced DB management features in the full client that are exposed in the ODP.NET, Unmanaged, which I have not done myself, so good luck with that..). And also nuke all of those annoying assemblyBindingRedirect
nodes from your app.config
/web.config
files and never sweat that junk again!
References:
Troubleshooting:
That error typically means ODP.NET was found OK, but Oracle client was not found or not installed. This could also occur when the architecture doesn't match (32-bit Oracle client is installed, but trying to use 64-bit Unmanaged ODP.NET, or vice versa). This can also happen due to permissions issues and path issues and other problems with the app domain (your web app or your EXE or whatever) not being able to find the Oracle DLLs to actually communicate with Oracle over the network (the ODP.NET Unmanaged DLLs are basically just wrappers for this that hook into ADO and stuff).
Common solutions I have found to this problem:
App is 64-bit?
App is 32-bit?
Oracle Client is already installed for the correct architecture?
ORACLE_HOME
variables, make sure Oracle can be found (newer versions may use Registry instead)ORACLE_HOME
folder. If you don't know where this is, check the Registry. I have seen cases where ASP.NET app worker process was using Network Service user and for some reason installing 32-bit and 64-bit clients side by side resulted in the permissions being removed from the first client for the Authorized Users
group.. fixing perms on the home folder fixed this.try this:
/////// Controller post and get simple text value
[HttpPost]
public string Contact(string message)
{
return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
}
//// in the view add reference to the Javascript (jQuery) files
@section Scripts{
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
}
/// then add the Post method as following:
<script type="text/javascript">
/// post and get text value
$("#send").on("click", function () {
$.post('', { message: $('#msg').val() })
//// empty post('') means post to the default controller,
///we are not pacifying different action or controller
/// however we can define a url as following:
/// var url = "@(Url.Action("GetDataAction", "GetDataController"))"
.done(function (response) {
$("#myform").html(response);
})
.error(function () { alert('Error') })
.success(function () { alert('OK') })
return false;
});
Now let's say you want to do it using $.Ajax and JSON:
// Post JSON data add using System.Net;
[HttpPost]
public JsonResult JsonFullName(string fname, string lastname)
{
var data = "{ \"fname\" : \"" + fname + " \" , \"lastname\" : \"" + lastname + "\" }";
//// you have to add the JsonRequestBehavior.AllowGet
//// otherwise it will throw an exception on run-time.
return Json(data, JsonRequestBehavior.AllowGet);
}
Then, inside your view: add the event click on a an input of type button, or even a from submit: Just make sure your JSON data is well formatted.
$("#jsonGetfullname").on("click", function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "@(Url.Action("JsonFullName", "Home"))",
data: "{ \"fname\" : \"Mahmoud\" , \"lastname\" : \"Sayed\" }",
dataType: "json",
success: function (data) {
var res = $.parseJSON(data);
$("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
})
});
another simple approach with modern built-in stuff like PercentRelativeLayout is now available for new users who hit this problem. thanks to android team for release this item.
<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
app:layout_widthPercent="50%">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop" />
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#55000000"
android:paddingBottom="15dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:textColor="@android:color/white" />
</FrameLayout>
and for better performance you can use some stuff like picasso image loader which help you to fill whole width of every image parents. for example in your adapter you should use this:
int width= context.getResources().getDisplayMetrics().widthPixels;
com.squareup.picasso.Picasso
.with(context)
.load("some url")
.centerCrop().resize(width/2,width/2)
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(item.drawableId);
now you dont need CustomImageView Class anymore.
P.S i recommend to use ImageView in place of Type Int in class Item.
hope this help..
Here is my implementation in C#:
public static PointF PointOnCircle(float radius, float angleInDegrees, PointF origin)
{
// Convert from degrees to radians via multiplication by PI/180
float x = (float)(radius * Math.Cos(angleInDegrees * Math.PI / 180F)) + origin.X;
float y = (float)(radius * Math.Sin(angleInDegrees * Math.PI / 180F)) + origin.Y;
return new PointF(x, y);
}
The syntax for creating a new table is
CREATE TABLE new_table
AS
SELECT *
FROM old_table
This will create a new table named new_table
with whatever columns are in old_table
and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.
SELECT INTO
is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.
Here is an updated version of Paul Burke's answer. In versions below Android 4.4 (KitKat) we don't have the DocumentsContract class.
In order to work on versions below KitKat create this class:
public class DocumentsContract {
private static final String DOCUMENT_URIS =
"com.android.providers.media.documents " +
"com.android.externalstorage.documents " +
"com.android.providers.downloads.documents " +
"com.android.providers.media.documents";
private static final String PATH_DOCUMENT = "document";
private static final String TAG = DocumentsContract.class.getSimpleName();
public static String getDocumentId(Uri documentUri) {
final List<String> paths = documentUri.getPathSegments();
if (paths.size() < 2) {
throw new IllegalArgumentException("Not a document: " + documentUri);
}
if (!PATH_DOCUMENT.equals(paths.get(0))) {
throw new IllegalArgumentException("Not a document: " + documentUri);
}
return paths.get(1);
}
public static boolean isDocumentUri(Uri uri) {
final List<String> paths = uri.getPathSegments();
Logger.v(TAG, "paths[" + paths + "]");
if (paths.size() < 2) {
return false;
}
if (!PATH_DOCUMENT.equals(paths.get(0))) {
return false;
}
return DOCUMENT_URIS.contains(uri.getAuthority());
}
}
For SOA system architecture, I use the SOACP Visio stencil. It provides the symbols that are used in Thomas Erl's SOA book series.
I use the Visio Network and Database stencils to model most other requirements.
Mark's solution can be quite expensive since it needs to synchronize everytime.
We can get around the need for synchronization by using the thread-specific storage pattern:
public class RandomNumber : IRandomNumber
{
private static readonly Random Global = new Random();
[ThreadStatic] private static Random _local;
public int Next(int max)
{
var localBuffer = _local;
if (localBuffer == null)
{
int seed;
lock(Global) seed = Global.Next();
localBuffer = new Random(seed);
_local = localBuffer;
}
return localBuffer.Next(max);
}
}
Measure the two implementations and you should see a significant difference.
msg * /time:0 /w Hello everybody!
This message waits forever until OK is clicked (it lasts only one minute by default) and works fine in Windows 8.1
If you're seeing these in a source be aware that it may be someone attempting to fingerprint text documents to reveal who is leaking information. It also may be an attempt to bypass a spam filter by making the same looking information different on a byte-by-byte level.
See my article on mitigating fingerprinting if you're interested in learning more.
This can be done in three steps:
// 1. Read the content of the file
string[] readText = File.ReadAllLines(path);
// 2. Empty the file
File.WriteAllText(path, String.Empty);
// 3. Fill up again, but without the deleted line
using (StreamWriter writer = new StreamWriter(path))
{
foreach (string s in readText)
{
if (!s.Equals(lineToBeRemoved))
{
writer.WriteLine(s);
}
}
}
The most readable CSS-only solution would probably be to use the aria-expanded attribute. Remember that you'll need to add aria-expanded="false" to all collapse-elements as this is not set on load (only on first click).
<h2 data-toggle="collapse" href="#collapseId" aria-expanded="false">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="glyphicon glyphicon-chevron-down"></span> Title
</h2>
h2[aria-expanded="false"] span.glyphicon-chevron-down,
h2[aria-expanded="true"] span.glyphicon-chevron-right
{
display: none;
}
h2[aria-expanded="true"] span.glyphicon-chevron-down,
h2[aria-expanded="false"] span.glyphicon-chevron-right
{
display: inline;
}
Works with Bootstrap 3.x.
gradle.properties:
theGroup=some.group
theName=someName
theVersion=1.0
theSourceCompatibility=1.6
settings.gradle:
rootProject.name = theName
build.gradle:
apply plugin: "java"
group = theGroup
version = theVersion
sourceCompatibility = theSourceCompatibility
Undeclared variable (without var
) are treated as properties of the global object. (Usually the window
object, unless you're in a with
block)
Variables declared with var
are normal local variables, and are not visible outside the function they're declared in. (Note that Javascript does not have block scope)
Update: ECMAScript 2015
let
was introduced in ECMAScript 2015 to have block scope.
If you only want to log the query, then add 'logger' and 'profileSQL' to the jdbc url:
&logger=com.mysql.jdbc.log.Slf4JLogger&profileSQL=true
Then you will get the SQL statement below:
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 999 resultset: 0
2016-01-14 10:09:43 INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 999 resultset: 0 message: SET sql_mode='NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES'
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 999 resultset: 0
2016-01-14 10:09:43 INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 2 connection: 19130945 statement: 13 resultset: 17 message: select 1
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 0 connection: 19130945 statement: 13 resultset: 17
2016-01-14 10:09:43 INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 15 resultset: 18 message: select @@session.tx_read_only
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 0 connection: 19130945 statement: 15 resultset: 18
2016-01-14 10:09:43 INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 2 connection: 19130945 statement: 14 resultset: 0 message: update sequence set seq=seq+incr where name='demo' and seq=4602
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 0 connection: 19130945 statement: 14 resultset: 0
The default logger is:
com.mysql.jdbc.log.StandardLogger
Mysql jdbc property list: https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html
This function should do what you want:
char* readLine( FILE* file )
{
char buffer[1024];
char* result = 0;
int length = 0;
while( !feof(file) )
{
fgets( buffer, sizeof(buffer), file );
int len = strlen(buffer);
buffer[len] = 0;
length += len;
char* tmp = (char*)malloc(length+1);
tmp[0] = 0;
if( result )
{
strcpy( tmp, result );
free( result );
result = tmp;
}
strcat( result, buffer );
if( strstr( buffer, "\n" ) break;
}
return result;
}
char* line = readLine( stdin );
/* Use it */
free( line );
I hope this helps.
If you want to work with $?
, you'll need to check it after each command, since $?
is updated after each command exits. This means that if you execute a pipeline, you'll only get the exit code of the last process in the pipeline.
Another approach is to do this:
set -e
set -o pipefail
If you put this at the top of the shell script, it looks like Bash will take care of this for you. As a previous poster noted, "set -e" will cause Bash to exit with an error on any simple command. "set -o pipefail" will cause Bash to exit with an error on any command in a pipeline as well.
See here or here for a little more discussion on this problem. Here is the Bash manual section on the set
builtin.
You can use -i''
(--in-place
) for sed
as already suggested. See: The -i
in-place argument, however note that -i
option is non-standard FreeBSD extensions and may not be available on other operating systems. Secondly sed
is a Stream EDitor, not a file editor.
Alternative way is to use built-in substitution in Vim Ex mode, like:
$ ex +%s/foo/bar/g -scwq file.txt
and for multiple-files:
$ ex +'bufdo!%s/foo/bar/g' -scxa *.*
To edit all files recursively you can use **/*.*
if shell supports that (enable by shopt -s globstar
).
Another way is to use gawk
and its new "inplace" extension such as:
$ gawk -i inplace '{ gsub(/foo/, "bar") }; { print }' file1
I suggest you to first try to understand Java 8 in the whole picture, most importantly in your case it will be streams, lambdas and method references.
You should never convert existing code to Java 8 code on a line-by-line basis, you should extract features and convert those.
What I identified in your first case is the following:
Let's see how we do that, we can do it with the following:
List<Player> playersOfTeam = players.stream()
.filter(player -> player.getTeam().equals(teamName))
.collect(Collectors.toList());
What you do here is:
Collection<Player>
, now you have a Stream<Player>
.Predicate<Player>
, mapping every player to the boolean true if it is wished to be kept.Collector
, here we can use one of the standard library collectors, which is Collectors.toList()
.This also incorporates two other points:
List<E>
over ArrayList<E>
.new ArrayList<>()
, you are using Java 8 after all.Now onto your second point:
You again want to convert something of legacy Java to Java 8 without looking at the bigger picture. This part has already been answered by @IanRoberts, though I think that you need to do players.stream().filter(...)...
over what he suggested.
by using replaceChild():
<html>
<head>
</head>
<body>
<div>
<a id="myAnchor" href="http://www.stackoverflow.com">StackOverflow</a>
</div>
<script type="text/JavaScript">
var myAnchor = document.getElementById("myAnchor");
var mySpan = document.createElement("span");
mySpan.innerHTML = "replaced anchor!";
myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
</body>
</html>
I don't think your going to get valueOf("Start Here") to work. But as far as spaces...try the following...
static private enum RandomEnum {
R("Start There"),
G("Start Here");
String value;
RandomEnum(String s) {
value = s;
}
}
System.out.println(RandomEnum.G.value);
System.out.println(RandomEnum.valueOf("G").value);
Start Here
Start Here
Use PHP_EOL
which outputs \r\n
or \n
depending on the OS.
IEEE 754 floating point values are stored using base 2 representation. Any base 2 number can be represented as a decimal (base 10) to full precision. None of the proposed answers, however, do. They all truncate the decimal value.
This seems to be due to a misinterpretation of what std::numeric_limits<T>::max_digits10
represents:
The value of
std::numeric_limits<T>::max_digits10
is the number of base-10 digits that are necessary to uniquely represent all distinct values of the typeT
.
In other words: It's the (worst-case) number of digits required to output if you want to roundtrip from binary to decimal to binary, without losing any information. If you output at least max_digits10
decimals and reconstruct a floating point value, you are guaranteed to get the exact same binary representation you started with.
What's important: max_digits10
in general neither yields the shortest decimal, nor is it sufficient to represent the full precision. I'm not aware of a constant in the C++ Standard Library that encodes the maximum number of decimal digits required to contain the full precision of a floating point value. I believe it's something like 767 for double
s1. One way to output a floating point value with full precision would be to use a sufficiently large value for the precision, like so2, and have the library strip any trailing zeros:
#include <iostream>
int main() {
double d = 0.1;
std::cout.precision(767);
std::cout << "d = " << d << std::endl;
}
This produces the following output, that contains the full precision:
d = 0.1000000000000000055511151231257827021181583404541015625
Note that this has significantly more decimals than max_digits10
would suggest.
While that answers the question that was asked, a far more common goal would be to get the shortest decimal representation of any given floating point value, that retains all information. Again, I'm not aware of any way to instruct the Standard I/O library to output that value. Starting with C++17 the possibility to do that conversion has finally arrived in C++ in the form of std::to_chars
. By default, it produces the shortest decimal representation of any given floating point value that retains the entire information.
Its interface is a bit clunky, and you'd probably want to wrap this up into a function template that returns something you can output to std::cout
(like a std::string
), e.g.
#include <charconv>
#include <array>
#include <string>
#include <system_error>
#include <iostream>
#include <cmath>
template<typename T>
std::string to_string(T value)
{
// 24 characters is the longest decimal representation of any double value
std::array<char, 24> buffer {};
auto const res { std::to_chars(buffer.data(), buffer.data() + buffer.size(), value) };
if (res.ec == std::errc {})
{
// Success
return std::string(buffer.data(), res.ptr);
}
// Error
return { "FAILED!" };
}
int main()
{
auto value { 0.1f };
std::cout << to_string(value) << std::endl;
value = std::nextafter(value, INFINITY);
std::cout << to_string(value) << std::endl;
value = std::nextafter(value, INFINITY);
std::cout << to_string(value) << std::endl;
}
This would print out (using Microsoft's C++ Standard Library):
0.1
0.10000001
0.10000002
1 From Stephan T. Lavavej's CppCon 2019 talk titled Floating-Point <charconv>: Making Your Code 10x Faster With C++17's Final Boss. (The entire talk is worth watching.)
2 This would also require using a combination of scientific
and fixed
, whichever is shorter. I'm not aware of a way to set this mode using the C++ Standard I/O library.
For a list, you could use the Google Guava Library:
for (String item : Lists.reverse(stringList))
{
// ...
}
Note that Lists.reverse
doesn't reverse the whole collection, or do anything like it - it just allows iteration and random access, in the reverse order. This is more efficient than reversing the collection first.
To reverse an arbitrary iterable, you'd have to read it all and then "replay" it backwards.
(If you're not already using it, I'd thoroughly recommend you have a look at the Guava. It's great stuff.)
I really like the accepted answer. I believe there is yet another way to approach this as well. Let's say you have a very short list of properties that you wouldn't want to ever include in a View, so when updating the entity, those would be omitted. Let's say that those two fields are Password and SSN.
db.Users.Attach(updatedUser);
var entry = db.Entry(updatedUser);
entry.State = EntityState.Modified;
entry.Property(e => e.Password).IsModified = false;
entry.Property(e => e.SSN).IsModified = false;
db.SaveChanges();
This example allows you to essentially leave your business logic alone after adding a new field to your Users table and to your View.
In my case the error was probably due to an incorrect merge between .gitmodules on two branches with different submodules configurations. After taking suggestions from this forum, I solved the problem editing manually the .gitmodules file, adding the missing submodule entry is pretty easy. After that, the command git submodule update --init --recursive worked with no issues.
I would like to recommend flask-empty at GitHub.
It provides an easy way to understand Blueprints, multiple views and extensions.
This is working
<form name="myform" ng-submit="create()">
<input type="number"
name="price_field"
ng-model="price"
require
ng-pattern="/^\d{0,9}(\.\d{1,9})?$/">
<span ng-show="myform.price_field.$error.pattern">Not valid number!</span>
<input type="submit" class="btn">
</form>
Robocopy, or "Robust File Copy", is a command-line directory and/or file replication command. Robocopy functionally replaces Xcopy, with more options. It has been available as part of the Windows Resource Kit starting with Windows NT 4.0, and was first introduced as a standard feature in Windows Vista and Windows Server 2008. The command is
robocopy
...
var currentDate = moment('2015-10-30');
var futureMonth = moment(currentDate).add(1, 'M');
var futureMonthEnd = moment(futureMonth).endOf('month');
if(currentDate.date() != futureMonth.date() && futureMonth.isSame(futureMonthEnd.format('YYYY-MM-DD'))) {
futureMonth = futureMonth.add(1, 'd');
}
console.log(currentDate);
console.log(futureMonth);
EDIT
moment.addRealMonth = function addRealMonth(d) {
var fm = moment(d).add(1, 'M');
var fmEnd = moment(fm).endOf('month');
return d.date() != fm.date() && fm.isSame(fmEnd.format('YYYY-MM-DD')) ? fm.add(1, 'd') : fm;
}
var nextMonth = moment.addRealMonth(moment());
You can do it like this:
label.font = UIFont(name: label.font.fontName, size: 20)
Or like this:
label.font = label.font.withSize(20)
This will use the same font. 20 can be whatever size you want of course.
Note: The latter option will overwrite the current font weight to regular
so if you want to preserve the font weight use the first option.
Swift 3 Update:
label.font = label.font.withSize(20)
Swift 4 Update:
label.font = label.font.withSize(20)
or
label.font = UIFont(name:"fontname", size: 20.0)
and if you use the system fonts
label.font = UIFont.systemFont(ofSize: 20.0)
label.font = UIFont.boldSystemFont(ofSize: 20.0)
label.font = UIFont.italicSystemFont(ofSize: 20.0)
Any chance your IIS is configured to require SSL on connections to your site/application?
You have two options for displaying the Map
For showing local POIs around a Lat, Long use Places APIs
Postman doesn't do that but you can run multiple curl
requests asynchronously in Bash:
curl url1 & curl url2 & curl url3 & ...
Remember to add an &
after each request which means that request should run as an async job.
Postman however can generate curl snippet for your request: https://learning.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets/
Update to angular 4.X.X, there is a new way to mark an option selected:
<select [compareWith]="byId" [(ngModel)]="selectedItem">
<option *ngFor="let item of items" [ngValue]="item">{{item.name}}
</option>
</select>
byId(item1: ItemModel, item2: ItemModel) {
return item1.id === item2.id;
}
Some tutorial here
I do know that the account needs to have "Log on as a Service" privileges. Other than that, I'm not sure. A quick reference to Log on as a Service can be found here, and there is a lot of information of specific privileges here.
HTML Comments:
<!-- <div> This div will not show </div> -->
CSS Comments:
/* This style will not apply */
JavaScript Comments:
// This single line JavaScript code will not execute
OR
/*
The whole block of JavaScript code will not execute
*/
Based on solution You've already found How to apply CSS to iframe?:
var cssLink = document.createElement("link")
cssLink.href = "file://path/to/style.css";
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
frames['iframe'].document.body.appendChild(cssLink);
or more jqueryish (from Append a stylesheet to an iframe with jQuery):
var $head = $("iframe").contents().find("head");
$head.append($("<link/>",
{ rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));
as for security issues: Disabling same-origin policy in Safari
A tip that may save you a lot of time - don't forget that even if you choose debug
under the build configuration (on vs2012/13 menu it's under BUILD => CONFIGURATION MANAGER) - that's not enough.
You need to pay attention to the PUBLISH Configuration
, as such:
This works for me for a single column
$('#example').dataTable( {
"aoColumns": [
{ "bSortable": false
}]});
To solve this problem, I store dates as YYYYMMDD
. Thus,
where mydate >= '20090101' and mydate <= '20050505'
It just plain WORKS all the time. You may only need to write a parser to handle how users might enter their dates so you can convert them to YYYYMMDD
.
Then the Android Device Monitor window will pop up. Click on the emulator & File Explorer.
Shared Preference files should be in:
DDMS-> File Explorer ->data -> data -> MY_PACKAGE_NAME -> shared_prefs -> YOUR_PREFERENCE_NAME.xml
check out
http://www.thesitewizard.com/general/set-cron-job.shtml
for the specifics of setting your crontab directives.
45 10 * * *
will run in the 10th hour, 45th minute of every day.
for midnight... maybe
0 0 * * *
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
worked!
Like most form controls in HTML, the results of applying CSS to <select>
and <option>
elements vary a lot between browsers. Chrome, as you've found, won't let you apply and font styles to an <option>
element directly --- if you do Inspect Element on it, you'll see the font-size: 14px
declaration is crossed through as if it's been overridden by the cascade, but it's actually because Chrome is ignoring it.
However, Chrome will let you apply font styles to the <optgroup>
element, so to achieve the result you want you can wrap all the <option>
s in an <optgroup>
and then apply your font styles to a .styled-select optgroup
selector. If you want the optgroup sans-label, you may have to do some clever CSS with positioning or something to hide the white area at the top where the label would be shown, but that should be possible.
Forked to a new JSFiddle to show you what I mean:
Just use the following
Server.MapPath("~/Data/data.html")
I can see many answers showing how to solve problem, but only Stephen's answer is trying to explain why problem occurs so I will try to add something more on this subject. It is a story about possible reasons why Object[] toArray
wasn't changed to T[] toArray
where generics ware introduced to Java.
String[] stockArr = (String[]) stock_list.toArray();
wont work?In Java, generic type exists at compile-time only. At runtime information about generic type (like in your case <String>
) is removed and replaced with Object
type (take a look at type erasure). That is why at runtime toArray()
have no idea about what precise type to use to create new array, so it uses Object
as safest type, because each class extends Object so it can safely store instance of any class.
Object[]
to String[]
.Why? Take a look at this example (lets assume that class B extends A
):
//B extends A
A a = new A();
B b = (B)a;
Although such code will compile, at runtime we will see thrown ClassCastException
because instance held by reference a
is not actually of type B
(or its subtypes). Why is this problem (why this exception needs to be cast)? One of the reasons is that B
could have new methods/fields which A
doesn't, so it is possible that someone will try to use these new members via b
reference even if held instance doesn't have (doesn't support) them. In other words we could end up trying to use data which doesn't exist, which could lead to many problems. So to prevent such situation JVM throws exception, and stop further potentially dangerous code.
You could ask now "So why aren't we stopped even earlier? Why code involving such casting is even compilable? Shouldn't compiler stop it?". Answer is: no because compiler can't know for sure what is the actual type of instance held by a
reference, and there is a chance that it will hold instance of class B
which will support interface of b
reference. Take a look at this example:
A a = new B();
// ^------ Here reference "a" holds instance of type B
B b = (B)a; // so now casting is safe, now JVM is sure that `b` reference can
// safely access all members of B class
Now lets go back to your arrays. As you see in question, we can't cast instance of Object[]
array to more precise type String[]
like
Object[] arr = new Object[] { "ab", "cd" };
String[] arr2 = (String[]) arr;//ClassCastException will be thrown
Here problem is a little different. Now we are sure that String[]
array will not have additional fields or methods because every array support only:
[]
operator,length
filed,So it is not arrays interface which is making it impossible. Problem is that Object[]
array beside Strings
can store any objects (for instance Integers
) so it is possible that one beautiful day we will end up with trying to invoke method like strArray[i].substring(1,3)
on instance of Integer
which doesn't have such method.
So to make sure that this situation will never happen, in Java array references can hold only
String[] strArr
can hold String[]
)Object[]
can hold String[]
because String
is subtype of Object
),but can't hold
String[]
can't hold Object[]
)Integer[]
can't hold String[]
)In other words something like this is OK
Object[] arr = new String[] { "ab", "cd" }; //OK - because
// ^^^^^^^^ `arr` holds array of subtype of Object (String)
String[] arr2 = (String[]) arr; //OK - `arr2` reference will hold same array of same type as
// reference
You could say that one way to resolve this problem is to find at runtime most common type between all list elements and create array of that type, but this wont work in situations where all elements of list will be of one type derived from generic one. Take a look
//B extends A
List<A> elements = new ArrayList<A>();
elements.add(new B());
elements.add(new B());
now most common type is B
, not A
so toArray()
A[] arr = elements.toArray();
would return array of B
class new B[]
. Problem with this array is that while compiler would allow you to edit its content by adding new A()
element to it, you would get ArrayStoreException
because B[]
array can hold only elements of class B
or its subclass, to make sure that all elements will support interface of B
, but instance of A
may not have all methods/fields of B
. So this solution is not perfect.
Best solution to this problem is explicitly tell what type of array toArray()
should be returned by passing this type as method argument like
String[] arr = list.toArray(new String[list.size()]);
or
String[] arr = list.toArray(new String[0]); //if size of array is smaller then list it will be automatically adjusted.
Or
import smtplib
from email.message import EmailMessage
from getpass import getpass
password = getpass()
message = EmailMessage()
message.set_content('Message content here')
message['Subject'] = 'Your subject here'
message['From'] = "USERNAME@DOMAIN"
message['To'] = "[email protected]"
try:
smtp_server = None
smtp_server = smtplib.SMTP("YOUR.MAIL.SERVER", 587)
smtp_server.ehlo()
smtp_server.starttls()
smtp_server.ehlo()
smtp_server.login("USERNAME@DOMAIN", password)
smtp_server.send_message(message)
except Exception as e:
print("Error: ", str(e))
finally:
if smtp_server is not None:
smtp_server.quit()
If you want to use Port 465 you have to create an SMTP_SSL
object.
public IEnumerable<Friend> FindFriends()
{
return userExists ? doc.Descendants("user").Select(user => new Friend
{
ID = user.Element("id").Value,
Name = user.Element("name").Value,
URL = user.Element("url").Value,
Photo = user.Element("photo").Value
}): new List<Friend>();
}
I just changed project facet to 1.7 and it worked.
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";
If Controls.Find is not found "textBox1" => error. You must add code.
If(tbx != null)
Edit:
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
If(tbx != null)
tbx.Text = "found!";
You can use the start (^
) and end ($
) of line indicators:
^[0-9]{2}$
Some language also have functions that allows you to match against an entire string, where-as you were using a find
function. Matching against the entire string will make your regex work as an alternative to the above. The above regex will also work, but the ^
and $
will be redundant.
I use an alpha-transparent PNG for that:
div.semi-transparent {
background: url('semi-transparent.png');
}
As a more general answer, try using the hasPrefix method. For example, the code below checks to see if a string begins with 10, which is the error code used to identify a certain problem.
NSString* myString = @"10:Username taken";
if([myString hasPrefix:@"10"]) {
//display more elegant error message
}
First, edit NetworkManager.conf file:
vim /etc/NetworkManager/NetworkManager.conf
Comment this line:
#dns=dnsmasq
Finally
sudo service network-manager restart
sudo service docker restart
This isn't as easy to do as one might expect -- you can really only do vertical alignment if you know the height of your container. IF this is the case, you can do it with absolute positioning.
The concept is to set the top / left positions at 50%, and then use negative margins (set to half the height / width) to pull the container back to being centered.
Example: http://jsbin.com/ipawe/edit
Basic CSS:
#mydiv {
position: absolute;
top: 50%;
left: 50%;
height: 400px;
width: 700px;
margin-top: -200px; /* -(1/2 height) */
margin-left: -350px; /* -(1/2 width) */
}
Use the flex-grow
property to make a flex item consume free space on the main axis.
This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.
A common example is flex-grow: 1
or, using the shorthand property, flex: 1
.
Hence, instead of width: 96%
on your div, use flex: 1
.
You wrote:
So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.
The squashing of the fixed-width div is related to another flex property: flex-shrink
By default, flex items are set to flex-shrink: 1
which enables them to shrink in order to prevent overflow of the container.
To disable this feature use flex-shrink: 0
.
For more details see The flex-shrink
factor section in the answer here:
Learn more about flex alignment along the main axis here:
Learn more about flex alignment along the cross axis here:
Assuming that "a" and "b" are bean properties
rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"
You may look at JSF EL operators
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
Use your console:
console.log(object);
Or if you are inspecting html dom elements use console.dir(object). Example:
let element = document.getElementById('alertBoxContainer');
console.dir(element);
Or if you have an array of js objects you could use:
console.table(objectArr);
If you are outputting a lot of console.log(objects) you can also write
console.log({ objectName1 });
console.log({ objectName2 });
This will help you label the objects written to console.
I would start by adding clearfix
class to the <div>
with panel-heading
class. Then, add both panel-title
and pull-left
to the H4
tag. Then, add padding-top
, as necessary.
Here's the complete code:
<div class="panel panel-default">
<div class="panel-heading clearfix">
<h4 class="panel-title pull-left" style="padding-top: 7.5px;">Panel header</h4>
<div class="btn-group pull-right">
<a href="#" class="btn btn-default btn-sm">## Lock</a>
<a href="#" class="btn btn-default btn-sm">## Delete</a>
<a href="#" class="btn btn-default btn-sm">## Move</a>
</div>
</div>
...
</div>
Should Return ActionResult, instead of Void
I was struggling with this question because I was looking for a way to do this in a bash script for OS X, hence /etc/passwd was out of the question, and my script was meant to be executed as root, therefore making the solutions invoking eval or bash -c dangerous as they allowed code injection into the variable specifying the username.
Here is what I found. It's simple and doesn't put a variable inside a subshell. However it does require the script to be ran by root as it sudos into the specified user account.
Presuming that $SOMEUSER contains a valid username:
echo "$(sudo -H -u "$SOMEUSER" -s -- "cd ~ && pwd")"
I hope this helps somebody!
There are two ways for case insensitive comparison:
===
). How strict operator treats operands read stuff at:
http://www.thesstech.com/javascript/relational-logical-operatorsUse the "search" string method for case insensitive search. Read about search and other string methods at: http://www.thesstech.com/pattern-matching-using-string-methods
<!doctype html>
<html>
<head>
<script>
// 1st way
var a = "apple";
var b = "APPLE";
if (a.toUpperCase() === b.toUpperCase()) {
alert("equal");
}
//2nd way
var a = " Null and void";
document.write(a.search(/null/i));
</script>
</head>
</html>
singletonList can hold instance of any object. Object state can be modify.
List<Character> list = new ArrayList<Character>();
list.add('X');
list.add('Y');
System.out.println("Initial list: "+ list);
List<List<Character>> list2 = Collections.singletonList(list);
list.add('Z');
System.out.println(list);
System.out.println(list2);
We can not define unmodifiableList like above.
>>> s = 'abcd'
>>> len(s)
4
On a Mac do this:
cmd + , or ADT -> Preferences
Expand General -> Editors ->Text Editors
Check box: Show line numbers
find /folder -type f -mtime -90 | grep -E "(.txt|.php|.inc|.root|.gif)" | xargs ls -l > WWWlastActivity.log
In my case the following worked:
rm -rf node_modules
rm package-lock.json
npm install
Hence the npm install
, not update.
It's just a syntax error. You just have to replace j+3
by j=j+3
or j+=3
.
For WampServer, click on its tray icon and then in the popup cascading menu select
MySQL | MySQL settings | datadir
The lightweight MooTools framework has one: http://demos.mootools.net/Slider
Look at http://docs.oracle.com/cd/B10501_01/server.920/a96521/privs.htm#15665
Check USER_SYS_PRIVS, USER_TAB_PRIVS, USER_ROLE_PRIVS tables with these select statements
SELECT * FROM USER_SYS_PRIVS;
SELECT * FROM USER_TAB_PRIVS;
SELECT * FROM USER_ROLE_PRIVS;
Setting the identity only makes this work in my pages.
You need to call the hasOwnProperty
function to check whether the property is actually defined on the object itself (as opposed to its prototype), like this:
for (var key in widthRange) {
if (key === 'length' || !widthRange.hasOwnProperty(key)) continue;
var value = widthRange[key];
}
Note that you need a separate check for length
.
However, you shouldn't be using an array here at all; you should use a regular object. All Javascript objects function as associative arrays.
For example:
var widthRange = { }; //Or new Object()
widthRange[46] = { sel:46, min:0, max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };
MySqldb python install windows
MySQL-python 1.2.3 for Windows and Python 2.7, 32bit and 64bit versions
This is another way for disabling constraints (it came from https://asktom.oracle.com/pls/asktom/f?p=100:11:2402577774283132::::P11_QUESTION_ID:399218963817)
WITH qry0 AS
(SELECT 'ALTER TABLE '
|| child_tname
|| ' DISABLE CONSTRAINT '
|| child_cons_name
disable_fk
, 'ALTER TABLE '
|| parent_tname
|| ' DISABLE CONSTRAINT '
|| parent.parent_cons_name
disable_pk
FROM (SELECT a.table_name child_tname
,a.constraint_name child_cons_name
,b.r_constraint_name parent_cons_name
,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) child_columns
FROM user_cons_columns a
,user_constraints b
WHERE a.constraint_name = b.constraint_name AND b.constraint_type = 'R'
GROUP BY a.table_name, a.constraint_name
,b.r_constraint_name) child
,(SELECT a.constraint_name parent_cons_name
,a.table_name parent_tname
,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) parent_columns
FROM user_cons_columns a
,user_constraints b
WHERE a.constraint_name = b.constraint_name AND b.constraint_type IN ('P', 'U')
GROUP BY a.table_name, a.constraint_name) parent
WHERE child.parent_cons_name = parent.parent_cons_name
AND (parent.parent_tname LIKE 'V2_%' OR child.child_tname LIKE 'V2_%'))
SELECT DISTINCT disable_pk
FROM qry0
UNION
SELECT DISTINCT disable_fk
FROM qry0;
works like a charm
Copy the btn_check.xml from android-sdk/platforms/android-#/data/res/drawable to your project's drawable folder and change the 'on' and 'off' image states to your custom images.
Then your xml will just need android:button="@drawable/btn_check"
<CheckBox
android:button="@drawable/btn_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true" />
If you want to use different default android icons, you can use android:button="@android:drawable/..."
The only way to fix this issue for my bootstrap modal (containing a form) was to add the following code to my CSS:
.modal {
-webkit-overflow-scrolling: auto!important;
}
As described in Documentation Environment.getExternalStorageDirectory() :
Environment.getExternalStorageDirectory() Return the primary shared/external storage directory.
This is an example of how to use it reading an image :
String fileName = "stored_image.jpg";
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String pathDir = baseDir + "/Android/data/com.mypackage.myapplication/";
File f = new File(pathDir + File.separator + fileName);
if(f.exists()){
Log.d("Application", "The file " + file.getName() + " exists!";
}else{
Log.d("Application", "The file no longer exists!";
}
ex="test1,test2,test3,test4,test5"
all_but_first=ex.split(/,/)[1..-1]
When you say "doesn't work", how do you know it doesn't work?
You might try to figure out if the file actually exists by adding:
while [ ! -f /tmp/list.txt ]
do
sleep 2 # or less like 0.2
done
ls -l /tmp/list.txt
You might also make sure that you're using a Bash (or related) shell by typing 'echo $SHELL'. I think that CSH and TCSH use a slightly different semantic for this loop.
1- Select LinearLayout findViewById
LinearLayout llayout =(LinearLayout) findViewById(R.id.llayoutId);
2- Set color from R.color.colorId
llayout.setBackgroundColor(getResources().getColor(R.color.colorId));
If none of the above method worked then try this it worked for me.
Go to File > Project Structure> Project and then in Project Compiler Output click on the three dots and provide the path of your project name(name of the file) and then click on Apply and than on Ok.
I ran into this issue when I wanted to temporarily disable the sending of an email while working on another part of the code.
Commenting the use of the service triggered a lot of cascade errors, so instead of commenting I used a condition
if false {
// Technically, svc still be used so no yelling
_, err = svc.SendRawEmail(input)
Check(err)
}
Use In
instead of =
select * from dbo.books
where isbn in (select isbn from dbo.lending
where act between @fdate and @tdate
and stat ='close'
)
or you can use Exists
SELECT t1.*,t2.*
FROM books t1
WHERE EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
t2.act between @fdate and @tdate and t2.stat ='close' )
Python actually makes this quite easy.
Something like
for i in range(10):
print '%-12i%-12i' % (10 ** i, 20 ** i)
will have the output
1 1
10 20
100 400
1000 8000
10000 160000
100000 3200000
1000000 64000000
10000000 1280000000
100000000 25600000000
1000000000 512000000000
The % within the string is essentially an escape character and the characters following it tell python what kind of format the data should have. The % outside and after the string is telling python that you intend to use the previous string as the format string and that the following data should be put into the format specified.
In this case I used "%-12i" twice. To break down each part:
'-' (left align)
'12' (how much space to be given to this part of the output)
'i' (we are printing an integer)
From the docs: https://docs.python.org/2/library/stdtypes.html#string-formatting
It looks as if you were on the right track. You just need to add the else statement after the ";" following the "then" statement. Also I would split the first line from the second line with a semicolon instead of joining it with "&&".
maxline='cat journald.conf | grep "#SystemMaxUse="'; if [ $maxline == "#SystemMaxUse=" ]; then sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf > journald.conf2 && mv journald.conf2 journald.conf; else echo "This file has been edited. You'll need to do it manually."; fi
Also in your original script, when declaring maxline you used back-ticks "`" instead of single quotes "'" which might cause problems.
Looper.myLooper() == Looper.getMainLooper()
if this returns true, then you're on the UI thread!
In addition to a performance considerations, there's a functional difference too. When you join comments, you are asking for posts that have comments- an inner join by default. When you include comments, you are asking for all posts- an outer join.
Put in head link to google styles
<link href="https://fonts.googleapis.com/icon?family=Material+Icons+Outlined" rel="stylesheet">
and in body something like this
<i class="material-icons-outlined">bookmarks</i>
No Dapper answer here. So I added one
using Dapper;
using System.Data.SqlClient;
using (var cn = new SqlConnection(@"Server=(local);DataBase=master;Integrated Security=SSPI"))
cn.Execute("dbo.test", commandType: CommandType.StoredProcedure);
iPad Multitasking support requires all the orientations but your app does not, so you need to opt out of it, just add the UIRequiresFullScreen
key to your Xcode project’s Info.plist
file and apply the Boolean value YES
.
Dim psValue As String = "1,5,12,34,123,12"
psValue = psValue.Substring(0, psValue.LastIndexOf(","))
output:
1,5,12,34,123