When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
I've faced the exactly same problem but I've fixed it with another approache.
Using Ubuntu 18.04, first disable systemd-resolved
service.
sudo systemctl disable systemd-resolved.service
Stop the service
sudo systemctl stop systemd-resolved.service
Then, remove the link to /run/systemd/resolve/stub-resolv.conf
in /etc/resolv.conf
sudo rm /etc/resolv.conf
Add a manually created resolv.conf
in /etc/
sudo vim /etc/resolv.conf
Add your prefered DNS server there
nameserver 208.67.222.222
I've tested this with success.
Xiaomi MIUI.
Options - Permissions - Install via USB (not the same item in Developers options!) then uncheck your disabled app
npm i cors
const app = require('express')()
app.use(cors())
Above code worked for me.
I ran into this using networkx
and bokeh
This works for me in Windows 7 (taken from here):
To create a jupyter_notebook_config.py file, with all the defaults commented out, you can use the following command line:
$ jupyter notebook --generate-config
Open the file and search for c.NotebookApp.iopub_data_rate_limit
Comment out the line c.NotebookApp.iopub_data_rate_limit = 1000000
and change it to a higher default rate. l used c.NotebookApp.iopub_data_rate_limit = 10000000
This unforgiving default config is popping up in a lot of places. See git issues:
It looks like it might get resolved with the 5.1 release
Jupyter notebook is now on release 5.2.2
. This problem should have been resolved. Upgrade using conda or pip.
Never thought MS could distribute this way, I understand that people downloading Visual Studio should have advanced knowledge of computers and OS but this is like a jump in time to 30 years back.
Found this post: "Breaking changes" in angular 9. All modules must be imported separately. Also a fine module available there, thanks to @jeff-gilliland: https://stackoverflow.com/a/60111086/824622
An alternative to this:
async function main() {
try {
var quote = await getQuote();
console.log(quote);
} catch (error) {
console.error(error);
}
}
would be something like this, using promises explicitly:
function main() {
getQuote().then((quote) => {
console.log(quote);
}).catch((error) => {
console.error(error);
});
}
or something like this, using continuation passing style:
function main() {
getQuote((error, quote) => {
if (error) {
console.error(error);
} else {
console.log(quote);
}
});
}
What your original code does is suspend the execution and wait for the promise returned by getQuote()
to settle. It then continues the execution and writes the returned value to var quote
and then prints it if the promise was resolved, or throws an exception and runs the catch block that prints the error if the promise was rejected.
You can do the same thing using the Promise API directly like in the second example.
Now, for the performance. Let's test it!
I just wrote this code - f1()
gives 1
as a return value, f2()
throws 1
as an exception:
function f1() {
return 1;
}
function f2() {
throw 1;
}
Now let's call the same code million times, first with f1()
:
var sum = 0;
for (var i = 0; i < 1e6; i++) {
try {
sum += f1();
} catch (e) {
sum += e;
}
}
console.log(sum);
And then let's change f1()
to f2()
:
var sum = 0;
for (var i = 0; i < 1e6; i++) {
try {
sum += f2();
} catch (e) {
sum += e;
}
}
console.log(sum);
This is the result I got for f1
:
$ time node throw-test.js
1000000
real 0m0.073s
user 0m0.070s
sys 0m0.004s
This is what I got for f2
:
$ time node throw-test.js
1000000
real 0m0.632s
user 0m0.629s
sys 0m0.004s
It seems that you can do something like 2 million throws a second in one single-threaded process. If you're doing more than that then you may need to worry about it.
I wouldn't worry about things like that in Node. If things like that get used a lot then it will get optimized eventually by the V8 or SpiderMonkey or Chakra teams and everyone will follow - it's not like it's not optimized as a principle, it's just not a problem.
Even if it isn't optimized then I'd still argue that if you're maxing out your CPU in Node then you should probably write your number crunching in C - that's what the native addons are for, among other things. Or maybe things like node.native would be better suited for the job than Node.js.
I'm wondering what would be a use case that needs throwing so many exceptions. Usually throwing an exception instead of returning a value is, well, an exception.
The date time you're passing is not a iso local date time format.
Change to
@Column(name = "start_date")
@DateTimeFormat(iso = DateTimeFormatter.ISO_LOCAL_DATE_TIME)
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime startDate;
and pass date string in the format '2011-12-03T10:15:30'.
But if you still want to pass your custom format, use just have to specify the right formatter.
Change to
@Column(name = "start_date")
@DateTimeFormat(iso = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime startDate;
I think your problem is the @DateTimeFormat has no effect at all. As the jackson is doing the deseralization and it doesnt know anything about spring annotation and I dont see spring scanning this annotation in the deserialization context.
Alternatively, you can try setting the formatter while registering the java time module.
LocalDateTimeDeserializer localDateTimeDeserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);
Here is the test case with the deseralizer which works fine. May be try to get rid of that DateTimeFormat annotation altogether.
@RunWith(JUnit4.class)
public class JacksonLocalDateTimeTest {
private ObjectMapper objectMapper;
@Before
public void init() {
JavaTimeModule module = new JavaTimeModule();
LocalDateTimeDeserializer localDateTimeDeserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);
objectMapper = Jackson2ObjectMapperBuilder.json()
.modules(module)
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
}
@Test
public void test() throws IOException {
final String json = "{ \"date\": \"2016-11-08 12:00\" }";
final JsonType instance = objectMapper.readValue(json, JsonType.class);
assertEquals(LocalDateTime.parse("2016-11-08 12:00",DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") ), instance.getDate());
}
}
class JsonType {
private LocalDateTime date;
public LocalDateTime getDate() {
return date;
}
public void setDate(LocalDateTime date) {
this.date = date;
}
}
In my case, the issue was of unsupported java version
Check the file /etc/init.d/jenkins
to find out which java versions are supported.
To find which java versions are supported, run
grep -m 1 "JAVA_ALLOWED_VERSIONS" /etc/init.d/jenkins
The output will be like this(your's might be different)
JAVA_ALLOWED_VERSIONS=( "1.8" "11" )
In my case version 1.8 and 11 are supported. I will be going with version 11.
Install the supported version of jre using command
For ubuntu/debian
sudo apt install openjdk-11-jre
For centOS use
sudo yum install java-11-openjdk-devel
Find the path to newly installed jre
For ubuntu/debian path is
/usr/lib/jvm/java-11-openjdk-amd64/bin/java
You can find the path on centOS under /usr/lib/jvm/
Modify the file /etc/init.d/jenkins
At line number 28, replace the JAVA=`type -p java`
with JAVA='/usr/lib/jvm/java-11-openjdk-amd64/bin/java'
Now run command to reload the systemctl daemon
sudo systemctl daemon-reload
Start the jenkins service
sudo systemctl start jenkins
I could also fix this. PYTHONPATH and PYTHONHOME were in cause.
run this in a terminal
touch ~/.bash_profile
open ~/.bash_profile
and then delete all useless parts of this file, and save. I do not know how recommended it is to do that !
the steps I followed are:
Android Studio
(or IntelliJ IDEA
).idea
directory.gradle
directory.iml
files
find . | grep -e .iml$ | xargs rm
Android Studio
to re-open the directory as a projectTerminal commands:
# close Android Studio
cd "your project's directory"
rm -rf ./.idea
rm -rf ./.gradle
find . | grep -e .iml$ | xargs rm
# use Android Studio to re-open the directory as a project
Set a local value with the observer
...also, don't forget to initialize the value with dummy data to avoid uninitialized
errors.
export class ModelService {
constructor() {
this.mode = new Model();
this._http.get('/api/v1/cats')
.map(res => res.json())
.subscribe(
json => {
this.model = new Model(json);
},
error => console.log(error);
);
}
}
This assumes Model, is a data model representing the structure of your data.
Model with no parameters should create a new instance with all values initialized (but empty). That way, if the template renders before the data is received it won't throw an error.
Ideally, if you want to persist the data to avoid unnecessary http requests you should put this in an object that has its own observer that you can subscribe to.
I resolved this problem by navigating to C:\Python27\Scripts folder and then run file.py file instead of C:\Python27 folder
Encountered similar error. resetting chrome://net-internals/#hsts did not work for me. The issue was that my vm's clock was skewed by days. resetting the time did work out to resolve this issue. https://support.google.com/chrome/answer/4454607?hl=en
I managed to fix it finally. The problem is not related to HikariCP.
The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional
or enveloping all the logic in a single call to transactional service method seem to solve the problem.
I don't understand, why you don't want to set the $HOME
environment variable since that solves exactly what you're asking for.
cd ~
doesn't mean change to the root directory, but change to the user's home directory, which is set by the $HOME
environment variable.
Edit C:\Program Files (x86)\Git\etc\profile
and set $HOME
variable to whatever you want (add it if it's not there). A good place could be for example right after a condition commented by # Set up USER's home directory
. It must be in the MinGW format, for example:
HOME=/c/my/custom/home
Save it, open Git Bash and execute cd ~
. You should be in a directory /c/my/custom/home
now.
Everything that accesses the user's profile should go into this directory instead of your Windows' profile on a network drive.
Note: C:\Program Files (x86)\Git\etc\profile
is shared by all users, so if the machine is used by multiple users, it's a good idea to set the $HOME
dynamically:
HOME=/c/Users/$USERNAME
Set the environment variable HOME
in Windows to whatever directory you want. In this case, you have to set it in Windows path format (with backslashes, e.g. c:\my\custom\home
), Git Bash will load it and convert it to its format.
If you want to change the home directory for all users on your machine, set it as a system environment variable, where you can use for example %USERNAME%
variable so every user will have his own home directory, for example:
HOME=c:\custom\home\%USERNAME%
If you want to change the home directory just for yourself, set it as a user environment variable, so other users won't be affected. In this case, you can simply hard-code the whole path:
HOME=c:\my\custom\home
This is an example for refreshing data with completely new content. You can easily modify it to fit your needs. I solved this in my case by calling:
notifyItemRangeRemoved(0, previousContentSize);
before:
notifyItemRangeInserted(0, newContentSize);
This is the correct solution and is also mentioned in this post by an AOSP project member.
For those of you who want a more context on why this is happening, in addition to how to fix it, then read below.
With the introduction of iOS 9, to improve the security of connections between an app and web services, secure connections between an app and its web service must follow best practices. The best practices behavior is enforced by the App Transport Security to:
As explained in the App Transport Security Technote, when communicating with your web service, App Transport Security now has the following requirements and behavior:
- The server must support at least Transport Layer Security (TLS) protocol version 1.2.
- Connection ciphers are limited to those that provide forward secrecy (see the list of ciphers below.)
- Certificates must be signed using a SHA256 or better signature hash algorithm, with either a 2048 bit or greater RSA key or a 256 bit or greater Elliptic-Curve (ECC) key.
- Invalid certificates result in a hard failure and no connection.
In other words, your web service request should: a.) use HTTPS and b.) be encrypted using TLS v1.2 with forward secrecy.
However, as was mentioned in other posts, you can override this new behavior from App Transport Security by specifying the insecure domain in the Info.plist
of your app.
To override, you will need to add the NSAppTransportSecurity
> NSExceptionDomains
dictionary properties to your Info.plist
. Next, you will add your web service's domain to the NSExceptionDomains
dictionary.
For example, if I want to bypass the App Transport Security behavior for a web service on the host www.yourwebservicehost.com then I would do the following:
Open your app in Xcode.
Find the Info.plist
file in Project Navigator and "right-mouse" click on it and choose the Open As > Source Code menu option. The property list file will appear in the right pane.
Put the following properties block inside of the main properties dictionary (under the first <dict>
).
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>www.example.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
If you need to provide exceptions for additional domains then you would add another dictionary property beneath NSExceptionDomains
.
To find out more about the keys referenced above, read this already mentioned technote.
That wasn't working for me, but this did the trick:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key><true/>
</dict>
I'm using a simplyfied version (just using position relative) based on @SimonEast answer:
li:before {
content: "\e080";
font-family: 'Glyphicons Halflings';
font-size: 9px;
position: relative;
margin-right: 10px;
top: 3px;
color: #ccc;
}
I noticed it myself, and found the files inside the backup folder. You can check where it is using Menu:Settings -> Preferences -> Backup. Note : My NPP installation is portable, and on Windows, so YMMV.
y my case i solved this by named it in the "Identifier" property of Table View Cell:
Don't forgot: to declare in your Class: UITableViewDataSource
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
On Linux Mint 18 the default config file that has the sql-mode
option set is located here :
/usr/my.cnf
And relevant line is:
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
So You can set there.
If not sure what config file has such option You can search for it:
$ sudo find / -iname "*my.cnf*"
And get a list:
/var/lib/dpkg/alternatives/my.cnf
/usr/my.cnf
/etc/alternatives/my.cnf
/etc/mysql/my.cnf.fallback
/etc/mysql/my.cnf
Check your firewall setting and set
<property>
<name>fs.default.name</name>
<value>hdfs://MachineName:9000</value>
</property>
replace localhost to machine name
Keep scroll position by using @DawnYu answer to wrap notifyDataSetChanged()
like this:
val recyclerViewState = recyclerView.layoutManager?.onSaveInstanceState()
adapter.notifyDataSetChanged()
recyclerView.layoutManager?.onRestoreInstanceState(recyclerViewState)
It worked for me, hope you too.
*Note: I have used auto layout in Nib, remember add top and bottom contraints for subviews in contentView
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cell = YourCollectionViewCell.instantiateFromNib()
cell.frame.size.width = collectionView.frame.width
cell.data = viewModel.data[indexPath.item]
let resizing = cell.systemLayoutSizeFitting(UILayoutFittingCompressedSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.fittingSizeLevel)
return resizing
}
If you really need to transform a date to a LocalDateTime object, you could use the LocalDate.atStartOfDay(). This will give you a LocalDateTime object at the specified date, having the hour, minute and second fields set to 0:
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime time = LocalDate.parse("20140218", formatter).atStartOfDay();
I got a same problem. Below is how I solved the problem. I am working on an oracle database 12c pluggable database(pdb) on a windows 10.
-- using sqlplus to login as sysdba from a terminal; Below is an example:
sqlplus sys/@orclpdb as sysdba
-- First check your database status;
SQL> select name, open_mode from v$pdbs;
-- It shows the database is mounted in my case. If yours is not mounted, you should mount the database first.
-- Next open the database for read/write
SQL> ALTER PLUGGABLE DATABASE OPEN; (or ALTER PLUGGABLE DATABASE YOURDATABASENAME OPEN;)
-- Check the status again.
SQL> select name, open_mode from v$pdbs;
-- Now your dababase should be open for read/write and you should be able to create schemas, etc.
Building on @Waterscroll's response, if you want to use async and await in node 8+:
const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';
async function toRun() {
try {
const files = await readdir(directory);
const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
return Promise.all(unlinkPromises);
} catch(err) {
console.log(err);
}
}
toRun();
Check the PASSWORD_LOCK_TIME
parameter. If it is set to 1 then you won't be able to unlock the password for 1 day even after you issue the alter user unlock
command.
Either:
row.name
inside the apply(..., axis=1)
call:df = pandas.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'], index=['x','y'])
a b c
x 1 2 3
y 4 5 6
df.apply(lambda row: row.name, axis=1)
x x
y y
iterrows()
(slower)DataFrame.iterrows() allows you to iterate over rows, and access their index:
for idx, row in df.iterrows():
...
In windows 10, most options will not work. Follow these steps:
In Windows 10 with CMD, you cannot download
scipy
directly using most of the well known commands likewget
,cloning scipy github
,pip install scipy
, etcTo install, go to pythonlibs .whl files , and if you are using
python 2.7 32 bit
then downloadnumpy-1.11.2rc1+mkl-cp27-cp27m-win32.whl and scipy-0.18.1-cp27-cp27m-win32.whl
or ifpython 2.7 62 bit
then downloadnumpy-1.11.2rc1+mkl-cp27-cp27m-win_amd64.whl and scipy-0.18.1-cp27-cp27m-win_amd64.whl
After downloading,save the files under your
python directory
, in my case it wasc:\>python27
Then run:
pip install C:\Python27\numpy-1.11.2rc1+mkl-cp27-cp27m-win32.whl
pip install C:\Python27\scipy-0.18.1-cp27-cp27m-win32.whl
Note:
scipy
needs numpy
as dependency, so that's why we are downloading numpy
before scipy
.cp27
in .whl files means that these files are meant for python 2.7
and cp33
stands for python 3.x
speciafically >=3.3My issue was that i had multiple versions of MS SQL express installed. I went to installation folder C:/ProgramFiles/MicrosoftSQL Server/ where i found 3 versions of it. I deleted 2 folders, and left only MSSQL13.SQLEXPRESS which solved the problem.
For me, it came out that my date and time was misconfigured on Raspberry Pi. The result was that all SSL and HTTPS connections failed, using the https://files.pythonhosted.org/ server.
sudo date -s "Wed Thu 23 11:12:00 GMT+1 2018"
sudo dpkg-reconfigure tzdata
Ref.: https://superuser.com/a/635024/935136
sudo date -s "$(curl -s --head http://google.com | grep ^Date: | sed 's/Date: //g')"
sudo dpkg-reconfigure tzdata
The prefix "Local" in JSR-310 (aka java.time-package in Java-8) does not indicate that there is a timezone information in internal state of that class (here: LocalDateTime
). Despite the often misleading name such classes like LocalDateTime
or LocalTime
have NO timezone information or offset.
You tried to format such a temporal type (which does not contain any offset) with offset information (indicated by pattern symbol Z). So the formatter tries to access an unavailable information and has to throw the exception you observed.
Solution:
Use a type which has such an offset or timezone information. In JSR-310 this is either OffsetDateTime
(which contains an offset but not a timezone including DST-rules) or ZonedDateTime
. You can watch out all supported fields of such a type by look-up on the method isSupported(TemporalField).. The field OffsetSeconds
is supported in OffsetDateTime
and ZonedDateTime
, but not in LocalDateTime
.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);
Each tablespace has one or more datafiles that it uses to store data.
The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.
To find out if the actual limit is 32gb, run the following:
select value from v$parameter where name = 'db_block_size';
Compare the result you get with the first column below, and that will indicate what your max datafile size is.
I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).
Block Sz Max Datafile Sz (Gb) Max DB Sz (Tb)
-------- -------------------- --------------
2,048 8,192 524,264
4,096 16,384 1,048,528
8,192 32,768 2,097,056
16,384 65,536 4,194,112
32,768 131,072 8,388,224
You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):
select bytes/1024/1024 as mb_size,
maxbytes/1024/1024 as maxsize_set,
x.*
from dba_data_files x
MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).
If your datafile has a low max size or autoextend is not on you could simply run:
alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;
However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:
alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;
use this
@Temporal(TemporalType.TIMESTAMP)
@Column(name="create_date")
private Calendar createDate;
public Calendar getCreateDate() {
return createDate;
}
public void setCreateDate(Calendar createDate) {
this.createDate = createDate;
}
To format an Instant
a time-zone is required. Without a time-zone, the formatter does not know how to convert the instant to human date-time fields, and therefore throws an exception.
The time-zone can be added directly to the formatter using withZone()
.
DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
.withLocale( Locale.UK )
.withZone( ZoneId.systemDefault() );
If you specifically want an ISO-8601 format with no explicit time-zone (as the OP asked), with the time-zone implicitly UTC, you need
DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC))
Now use that formatter to generate the String representation of your Instant.
Instant instant = Instant.now();
String output = formatter.format( instant );
Dump to console.
System.out.println("formatter: " + formatter + " with zone: " + formatter.getZone() + " and Locale: " + formatter.getLocale() );
System.out.println("instant: " + instant );
System.out.println("output: " + output );
When run.
formatter: Localized(SHORT,SHORT) with zone: US/Pacific and Locale: en_GB
instant: 2015-06-02T21:34:33.616Z
output: 02/06/15 14:34
If width:100%
works in any cases, just use that, otherwise you can use vw
in this case which is relative to 1% of the width of the viewport.
That means if you want to cover off the width, just use 100vw
.
Look at the image I draw for you here:
Try the snippet I created for you as below:
.full-width {_x000D_
width: 100vw;_x000D_
height: 100px;_x000D_
margin-bottom: 40px;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.one-vw-width {_x000D_
width: 1vw;_x000D_
height: 100px;_x000D_
background-color: red;_x000D_
}
_x000D_
<div class="full-width"></div>_x000D_
<div class="one-vw-width"></div>
_x000D_
Have you tried using the [FromUri]
attribute when sending parameters over the query string.
Here is an example:
[HttpGet]
[Route("api/department/getndeptsfromid")]
public List<Department> GetNDepartmentsFromID([FromUri]int FirstId, [FromUri] int CountToFetch)
{
return HHSService.GetNDepartmentsFromID(FirstId, CountToFetch);
}
Include this package at the top also, using System.Web.Http;
If you are using dj-database-url check the schema in your DATABASES
https://github.com/kennethreitz/dj-database-url
MySQL is
'default': dj_database_url.config(default='mysql://USER:PASSWORD@localhost:PORT/NAME')
It solves the same error even without the PORT
You set the password with:
mysql -u user -p
I needed a cross-browser solution. Requirements were:
Building off what I learned from @Idra regarding scrolling="no" on iOS and this post about fitting iFrame content to the screen in iOS here's what I ended up with. Hope it helps someone =)
HTML
<div id="url-wrapper"></div>
CSS
html, body{
height: 100%;
}
#url-wrapper{
margin-top: 51px;
height: 100%;
}
#url-wrapper iframe{
height: 100%;
width: 100%;
}
#url-wrapper.ios{
overflow-y: auto;
-webkit-overflow-scrolling:touch !important;
height: 100%;
}
#url-wrapper.ios iframe{
height: 100%;
min-width: 100%;
width: 100px;
*width: 100%;
}
JS
function create_iframe(url){
var wrapper = jQuery('#url-wrapper');
if(navigator.userAgent.match(/(iPod|iPhone|iPad)/)){
wrapper.addClass('ios');
var scrolling = 'no';
}else{
var scrolling = 'yes';
}
jQuery('<iframe>', {
src: url,
id: 'url',
frameborder: 0,
scrolling: scrolling
}).appendTo(wrapper);
}
The best way to handle the LazyInitializationException
is to use the JOIN FETCH
directive for all the entities that you need to fetch along.
Anyway, DO NOT use the following Anti-Patterns as suggested by some of the answers:
Sometimes, a DTO projection is a better choice than fetching entities, and this way, you won't get any LazyInitializationException
.
None of these options worked for me, in the end it was;
Test > Test Settings > *.testrunconfig
I had to add a new line
<DeploymentItem filename="packages\Newtonsoft.Json.4.5.8\lib\net40\Newtonsoft.Json.dll" />
Make sure the path and version is correct for your setup.
mysqladmin
is not a SQL statement. It's a little helper utility program you'll find on your MySQL server... and "flush-hosts" is one of the things it can do. ("status" and "shutdown" are a couple of other things that come to mind).
You type that command from a shell prompt.
Alternately, from your query browser (such as phpMyAdmin), the SQL statement you're looking for is simply this:
FLUSH HOSTS;
This solution worked for me:
import pandas as pd
data = pd.read_csv("training.csv", encoding = 'unicode_escape')
This solved the problem for me (Ubuntu 16.04):
sudo apt-get install build-essential libssl-dev libffi-dev python-dev python3-dev
and then it was working like this:
pip install cryptography
pip install pyopenssl ndg-httpsclient pyasn1
In order to avoid such error you could use CASE
+ ISNUMERIC
to handle scenarios when you cannot convert to int.
Change
CONVERT(INT, CONVERT(VARCHAR(12), a.value))
To
CONVERT(INT,
CASE
WHEN IsNumeric(CONVERT(VARCHAR(12), a.value)) = 1 THEN CONVERT(VARCHAR(12),a.value)
ELSE 0 END)
Basically this is saying if you cannot convert me to int assign value of 0 (in my example)
Alternatively you can look at this article about creating a custom function that will check if a.value
is number: http://www.tek-tips.com/faqs.cfm?fid=6423
Use count(d.ertek)
or count(d.id)
instead of count(d)
. This can be happen when you have composite primary key at your entity.
Adding responseType to the request that is made from angular is indeed the solution, but for me it didn't work until I've set responseType to blob, not to arrayBuffer. The code is self explanatory:
$http({
method : 'GET',
url : 'api/paperAttachments/download/' + id,
responseType: "blob"
}).then(function successCallback(response) {
console.log(response);
var blob = new Blob([response.data]);
FileSaver.saveAs(blob, getFileNameFromHttpResponse(response));
}, function errorCallback(response) {
});
Right click on your project, then left click Properties, and select the Web tab. Debuggers > ASP.NET
I ran into this error when attempting to install 12c 32x client on Windows 10. "net use \\localhost\c$"
worked, but when I substituted "localhost" the computer's "name" (e.g., \\my-computer\c$
), I got the "System error 53 ...
". Oracle seems to prefer the computer's name.
What fixed it: we temporarily disabled the IPv6 protocol for the computer (our network uses IPv4). How to do this: Control Panel --> Network and Sharing Center --> Change adapter settings --> right click on Ethernet Connection --> Properties --> uncheck "Internet Protocol Version 6 (TCP/IPv6) --> OK. That should disable it. After that, \\my-computer\c$
ran successfully in the command prompt. Then the Oracle installer finally completed and we were able to tnsping the database server.
Just to test it out, we re-enabled IPv6 and restarted the computer. \\my-computer\c$
failed in the cmd prompt, but tnsping still functioned correctly.
I hope this helps somebody in the future.
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
To avoid the global lock, you can use SingletonCache to implement one lock per key, without exploding memory usage (the lock objects are removed when no longer referenced, and acquire/release is thread safe guaranteeing that only 1 instance is ever in use via compare and swap).
Using it looks like this:
SingletonCache<string, object> keyLocks = new SingletonCache<string, object>();
const string CacheKey = "CacheKey";
static string GetCachedData()
{
string expensiveString =null;
if (MemoryCache.Default.Contains(CacheKey))
{
return MemoryCache.Default[CacheKey] as string;
}
// double checked lock
using (var lifetime = keyLocks.Acquire(url))
{
lock (lifetime.Value)
{
if (MemoryCache.Default.Contains(CacheKey))
{
return MemoryCache.Default[CacheKey] as string;
}
cacheItemPolicy cip = new CacheItemPolicy()
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(20))
};
expensiveString = SomeHeavyAndExpensiveCalculation();
MemoryCache.Default.Set(CacheKey, expensiveString, cip);
return expensiveString;
}
}
}
Code is here on GitHub: https://github.com/bitfaster/BitFaster.Caching
Install-Package BitFaster.Caching
There is also an LRU implementation that is lighter weight than MemoryCache, and has several advantages - faster concurrent reads and writes, bounded size, no background thread, internal perf counters etc. (disclaimer, I wrote it).
This is all you need.
rsync -e ssh file host:/directory/.
Try this:
Private Sub CreateSheet()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets.Add(After:= _
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
ws.Name = "Tempo"
End Sub
Or use a With
clause to avoid repeatedly calling out your object
Private Sub CreateSheet()
Dim ws As Worksheet
With ThisWorkbook
Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
ws.Name = "Tempo"
End With
End Sub
Above can be further simplified if you don't need to call out on the same worksheet in the rest of the code.
Sub CreateSheet()
With ThisWorkbook
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Temp"
End With
End Sub
Removing .txt after LICENSE removed my error :
packagingOptions {
exclude 'META-INF/LICENSE'
}
You should use getClassLoader()
method in your root
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("main.fxml"));
The typical pattern would be as follows, but you need to actually define how the ordering should be applied (since a table is, by definition, an unordered bag of rows):
SELECT t.A, t.B, t.C, number = ROW_NUMBER() OVER (ORDER BY t.A)
FROM dbo.tableZ AS t
ORDER BY t.A;
Not sure what the variables in your question are supposed to represent (they don't match).
I've already encountered this error and this is the best solution I've found:
In your root folder (probably called public_html)please add this code to your .htaccess file...
REPLACE the 00.00.00.000 with YOUR IP address. If you don't know your IP address buzz over to What Is My IP - The IP Address Experts Since 1999
#By Marky WP Root Directory to deny entry for WP-Login & xmlrpc
<Files wp-login.php>
order deny,allow
deny from all
allow from 00.00.00.000
</Files>
<Files xmlrpc.php>
order deny,allow
deny from all
allow from 00.00.00.000
</Files>
In your wp-admin folder please add this code to your .htaccess file...
#By Marky WP Admin Folder to deny entry for entire admin folder
order deny,allow
deny from all
allow from 00.00.00.000
<Files index.php>
order deny,allow
deny from all
allow from 00.00.00.000
</Files>
I got this problem because I uninstalled VS 2012, I don't want to reinstall it back, so I downloaded the AspNetMVC4Setup.exe from Microsoft.com and fixed my problem.
https://www.microsoft.com/en-us/download/details.aspx?id=30683
YES!!!
Install-Package Microsoft.AspNet.WebApi -Version 5.0.0
It works fine in my case....thnkz
The dash type of a linestyle
is given by the linetype
, which does also select the line color unless you explicitely set an other one with linecolor
.
However, the support for dashed lines depends on the selected terminal:
png
(uses libgd
)pngcairo
, support dashed lines, but it is disables by default. To enable it, use set termoption dashed
, or set terminal pngcairo dashed ...
.linetype
, use the test
command:Running
set terminal pngcairo dashed
set output 'test.png'
test
set output
gives:
whereas, the postscript
terminal shows different dash patterns:
set terminal postscript eps color colortext
set output 'test.eps'
test
set output
Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:
A new dashtype
parameter was introduced:
To get the predefined dash patterns, use e.g.
plot x dashtype 2
You can also specify custom dash patterns like
plot x dashtype (3,5,10,5),\
2*x dashtype '.-_'
The terminal options dashed
and solid
are ignored. By default all lines are solid. To change them to dashed, use e.g.
set for [i=1:8] linetype i dashtype i
The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic
:
In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
try:
image = pygame.image.load(imgfile, 'img_01.png')
finally:
imgfile.close()
You probably want to have LI rather than the UL have the background-color:
.selected li {
background-color: red;
}
Then you want to have a dynamic class for the UL:
<ul ng-repeat="vote in votes" ng-click="setSelected()" class="{{selected}}">
Now you need to update the $scope.selected when clicking the row:
$scope.setSelected = function() {
console.log("show", arguments, this);
this.selected = 'selected';
}
and then un-select the previously highlighted row:
$scope.setSelected = function() {
// console.log("show", arguments, this);
if ($scope.lastSelected) {
$scope.lastSelected.selected = '';
}
this.selected = 'selected';
$scope.lastSelected = this;
}
Working solution:
I have at least one situation where the data is not automatically cleaned up, which would eventually lead to "Out of Memory" errors. In a UserForm I had:
Public mainPicture As StdPicture
...
mainPicture = LoadPicture(PAGE_FILE)
When UserForm was destroyed (after Unload Me
) the memory allocated for the data loaded in the mainPicture
was not being de-allocated. I had to add an explicit
mainPicture = Nothing
in the terminate event.
Update in 2020. For React devs who care performance seriously.
Above solutions do work BUT will re-render your components whenever the window size changes by a single pixel.
This often causes performance issues so I wrote useWindowDimension
hook that debounces the resize
event for a short period of time. e.g 100ms
import React, { useState, useEffect } from 'react';
export function useWindowDimension() {
const [dimension, setDimension] = useState([
window.innerWidth,
window.innerHeight,
]);
useEffect(() => {
const debouncedResizeHandler = debounce(() => {
console.log('***** debounced resize'); // See the cool difference in console
setDimension([window.innerWidth, window.innerHeight]);
}, 100); // 100ms
window.addEventListener('resize', debouncedResizeHandler);
return () => window.removeEventListener('resize', debouncedResizeHandler);
}, []); // Note this empty array. this effect should run only on mount and unmount
return dimension;
}
function debounce(fn, ms) {
let timer;
return _ => {
clearTimeout(timer);
timer = setTimeout(_ => {
timer = null;
fn.apply(this, arguments);
}, ms);
};
}
Use it like this.
function YourComponent() {
const [width, height] = useWindowDimension();
return <>Window width: {width}, Window height: {height}</>;
}
For me everything else was almost ok, but somehow my project settings changed & iisExpress was getting used instead of IISLocal. When I changed & pointed to the virtual directory (in IISLocal), it stared working perfectly again.
A good but "heavyweight" solution is to use Twisted - see the bottom.
If you're willing to live with only stdout something along those lines should work:
import subprocess
import sys
popenobj = subprocess.Popen(["ls", "-Rl"], stdout=subprocess.PIPE)
while not popenobj.poll():
stdoutdata = popenobj.stdout.readline()
if stdoutdata:
sys.stdout.write(stdoutdata)
else:
break
print "Return code", popenobj.returncode
(If you use read() it tries to read the entire "file" which isn't useful, what we really could use here is something that reads all the data that's in the pipe right now)
One might also try to approach this with threading, e.g.:
import subprocess
import sys
import threading
popenobj = subprocess.Popen("ls", stdout=subprocess.PIPE, shell=True)
def stdoutprocess(o):
while True:
stdoutdata = o.stdout.readline()
if stdoutdata:
sys.stdout.write(stdoutdata)
else:
break
t = threading.Thread(target=stdoutprocess, args=(popenobj,))
t.start()
popenobj.wait()
t.join()
print "Return code", popenobj.returncode
Now we could potentially add stderr as well by having two threads.
Note however the subprocess docs discourage using these files directly and recommends to use communicate()
(mostly concerned with deadlocks which I think isn't an issue above) and the solutions are a little klunky so it really seems like the subprocess module isn't quite up to the job (also see: http://www.python.org/dev/peps/pep-3145/ ) and we need to look at something else.
A more involved solution is to use Twisted as shown here: https://twistedmatrix.com/documents/11.1.0/core/howto/process.html
The way you do this with Twisted is to create your process using reactor.spawnprocess()
and providing a ProcessProtocol
that then processes output asynchronously. The Twisted sample Python code is here: https://twistedmatrix.com/documents/11.1.0/core/howto/listings/process/process.py
In Azure Data warehouse also this occurs sometimes, because temporary tables created for a user session.. I got the same issue fixed by reconnecting the database,
sample code:
<em><b>
<h2>Upload,Save and Download video </h2>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="video"/>
<input type="submit" name="submit" value="Upload"/></b>
</form></em>
<?php>
include("connect.php");
$errors=1;
//Targeting Folder
$target="videos/";
if(isset($_POST['submit'])){
//Targeting Folder
$target=$target.basename($_FILES['video']['name']);
//Getting Selected video Type
$type=pathinfo($target,PATHINFO_EXTENSION);
//Allow Certain File Format To Upload
if($type!='mp4' && $type!='3gp' && $type!='avi'){
echo "Only mp4,3gp,avi file format are allowed to Upload";
$errors=0;
}
//checking for Exsisting video Files
if(file_exists($target)){
echo "File Exist";
$errors=0;
}
$filesize=$_FILES['video']['size'];
if($filesize>250*2000000){
echo 'You Can not Upload Large File(more than 500MB) by Default ini setting..<a href="http://www.codenair.com/2018/03/how-to-upload-large-file-in-php.html">How to upload large file in php</a>';
$errors=0;
}
if($errors == 0){
echo ' Your File Not Uploaded';
}else{
//Moving The video file to Desired Directory
$uplaod_success=move_uploaded_file($_FILES['video']['tmp_name'],$target);
if($uplaod_success){
//Getting Selected video Information
$name=$_FILES['video']['name'];
$size=$_FILES['video']['size'];
$result=mysqli_query($con,"INSERT INTO VIdeos (name,size,type)VALUES('".$name."','".$size."','".$type."')");
if($result==TRUE){
echo "Your video '$name' Successfully Upload and Information Saved Our Database";
}
}
}
}
?>
If you are running on headless CI and are installing the Android SDK through command line, make sure to include the m2repository packages in the --filter
argument:
android update sdk --no-ui --filter platform-tools,build-tools-19.0.1,android-19,extra-android-support,extra-android-m2repository,extra-google-m2repository
Update
As of Android SDK Manager rev. 22.6.4 this does not work anymore. Try this instead:
android list sdk --all
You will get a list of all available SDK packages. Look up the numerical values of the components from the first command above ("Google Repository" and others you might be missing).
Install the packages using their numerical values:
android update sdk --no-ui --all --filter <num>
Update #2 (Sept 2017)
With the "new" Android SDK tools that were released earlier this year, the android
command is now deprecated, and similar functionality has been moved to a new tool called sdkmanager
:
List installed components:
sdkmanager --list
Update installed components:
sdkmanager --update
Install a new component (e.g. build tools version 26.0.0
):
sdkmanager 'build-tools;26.0.0'
Try these:
pip install --upgrade setuptools
or easy_install -U setuptools
Initialize again select2
by new id or class like below
when the page load
$(".mynames").select2();
call again when came by ajax after success ajax function
$(".names").select2();
As it is written in the documentation you have to change the cell type to a markdown.
Best Firefox Addon to disable CORS as of September 2016: https://github.com/fredericlb/Force-CORS/releases
You can even configure it by Referrers (Website).
I ran into this situation and creating an extra div was impractical.
I ended up just setting the full-height
div to height: 10000%; overflow: hidden;
Clearly not the cleanest solution, but it works really fast.
in my case, only height: 100vh
fix the problem with the expected behavior
How to delete only the content of file in python
There is several ways of set the logical size of a file to 0, depending how you access that file:
To empty an open file:
def deleteContent(pfile):
pfile.seek(0)
pfile.truncate()
To empty a open file whose file descriptor is known:
def deleteContent(fd):
os.ftruncate(fd, 0)
os.lseek(fd, 0, os.SEEK_SET)
To empty a closed file (whose name is known)
def deleteContent(fName):
with open(fName, "w"):
pass
I have a temporary file with some content [...] I need to reuse that file
That being said, in the general case it is probably not efficient nor desirable to reuse a temporary file. Unless you have very specific needs, you should think about using tempfile.TemporaryFile
and a context manager to almost transparently create/use/delete your temporary files:
import tempfile
with tempfile.TemporaryFile() as temp:
# do whatever you want with `temp`
# <- `tempfile` guarantees the file being both closed *and* deleted
# on exit of the context manager
You may find this to be more common on CIFS/SMB network shares. Windows doesn't allow for a file to be written when something else has that file open, and even if the service is not Windows (it might be some other NAS product), it will likely reproduce the same behaviour. Potentially, it might also be a manifestation of some underlying NAS issue vaguely related to locking/replication.
The difference between this two tables ItemBack1
and #ItemBack1
is that the first on is persistent (permanent) where as the other is temporary.
Now if take a look at your question again
Is it necessary to Use # for creating temp table in sql server?
The answer is Yes, because without this preceding #
the table will not be a temporary table, it will be independent of all sessions and scopes.
Call Angular Scope function from outside the controller.
// Simply Use "Body" tag, Don't try/confuse using id/class.
var scope = angular.element('body').scope();
scope.$apply(function () {scope.YourAngularJSFunction()});
A function is not even needed. Just put parentheses around the default expression:
create temporary table test(
id int,
ts timestamp without time zone default (now() at time zone 'utc')
);
Roughly speaking:
getClass().getResource("/")
~= Thread.currentThread().getContextClassLoader().getResource(".")
Suppose your project structure is like the following:
+-- src
¦ +-- main
¦ +-- test
¦ +-- test
¦ +-- java
¦ ¦ +-- com
¦ ¦ +-- github
¦ ¦ +-- xyz
¦ ¦ +-- proj
¦ ¦ +-- MainTest.java
¦ ¦ +-- TestBase.java
¦ +-- resources
¦ +-- abcd.txt
+-- target
+-- test-classes
+-- com
+-- abcd.txt
// in MainClass.java
this.getClass.getResource("/") -> "~/proj_dir/target/test-classes/"
this.getClass.getResource(".") -> "~/proj_dir/target/test-classes/com/github/xyz/proj/"
Thread.currentThread().getContextClassLoader().getResources(".") -> "~/proj_dir/target/test-classes/"
Thread.currentThread().getContextClassLoader().getResources("/") -> null
Value of %TEMP%
environment variable is often user-specific and Windows sets it up with regard to currently logged in user account. Some user accounts may have no user profile, for example when your process runs as a service on SYSTEM
, LOCALSYSTEM
or other built-in account, or is invoked by IIS application with AppPool identity with Create user profile option disabled. So even when you do not overwrite %TEMP%
variable explicitly, Windows may use c:\temp
or even c:\windows\temp
folders for, lets say, non-usual user accounts. And what's more important, process might have no access rights to this directory!
Try:
import numpy as np
dist = np.array([1,2,3,4,5])
r = 2
dr = 3
np.where(np.logical_and(dist> r, dist<=r+dr))
Output: (array([2, 3]),)
You can see Logic functions for more details.
Maybe I'm a little bit late :), but here is a nice and brief solution by chrisjhoughton, which allows to perform a callback function when the wait is over.
https://gist.github.com/chrisjhoughton/7890303
var waitForEl = function(selector, callback) {
if (jQuery(selector).length) {
callback();
} else {
setTimeout(function() {
waitForEl(selector, callback);
}, 100);
}
};
waitForEl(selector, function() {
// work the magic
});
If you need to pass parameters to a callback function, you can use it this way:
waitForEl("#" + elDomId, () => callbackFunction(param1, param2));
But be careful! This solution by default can fall into a trap of an infinite loop.
Several improvements of the topicstarter's suggestion are also provided in The GitHub thread.
Enjoy!
Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue
annotation using IDENTITY.
@Entity
@Table(name = "client")
data class Client(
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)
GL
Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.
For background, see the Understanding ASP.NET dynamic compilation article on MSDN.
HTML
<input type="text" name="my_date" value="4/26/2015" class="datepicker">
JS
jQuery(function() {
var datepicker = $('input.datepicker');
if (datepicker.length > 0) {
datepicker.datepicker({
format: "mm/dd/yyyy",
startDate: new Date()
});
}
});
That will highlight the default date as 4/26/2015 (Apr 26, 2015) in the calendar when opened and disable all the dates before current date.
I guess problem is in width attributes in table and td remove 'px' for example
<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">
Should be
<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">
In Java, you cannot set a value in ArrayList by assigning to it, there's a set()
method to call:
String a = words.get(0);
words.set(0, words.get(words.size() - 1));
words.set(words.size() - 1, a)
I followed Alohci's recommendation of looping in reverse because it's a live nodeList
. Here's what I did for those who are curious...
var activeObjects = documents.getElementsByClassName('active'); // a live nodeList
//Use a reverse-loop because the array is an active NodeList
while(activeObjects.length > 0) {
var lastElem = activePaths[activePaths.length-1]; //select the last element
//Remove the 'active' class from the element.
//This will automatically update the nodeList's length too.
var className = lastElem.getAttribute('class').replace('active','');
lastElem.setAttribute('class', className);
}
In some case, I want only to undo the changes on specific files on the first commit to add them to a second commit and have a cleaner git log.
In this case, what I do is the following:
git checkout HEAD~1 <path_to_file_to_put_in_different_commit>
git add -u
git commit --amend --no-edit
git checkout HEAD@{1} <path_to_file_to_put_in_different_commit>
git commit -m "This is the new commit"
Of course, this works well even in the middle of a rebase -i
with an edit option on the commit to split.
It does work with me. Make sure that you append ".txt" next to timeLog. I used it in a simple program opened with Netbeans and it writes the program in the main folder (where builder and src folders are).
To turn off foreign key constraint globally, do the following:
SET GLOBAL FOREIGN_KEY_CHECKS=0;
and remember to set it back when you are done
SET GLOBAL FOREIGN_KEY_CHECKS=1;
WARNING: You should only do this when you are doing single user mode maintenance. As it might resulted in data inconsistency. For example, it will be very helpful when you are uploading large amount of data using a mysqldump output.
I don't see any margin
or margin-left
declarations for #footer-wrap li
.
This ought to do the trick:
#footer-wrap ul,
#footer-wrap li {
margin-left: 0;
list-style-type: none;
}
Passing structs to functions by reference: simply :)
#define maxn 1000
struct solotion
{
int sol[maxn];
int arry_h[maxn];
int cat[maxn];
int scor[maxn];
};
void inser(solotion &come){
come.sol[0]=2;
}
void initial(solotion &come){
for(int i=0;i<maxn;i++)
come.sol[i]=0;
}
int main()
{
solotion sol1;
inser(sol1);
solotion sol2;
initial(sol2);
}
Hope this will help!
@OneToOne(optional = false)
@JoinColumn(name = "department_id", insertable = false, updatable = false)
@JsonManagedReference
private Department department;
@JsonIgnore
public Department getDepartment() {
return department;
}
@OneToOne(mappedBy = "department")
private Designation designation;
@JsonIgnore
public Designation getDesignation() {
return designation;
}
If you use a Custom format, rather than one of the pre-selected Date formats, the export to CSV will keep your selected format. Otherwise it defaults back to the US format
What happened with me was the Type of class was not UIViewController for the script attached to my view controller. It was for a UITabController..... I had mistakenly quickly created the wrong type of class.... So make sure the class if the correct type.. Hope this helps someone. I was in a rush and made this mistake.
One possible solution that I use is to use python3. It seems to solve many utf issues.
Sorry for the late answer, but it may help people in the future.
For example,
#!/usr/bin/env python3
import json
# your code follows
I use the following technique. It makes it easy to keep the column names in sync with the content:
var cursor = db.getCollection('Employees.Details').find({})
var header = []
var rows = []
var firstRow = true
cursor.forEach((doc) =>
{
var cells = []
if (firstRow) header.push("employee_number")
cells.push(doc.EmpNum.valueOf())
if (firstRow) header.push("name")
cells.push(doc.FullName.valueOf())
if (firstRow) header.push("dob")
cells.push(doc.DateOfBirth.valueOf())
row = cells.join(',')
rows.push(row)
firstRow = false
})
print(header.join(','))
print(rows.join('\n'))
This is an old question but there is some newer guidance in PEP 565 that to turn off all warnings if you're writing a python application you should use:
import sys
import warnings
if not sys.warnoptions:
warnings.simplefilter("ignore")
The reason this is recommended is that it turns off all warnings by default but crucially allows them to be switched back on via python -W
on the command line or PYTHONWARNINGS
.
Installing the Chrome extension IE Tab did the job for me.
It has the ability to auto-detect URLs so whenever I browse to our SharePoint it emulates Internet Explorer. Finally I can open Office documents directly from Chrome.
You can install IETab for FireFox too.
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
select_statement
Example :
CREATE TEMPORARY TABLE IF NOT EXISTS mytable
(id int(11) NOT NULL, PRIMARY KEY (id)) ENGINE=MyISAM;
INSERT IGNORE INTO mytable SELECT id FROM table WHERE xyz;
That's because you're using a non-blocking
socket and the output buffer is full.
From the send()
man page
When the message does not fit into the send buffer of the socket,
send() normally blocks, unless the socket has been placed in non-block-
ing I/O mode. In non-blocking mode it would return EAGAIN in this
case.
EAGAIN is the error code tied to "Resource temporarily unavailable"
Consider using select()
to get a better control of this behaviours
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
Okay. If you do not want to store the file in database and store in the application, like assets (custom folder), you can define non-db instance variable defined by attr_accessor: document and use form_for - f.file_field
to get the file,
In controller,
@person = Person.new(person_params)
Here person_params
return whitelisted params[:person]
(define yourself)
Save file as,
dir = "#{Rails.root}/app/assets/custom_path"
FileUtils.mkdir(dir) unless File.directory? dir
document = @person.document.document_file_name # check document uploaded params
File.copy_stream(@font.document, "#{dir}/#{document}")
Note, Add this path in .gitignore
& if you want to use this file again add this path asset_path
an of application by application.rb
Whenever form read file field, it get store in tmp folder, later you can store at your place, I gave example to store at assets
note: Storing files like this will increase the size of the application, better to store in the database using paperclip
.
here the problem is model binding if you specify a class then the model binding can understand it during the post if it an integer or string then you have to specify the [FromBody] to bind it properly.
make the following changes in FormMethod
using (@Html.BeginForm("myMethod", "Home", FormMethod.Post, new { id = @item.JobId })){
}
and inside your home controller for binding the string you should specify [FromBody]
using System.Web.Http;
[HttpPost]
public FileStreamResult myMethod([FromBody]string id)
{
// Set a local variable with the incoming data
string str = id;
}
FromBody is available in System.Web.Http. make sure you have the reference to that class and added it in the cs file.
After trying everything I could, I just added "autoWidth": true
and it worked for me.
A possibility is that the git server you are pushing to is down/crashed, and the solution lies in restarting the git server.
you can try with System.Web.Script.Serialization.JavaScriptSerializer
:
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(jsonStr);
1) Upgrade your Selenium Server i.e. selenium jar "selenium-server-standalone-2.xx.x.JAR" TO "selenium-server-standalone-2.45.0.JAR"
2) Upgrade your Selenium Client Driver i.e. selenium libs folder "selenium-java-2.xx.x" TO "selenium-java-2.45.0"
3) Check and Install compatible Firefox version
Refer - Download updated selenium libs & jar i.e. Version 2.45.0
This will RESOLVE your problem.. Cheers !!
I experienced the same problem and tried most of the resolutions above. Simply deleting cache and temp files end up working for me.
Try removing the contents of these two folders:
C:\Users\\{UserName}\AppData\Local\Microsoft\WebsiteCache
and
C:\Users\\{UserName}\AppData\Local\Temp
(in particular the iisexpress and Temporary ASP.NET Files folders).
This can be set up to happen automatically on logging on to Windows by adding a cmd file to the C:\Users\\{username}\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
folder with the following content:
rmdir C:\Users\\{username}\AppData\Local\Microsoft\WebsiteCache /s /q
rmdir C:\Users\\{username}\AppData\Local\Temp /s /q
Use ThisWorkbook
which will refer to the original workbook which holds the code.
Alternatively at code start
Dim Wb As Workbook
Set Wb = ActiveWorkbook
sample code that activates all open books before returning to ThisWorkbook
Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
Wb2.Activate
Next
Wb.Activate
End Sub
I would try something like this for multiple collections. I'm a MySQL beginner. Sorry about the function names, couldn't decide on what names would be best.
delimiter //
drop procedure init_
//
create procedure init_()
begin
CREATE TEMPORARY TABLE if not exists
val_store(
realm varchar(30)
, id varchar(30)
, val varchar(255)
, primary key ( realm , id )
);
end;
//
drop function if exists get_
//
create function get_( p_realm varchar(30) , p_id varchar(30) )
returns varchar(255)
reads sql data
begin
declare ret_val varchar(255);
declare continue handler for 1146 set ret_val = null;
select val into ret_val from val_store where id = p_id;
return ret_val;
end;
//
drop procedure if exists set_
//
create procedure set_( p_realm varchar(30) , p_id varchar(30) , p_val varchar(255) )
begin
call init_();
insert into val_store (realm,id,val) values (p_realm , p_id , p_val) on duplicate key update val = p_val;
end;
//
drop procedure if exists remove_
//
create procedure remove_( p_realm varchar(30) , p_id varchar(30) )
begin
call init_();
delete from val_store where realm = p_realm and id = p_id;
end;
//
drop procedure if exists erase_
//
create procedure erase_( p_realm varchar(30) )
begin
call init_();
delete from val_store where realm = p_realm;
end;
//
call set_('my_array_table_name','my_key','my_value');
select get_('my_array_table_name','my_key');
Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used
watch -n 5 -d "ps -eL <java_pid> | wc -l"
to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.
Here is an example to move the mysqld tmpdir from /tmp to /run/mysqld which already exists on Ubuntu 13.04 and is a tmpfs (memory/ram):
sudo vim /etc/mysql/conf.d/local.cnf
Add:
[mysqld]
tmpdir = /run/mysqld
Then:
sudo service mysql restart
Verify:
SHOW VARIABLES LIKE 'tmpdir';
==================================================================
If you get an error on MySQL restart, you may have AppArmor enabled:
sudo vim /etc/apparmor.d/local/usr.sbin.mysqld
Add:
# Site-specific additions and overrides for usr.sbin.mysqld.
# For more details, please see /etc/apparmor.d/local/README.
/run/mysqld/ r,
/run/mysqld/** rwk,
Then:
sudo service apparmor reload
sources: http://2bits.com/articles/reduce-your-servers-resource-usage-moving-mysql-temporary-directory-ram-disk.html, https://blogs.oracle.com/jsmyth/entry/apparmor_and_mysql
I totally agree with Abacus (sorry - don't have enough points to comment).
Also, keep in mind it doesn't necessarily come down to how many records you have, but the size of your records.
For instance, have you considered the performance difference between 1,000 records with 50 columns each vs 100,000 records with only 5 columns each?
Lastly, maybe you're querying/storing more data than you need? Here's a good read on SQL optimization strategies. Limit the amount of data you're pulling, especially if you're not using it all (some SQL programmers do get lazy and just select everything even though they only use a tiny subset). Don't forget the SQL query analyzer may also become your best friend.
SELECT *
INTO #TempTable
FROM table
Create a function like so:
CREATE FUNCTION dbo.fn_FileExists(@path varchar(512))
RETURNS BIT
AS
BEGIN
DECLARE @result INT
EXEC master.dbo.xp_fileexist @path, @result OUTPUT
RETURN cast(@result as bit)
END;
GO
Edit your table and add a computed column (IsExists BIT). Set the expression to:
dbo.fn_FileExists(filepath)
Then just select:
SELECT * FROM dbo.MyTable where IsExists = 1
Update:
To use the function outside a computed column:
select id, filename, dbo.fn_FileExists(filename) as IsExists
from dbo.MyTable
Update:
If the function returns 0 for a known file, then there is likely a permissions issue. Make sure the SQL Server's account has sufficient permissions to access the folder and files. Read-only should be enough.
And YES, by default, the 'NETWORK SERVICE' account will not have sufficient right into most folders. Right click on the folder in question and select 'Properties', then click on the 'Security' tab. Click 'Edit' and add 'Network Service'. Click 'Apply' and retest.
There is a easy way to this.
-- Disable all the constraint in database
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'
-- Enable all the constraint in database
EXEC sp_msforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'
Here's a solution that doesn't use JS at all. It uses checkboxes instead.
You can hide the checkbox by adding this to your CSS:
.container input{
display: none;
}
And then add some styling to make it look like a button.
In one line :
FileUtils.copyInputStreamToFile(inputStream, file);
(org.apache.commons.io)
Here's one slight alteration to the answers of a query that creates the table upon execution (i.e. you don't have to create the table first):
SELECT * INTO #Temp
FROM (
select OptionNo, OptionName from Options where OptionActive = 1
) as X
Keep Trying!
I have had this a few times (including today), and each time, without changing anything, it has worked when I tried again.
Sometimes the 2nd time, other times 20 minutes later.
#temp is materalized and CTE is not.
CTE is just syntax so in theory it is just a subquery. It is executed. #temp is materialized. So an expensive CTE in a join that is execute many times may be better in a #temp. On the other side if it is an easy evaluation that is not executed but a few times then not worth the overhead of #temp.
The are some people on SO that don't like table variable but I like them as the are materialized and faster to create than #temp. There are times when the query optimizer does better with a #temp compared to a table variable.
The ability to create a PK on a #temp or table variable gives the query optimizer more information than a CTE (as you cannot declare a PK on a CTE).
This is the workaround that worked easily for me. It isn't direct answer to the question but still may help someone.
Rather than creating notransition
class which was supposed to cancel the transition
.notransition {
-webkit-transition: none !important;
-moz-transition: none !important;
-o-transition: none !important;
transition: none !important;
}
I created moveTransition
class
.moveTransition {
-webkit-transition: left 3s, top 3s;
-moz-transition: left 3s, top 3s;
-o-transition: left 3s, top 3s;
transition: left 3s, top 3s;
}
Then I added this class to element with js
element.classList.add("moveTransition")
And later in setTimeout, I removed it
element.classList.remove("moveTransition")
I wasn't able to test it in different browsers but in chrome it works perfectly
PsSuspend command line utility from SysInternals
suite. It suspends / resumes a process by its id.
After much pain, googling and hair pulling, I ended up uninstalling MVC 4 using nuget, deleting all references to MVC, razor and infrastructure from the web config, deleting the dlls from the bin folder - then using nuget to reinstall everything. It took less time then trying to figure out why the dlls did not match.
The mktemp(1)
man page explains it fairly well:
Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win. A safer, though still inferior, approach is to make a temporary directory using the same naming scheme. While this does allow one to guarantee that a temporary file will not be subverted, it still allows a simple denial of service attack. For these reasons it is suggested that mktemp be used instead.
In a script, I invoke mktemp something like
mydir=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")
which creates a temporary directory I can work in, and in which I can safely name the actual files something readable and useful.
mktemp
is not standard, but it does exist on many platforms. The "X"s will generally get converted into some randomness, and more will probably be more random; however, some systems (busybox ash, for one) limit this randomness more significantly than others
By the way, safe creation of temporary files is important for more than just shell scripting. That's why python has tempfile, perl has File::Temp, ruby has Tempfile, etc…
I have encountered this problem and finally solved it today, so I write down what I have learned and I hope it is helpful for someone who is new to Android's ViewPager
and update as I do. I'm using FragmentStatePagerAdapter
in API level 17 and currently have just 2 fragments. I think there must be something not correct, please correct me, thanks.
Serialized data has to be loaded into memory. This can be done using a CursorLoader
/AsyncTask
/Thread
. Whether it's automatically loaded depends on your code. If you are using a CursorLoader
, it's auto-loaded since there is a registered data observer.
After you call viewpager.setAdapter(pageradapter)
, the adapter's getCount()
is constantly called to build fragments. So if data is being loaded, getCount()
can return 0, thus you don't need to create dummy fragments for no data shown.
After the data is loaded, the adapter will not build fragments automatically since getCount()
is still 0, so we can set the actually loaded data number to be returned by getCount()
, then call the adapter's notifyDataSetChanged()
. ViewPager
begin to create fragments (just the first 2 fragments) by data in memory. It's done before notifyDataSetChanged()
is returned. Then the ViewPager
has the right fragments you need.
If the data in the database and memory are both updated (write through), or just data in memory is updated (write back), or only data in the database is updated. In the last two cases if data is not automatically loaded from the database to memory (as mentioned above).
The ViewPager
and pager adapter just deal with data in memory.
So when data in memory is updated, we just need to call the adapter's notifyDataSetChanged()
. Since the fragment is already created, the adapter's onItemPosition()
will be called before notifyDataSetChanged()
returns. Nothing needs to be done in getItemPosition()
. Then the data is updated.
One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .
There is one more way to run grunt on windows, without adding anything globally. This is a case when you don't have to do anything with %PATH%
if you have grunt and grunt-cli installed (without -g switch). Either by:
npm install grunt-cli
npm install [email protected]
Or by having that in your packages.json file like:
"devDependencies": {
"grunt-cli": "^1.2.0",
"grunt": "^0.4.5",
You can call grunt from your local installation by:
node node_modules\grunt-cli\bin\grunt --version
This is a solution for those who for some reasons don't want to or can't play with PATH, or have something else messing it all the time, for instance on a build agent.
Edit: Added versions as the grunt-cli works with grunt > 0.3
Mysql error "28 from storage engine" - means "not enough disk space".
To show disc space use command below.
myServer# df -h
Results must be like this.
Filesystem Size Used Avail Capacity Mounted on
/dev/vdisk 13G 13G 46M 100% /
devfs 1.0k 1.0k 0B 100% /dev
I think this is what you want...
Sub SaveWorksheetsAsCsv()
Dim WS As Excel.Worksheet
Dim SaveToDirectory As String
Dim CurrentWorkbook As String
Dim CurrentFormat As Long
CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook
SaveToDirectory = "H:\test\"
For Each WS In Application.ActiveWorkbook.Worksheets
WS.SaveAs SaveToDirectory & WS.Name, xlCSV
Next
Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
Application.DisplayAlerts = True
' Temporarily turn alerts off to prevent the user being prompted
' about overwriting the original file.
End Sub
There are two separate things here:
For example:
{
vector<MyObject> v;
// do some stuff, push some objects onto v
v.clear(); // 1
// maybe do some more stuff
} // 2
At 1
, you clear v
: this destroys all the objects it was storing. Each gets its destructor called, if your wrote one, and anything owned by that MyObject
is now released.
However, vector v
has the right to keep the raw storage around in case you want it later.
If you decide to push some more things into it between 1
and 2
, this saves time as it can reuse the old memory.
At 2
, the vector v
goes out of scope: any objects you pushed into it since 1
will be destroyed (as if you'd explicitly called clear again), but now the underlying storage is also released (v
won't be around to reuse it any more).
If I change the example so v
becomes a pointer to a dynamically-allocated vector, you need to explicitly delete it, as the pointer going out of scope at 2
doesn't do that for you. It's better to use something like std::unique_ptr
in that case, but if you don't and v
is leaked, the storage it allocated will be leaked as well. As above, you need to make sure v
is deleted, and calling clear
isn't sufficient.
I had the idea of simply copy the source code from android.support.v4.app.FragmentPagerAdpater
into a custom class named
CustumFragmentPagerAdapter
. This gave me the chance to modify the instantiateItem(...)
so that every time it is called, it removes / destroys the currently attached fragment before it adds the new fragment received from getItem()
method.
Simply modify the instantiateItem(...)
in the following way:
@Override
public Object instantiateItem(ViewGroup container, int position) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
final long itemId = getItemId(position);
// Do we already have this fragment?
String name = makeFragmentName(container.getId(), itemId);
Fragment fragment = mFragmentManager.findFragmentByTag(name);
// remove / destroy current fragment
if (fragment != null) {
mCurTransaction.remove(fragment);
}
// get new fragment and add it
fragment = getItem(position);
mCurTransaction.add(container.getId(), fragment, makeFragmentName(container.getId(), itemId));
if (fragment != mCurrentPrimaryItem) {
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
}
return fragment;
}
Something like this should work:
sh -c 'cd /tmp && exec pwd'
In addition to the other answers here showing you how to git checkout <the-hash-you-want>
it's worth knowing you can switch back to where you were using:
git checkout @{-1}
This is often more convenient than:
git checkout what-was-that-original-branch-called-again-question-mark
As you might anticipate, git checkout @{-2}
will take you back to the branch you were at two git checkout
s ago, and similarly for other numbers. If you can remember where you were for bigger numbers, you should get some kind of medal for that.
Sadly for productivity, git checkout @{1}
does not take you to the branch you will be on in future, which is a shame.
Set the scrollable div to have a max-size
and add overflow-y: scroll;
to it's properties.
Edit: trying to get the jsfiddle to work, but it's not scrolling properly. This will take some time to figure out.
You can include the Jython library in your Java Project. You can download the source code from the Jython project itself.
Jython does offers support for JSR-223 which basically lets you run a Python script from Java.
You can use a ScriptContext
to configure where you want to send your output of the execution.
For instance, let's suppose you have the following Python script in a file named numbers.py
:
for i in range(1,10):
print(i)
So, you can run it from Java as follows:
public static void main(String[] args) throws ScriptException, IOException {
StringWriter writer = new StringWriter(); //ouput will be stored here
ScriptEngineManager manager = new ScriptEngineManager();
ScriptContext context = new SimpleScriptContext();
context.setWriter(writer); //configures output redirection
ScriptEngine engine = manager.getEngineByName("python");
engine.eval(new FileReader("numbers.py"), context);
System.out.println(writer.toString());
}
And the output will be:
1
2
3
4
5
6
7
8
9
As long as your Python script is compatible with Python 2.5 you will not have any problems running this with Jython.
If we want to copy an object in Java, there are two possibilities that we need to consider: a shallow copy and a deep copy.
The shallow copy is the approach when we only copy field values. Therefore, the copy might be dependent on the original object. In the deep copy approach, we make sure that all the objects in the tree are deeply copied, so the copy is not dependent on any earlier existing object that might ever change.
This question is the perfect definition for the application of the deep copy approach.
First, if you have a simple HashMap<Integer, List<T>>
map then we just create a workaround like this. Creating a new instance of the List<T>
.
public static <T> HashMap<Integer, List<T>> deepCopyWorkAround(HashMap<Integer, List<T>> original)
{
HashMap<Integer, List<T>> copy = new HashMap<>();
for (Map.Entry<Integer, List<T>> entry : original.entrySet()) {
copy.put(entry.getKey(), new ArrayList<>(entry.getValue()));
}
return copy;
}
This one uses Stream.collect()
method to create the clone map, but uses the same idea as the previous method.
public static <T> Map<Integer, List<T>> deepCopyStreamWorkAround(Map<Integer, List<T>> original)
{
return original
.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, valueMapper -> new ArrayList<>(valueMapper.getValue())));
}
But, if the instances inside T
are also mutable objects we have a big problem. In this case a real deep copy is an alternative that solves this problem. Its advantage is that at least each mutable object in the object graph is recursively copied. Since the copy is not dependent on any mutable object that was created earlier, it won’t get modified by accident like we saw with the shallow copy.
To solve that this deep copy implementations will do the work.
public class DeepClone
{
public static void main(String[] args)
{
Map<Long, Item> itemMap = Stream.of(
entry(0L, new Item(2558584)),
entry(1L, new Item(254243232)),
entry(2L, new Item(986786)),
entry(3L, new Item(672542)),
entry(4L, new Item(4846)),
entry(5L, new Item(76867467)),
entry(6L, new Item(986786)),
entry(7L, new Item(7969768)),
entry(8L, new Item(68868486)),
entry(9L, new Item(923)),
entry(10L, new Item(986786)),
entry(11L, new Item(549768)),
entry(12L, new Item(796168)),
entry(13L, new Item(868421)),
entry(14L, new Item(923)),
entry(15L, new Item(986786)),
entry(16L, new Item(549768)),
entry(17L, new Item(4846)),
entry(18L, new Item(4846)),
entry(19L, new Item(76867467)),
entry(20L, new Item(986786)),
entry(21L, new Item(7969768)),
entry(22L, new Item(923)),
entry(23L, new Item(4846)),
entry(24L, new Item(986786)),
entry(25L, new Item(549768))
).collect(entriesToMap());
Map<Long, Item> clone = DeepClone.deepClone(itemMap);
clone.remove(1L);
clone.remove(2L);
System.out.println(itemMap);
System.out.println(clone);
}
private DeepClone() {}
public static <T> T deepClone(final T input)
{
if (input == null) return null;
if (input instanceof Map<?, ?>) {
return (T) deepCloneMap((Map<?, ?>) input);
} else if (input instanceof Collection<?>) {
return (T) deepCloneCollection((Collection<?>) input);
} else if (input instanceof Object[]) {
return (T) deepCloneObjectArray((Object[]) input);
} else if (input.getClass().isArray()) {
return (T) clonePrimitiveArray((Object) input);
}
return input;
}
private static Object clonePrimitiveArray(final Object input)
{
final int length = Array.getLength(input);
final Object output = Array.newInstance(input.getClass().getComponentType(), length);
System.arraycopy(input, 0, output, 0, length);
return output;
}
private static <E> E[] deepCloneObjectArray(final E[] input)
{
final E[] clone = (E[]) Array.newInstance(input.getClass().getComponentType(), input.length);
for (int i = 0; i < input.length; i++) {
clone[i] = deepClone(input[i]);
}
return clone;
}
private static <E> Collection<E> deepCloneCollection(final Collection<E> input)
{
Collection<E> clone;
if (input instanceof LinkedList<?>) {
clone = new LinkedList<>();
} else if (input instanceof SortedSet<?>) {
clone = new TreeSet<>();
} else if (input instanceof Set) {
clone = new HashSet<>();
} else {
clone = new ArrayList<>();
}
for (E item : input) {
clone.add(deepClone(item));
}
return clone;
}
private static <K, V> Map<K, V> deepCloneMap(final Map<K, V> map)
{
Map<K, V> clone;
if (map instanceof LinkedHashMap<?, ?>) {
clone = new LinkedHashMap<>();
} else if (map instanceof TreeMap<?, ?>) {
clone = new TreeMap<>();
} else {
clone = new HashMap<>();
}
for (Map.Entry<K, V> entry : map.entrySet()) {
clone.put(deepClone(entry.getKey()), deepClone(entry.getValue()));
}
return clone;
}
}
If the problem is 100% here
EffectSelectorForm effectSelectorForm = new EffectSelectorForm(Effects);
There's only one possible explanation: property/variable "Effects" is not initialized properly... Debug your code to see what you pass to your objects.
EDIT after several hours
There were some problems:
MEF attribute [Import] didn't work as expected, so we replaced it for the time being with a manually populated List<>. While the collection was null, it was causing exceptions later in the code, when the method tried to get the type of the selected item and there was none.
several event handlers weren't wired up to control events
Some problems are still present, but I believe OP's original problem has been fixed. Other problems are not related to this one.
things that speed up the inserts:
You are trying to send headers information after outputing content.
If you want to do this, look for output buffering.
Therefore, look to use ob_start();
Ignore full folder on source tree.
Just Open Repository >Repository setting > Edit git ignore File and
you can rite some thing like this :
*.pdb
*.bak
*.dll
*.lib
.gitignore
packages/
*/bin/
*/obj/
For bin folder and obj folder just write : */bin/ */obj/
I've compared performance (space and time) for a number of ways to store numpy arrays. Few of them support multiple arrays per file, but perhaps it's useful anyway.
Npy and binary files are both really fast and small for dense data. If the data is sparse or very structured, you might want to use npz with compression, which'll save a lot of space but cost some load time.
If portability is an issue, binary is better than npy. If human readability is important, then you'll have to sacrifice a lot of performance, but it can be achieved fairly well using csv (which is also very portable of course).
More details and the code are available at the github repo.
A simple alternative to using a custom UserType is to construct a new java.util.Date in the setter for the date property in your persisted bean, eg:
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Column;
@Entity
public class Purchase {
private Date date;
@Column
public Date getDate() {
return this.date;
}
public void setDate(Date date) {
// force java.sql.Timestamp to be set as a java.util.Date
this.date = new Date(date.getTime());
}
}
If your SQL Server table has a column of type INT IDENTITY
(or BIGINT IDENTITY
), then you can get the latest inserted value using:
INSERT INTO dbo.YourTable(columns....)
VALUES(..........)
SELECT SCOPE_IDENTITY()
This works as long as you haven't inserted another row - it just returns the last IDENTITY
value handed out in this scope here.
There are at least two more options - @@IDENTITY
and IDENT_CURRENT
- read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.
Right from the docs:
-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using-fpermissive
will allow some nonconforming code to compile.
Bottom line: don't use it unless you know what you are doing!
It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:
myFunc() = Object(...);
That would work nicely if myFunc
returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.
instant/feasible/partial answer : https://stackoverflow.com/a/20130959/2584794
unlike from the previous answer where netstat -a -o -n was used incredibly long list was to be looked into without the name of application using those ports
final int[] positions=new int[2];
Spinner sp=findViewByID(R.id.spinner);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText( arg2....);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Notice how the output of
SHOW GRANTS FOR 'root'@'localhost';
did not say 'ALL PRIVILEGES' but had to spell out what root@localhost has.
GRANT ALL PRIVILEGES will fail, because a user can not grant what he/she does not have, and the server seem to think something is not here ...
Now, what's missing then ?
On my system, I get this:
mysql> select version();
+------------+
| version() |
+------------+
| 5.5.21-log |
+------------+
1 row in set (0.00 sec)
mysql> SHOW GRANTS FOR 'root'@'localhost';
+---------------------------------------------------------------------+
| Grants for root@localhost |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION |
+---------------------------------------------------------------------+
2 rows in set (0.00 sec)
mysql> SELECT * FROM mysql.user WHERE User='root' and Host='localhost'\G
*************************** 1. row ***************************
Host: localhost
User: root
Password:
Select_priv: Y
Insert_priv: Y
Update_priv: Y
Delete_priv: Y
Create_priv: Y
Drop_priv: Y
Reload_priv: Y
Shutdown_priv: Y
Process_priv: Y
File_priv: Y
Grant_priv: Y
References_priv: Y
Index_priv: Y
Alter_priv: Y
Show_db_priv: Y
Super_priv: Y
Create_tmp_table_priv: Y
Lock_tables_priv: Y
Execute_priv: Y
Repl_slave_priv: Y
Repl_client_priv: Y
Create_view_priv: Y
Show_view_priv: Y
Create_routine_priv: Y
Alter_routine_priv: Y
Create_user_priv: Y
Event_priv: Y
Trigger_priv: Y
Create_tablespace_priv: Y <----------------------------- new column in 5.5
ssl_type:
ssl_cipher:
x509_issuer:
x509_subject:
max_questions: 0
max_updates: 0
max_connections: 0
max_user_connections: 0
plugin: <------------------------------- new column in 5.5
authentication_string: <------------------------------- new column in 5.5
1 row in set (0.00 sec)
There are also new tables in 5.5, such as mysql.proxies_user: make sure you have them.
When installing a brand new mysql server instance, the install script will create all the mysql.* tables with the proper structure.
When upgrading from an old version, make sure the proper upgrade procedure (mysql_upgrade) is used, which will add the missing tables / columns.
It is only a guess, but it seems mysql_upgrade was not done for this instance, causing the behavior seen.
originalArrayList.addAll(copyArrayList);
Please Note: When using the addAll() method to copy, the contents of both the array lists (originalArrayList and copyArrayList) refer to the same objects or contents. So if you modify any one of them the other will also reflect the same change.
If you don't wan't this then you need to copy each element from the originalArrayList to the copyArrayList, like using a for or while loop.
You can create table variable instead of tamp table in procedure A and execute procedure B and insert into temp table by below query.
DECLARE @T TABLE
(
TABLE DEFINITION
)
.
.
.
INSERT INTO @T
EXEC B @MYDATE
and you continue operation.
Add the s
modifier to your regex to cause .
to match newlines:
$string =~ /(START)(.+?)(END)/s;
You can achieve what you are trying to do, using a Stored Procedure
which returns a query result. Views
are not suitable / developed for operations like this one.
Check if there is a file called maintenance.flag and if so delete it.
Magento 1.x : maintenance.flag file is in : magento root directory
Magento 2.x : maintenance.flag file is in : var folder
When Magento is performing certain tasks it temporarily creates this file. Magento checks for its existence and if it's there will send users to the page you described.
It's supposed to automatically delete this file when done processing whatever task it was doing, but I've experienced occasions where something went wrong and it failed to delete it.
You can try this code
String[] stringA = new String[stringArrayList.size()];
stringArrayList.toArray(stringA)
System.out.println(stringA[0]);
b = a[a>threshold]
this should do
I tested as follows:
import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()
t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0
t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0
I got
$ python test.py
0:00:00.028000
0:00:02.461000
http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays
Step 1. Figure out which errors you want to trap:
If the table does not exist:
SQL> drop table x;
drop table x
*
ERROR at line 1:
ORA-00942: table or view does not exist
If the table is in use:
SQL> create global temporary table t (data varchar2(4000));
Table created.
Use the table in another session. (Notice no commit or anything after the insert.)
SQL> insert into t values ('whatever');
1 row created.
Back in the first session, attempt to drop:
SQL> drop table t;
drop table t
*
ERROR at line 1:
ORA-14452: attempt to create, alter or drop an index on temporary table already in use
So the two errors to trap:
See if the errors are predefined. They aren't. So they need to be defined like so:
create or replace procedure p as
table_or_view_not_exist exception;
pragma exception_init(table_or_view_not_exist, -942);
attempted_ddl_on_in_use_GTT exception;
pragma exception_init(attempted_ddl_on_in_use_GTT, -14452);
begin
execute immediate 'drop table t';
exception
when table_or_view_not_exist then
dbms_output.put_line('Table t did not exist at time of drop. Continuing....');
when attempted_ddl_on_in_use_GTT then
dbms_output.put_line('Help!!!! Someone is keeping from doing my job!');
dbms_output.put_line('Please rescue me');
raise;
end p;
And results, first without t
:
SQL> drop table t;
Table dropped.
SQL> exec p;
Table t did not exist at time of drop. Continuing....
PL/SQL procedure successfully completed.
And now, with t
in use:
SQL> create global temporary table t (data varchar2(4000));
Table created.
In another session:
SQL> insert into t values (null);
1 row created.
And then in the first session:
SQL> exec p;
Help!!!! Someone is keeping from doing my job!
Please rescue me
BEGIN p; END;
*
ERROR at line 1:
ORA-14452: attempt to create, alter or drop an index on temporary table already in use
ORA-06512: at "SCHEMA_NAME.P", line 16
ORA-06512: at line 1
You may take a look at this answer to an identical question (as I understand): https://stackoverflow.com/a/1478553 The link posted there explains the problem.
For quick solving your problem you should try to code something like this:
ImplementingClass::virtualFunctionToImplement(){...}
It helped me a lot.
No. Scroll speed is determined by the browser (and usually directly by the settings on the computer/device). CSS and Javascript don't (or shouldn't) have any way to affect system settings.
That being said, there are likely a number of ways you could try to fake a different scroll speed by moving your own content around in such a way as to counteract scrolling. However, I think doing so is a HORRIBLE idea in terms of usability, accessibility, and respect for your users, but I would start by finding events that your target browsers fire that indicate scrolling.
Once you can capture the scroll event (assuming you can), then you would be able to adjust your content dynamically so that the portion you want is visible.
Another approach would be to deal with this in Flash, which does give you at least some level of control over scrolling events.
To directly get image as numpy array without using PIL
import requests, io
import matplotlib.pyplot as plt
response = requests.get(url).content
img = plt.imread(io.BytesIO(response), format='JPG')
plt.imshow(img)
More simple:
return (byte[])System.ComponentModel.TypeDescriptor.GetConverter(pImagen).ConvertTo(pImagen, typeof(byte[]))
I was looking into this but wanted to have a different transition rate for in and out.
This is what I ended up doing:
//css
.addedClass {
background: #5eb4fc;
}
// js
function setParentTransition(id, prop, delay, style, callback) {
$(id).css({'-webkit-transition' : prop + ' ' + delay + ' ' + style});
$(id).css({'-moz-transition' : prop + ' ' + delay + ' ' + style});
$(id).css({'-o-transition' : prop + ' ' + delay + ' ' + style});
$(id).css({'transition' : prop + ' ' + delay + ' ' + style});
callback();
}
setParentTransition(id, 'background', '0s', 'ease', function() {
$('#elementID').addClass('addedClass');
});
setTimeout(function() {
setParentTransition(id, 'background', '2s', 'ease', function() {
$('#elementID').removeClass('addedClass');
});
});
This instantly turns the background color to #5eb4fc and then slowly fades back to normal over 2 seconds.
Here's a fiddle
From SQL Server 2016 you can just use
DROP TABLE IF EXISTS ##CLIENTS_KEYWORD
On previous versions you can use
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
/*Then it exists*/
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
You could also consider truncating the table instead rather than dropping and recreating.
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
TRUNCATE TABLE ##CLIENTS_KEYWORD
ELSE
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
You don't want a "temporary default Python"
You want the 2.7 scripts to start with
/usr/bin/env python2.7
And you want the 3.2 scripts to begin with
/usr/bin/env python3.2
There's really no use for a "default" Python. And the idea of a "temporary default" is just a road to absolute confusion.
Remember.
Explicit is better than Implicit.
The only exact solution is to perform arbitrary-precision decimal arithmetic for the base conversion, since the exact value can be very long - for 80-bit long double
, up to about 10000 decimal places. Fortunately it's "only" up to about 700 places or so for IEEE double
.
Rather than working with individual decimal digits, it's helpful to instead work base-1-billion (the highest power of 10 that fits in a 32-bit integer) and then convert these "base-1-billion digits" to 9 decimal digits each at the end of your computation.
I have a very dense (rather hard to read) but efficient implementation here, under LGPL MIT license:
http://git.musl-libc.org/cgit/musl/blob/src/stdio/vfprintf.c?h=v1.1.6
If you strip out all the hex float support, infinity/nan support, %g
/%f
/%e
variation support, rounding (which will never be needed if you only want exact answers), and other things you might not need, the remaining code is rather simple.
env VAR=value myScript args ...
I'm afraid that the first of those command lines unconditionally deleted from the working copy all the files that are in git's staging area. The second one unstaged all the files that were tracked but have now been deleted. Unfortunately this means that you will have lost any uncommitted modifications to those files.
If you want to get your working copy and index back to how they were at the last commit, you can (carefully) use the following command:
git reset --hard
I say "carefully" since git reset --hard
will obliterate uncommitted changes in your working copy and index. However, in this situation it sounds as if you just want to go back to the state at your last commit, and the uncommitted changes have been lost anyway.
Update: it sounds from your comments on Amber's answer that you haven't yet created any commits (since HEAD cannot be resolved), so this won't help, I'm afraid.
As for how those pipes work: git ls-files -z
and git diff --name-only --diff-filter=D -z
both output a list of file names separated with the byte 0
. (This is useful, since, unlike newlines, 0
bytes are guaranteed not to occur in filenames on Unix-like systems.) The program xargs
essentially builds command lines from its standard input, by default by taking lines from standard input and adding them to the end of the command line. The -0
option says to expect standard input to by separated by 0
bytes. xargs
may invoke the command several times to use up all the parameters from standard input, making sure that the command line never becomes too long.
As a simple example, if you have a file called test.txt
, with the following contents:
hello
goodbye
hello again
... then the command xargs echo whatever < test.txt
will invoke the command:
echo whatever hello goodbye hello again
If the files which you are loading are cached and if the changes you have made does not reflect in the code then there are 2 ways you can deal with this
Clear the Cache as everyone told
If u want Cache and only the files have to be reloaded , you can go to network tab of the dev tool and clear whatever was loaded. next time it will not load it from cache. you will have your latest changes.
You can get list of temp tables by following query :
select left(name, charindex('_',name)-1)
from tempdb..sysobjects
where charindex('_',name) > 0 and
xtype = 'u' and not object_id('tempdb..'+name) is null
An alternative to assume-unchanged
is skip-worktree
. The latter has a different meaning, something like "Git should not track this file. Developers can, and are encouraged, to make local changes."
In your situation where you do not wish to track changes to (typically large) build files, assume-unchanged
is a good choice.
In the situation where the file should have default contents and the developer is free to modify the file locally, but should not check their local changes back to the remote repo, skip-worktree
is a better choice.
Another elegant option is to have a default file in the repo. Say the filename is BuildConfig.Default.cfg
. The developer is expected to rename this locally to BuildConfig.cfg
and they can make whatever local changes they need. Now add BuildConfig.cfg
to .gitignore
so the file is untracked.
See this question which has some nice background information in the accepted answer.
This answer below does not directly answer the OP's question. However, I'm adding this answer here because this page is the first result when you Google "The total number of locks exceeds the lock table size".
If the query you are running is parsing an entire table that spans millions of rows, you can try a while loop instead of changing limits in the configuration.
The while look will break it into pieces. Below is an example looping over an indexed column that is DATETIME.
# Drop
DROP TABLE IF EXISTS
new_table;
# Create (we will add keys later)
CREATE TABLE
new_table
(
num INT(11),
row_id VARCHAR(255),
row_value VARCHAR(255),
row_date DATETIME
);
# Change the delimimter
DELIMITER //
# Create procedure
CREATE PROCEDURE do_repeat(IN current_loop_date DATETIME)
BEGIN
# Loops WEEK by WEEK until NOW(). Change WEEK to something shorter like DAY if you still get the lock errors like.
WHILE current_loop_date <= NOW() DO
# Do something
INSERT INTO
user_behavior_search_tagged_keyword_statistics_with_type
(
num,
row_id,
row_value,
row_date
)
SELECT
# Do something interesting here
num,
row_id,
row_value,
row_date
FROM
old_table
WHERE
row_date >= current_loop_date AND
row_date < current_loop_date + INTERVAL 1 WEEK;
# Increment
SET current_loop_date = current_loop_date + INTERVAL 1 WEEK;
END WHILE;
END//
# Run
CALL do_repeat('2017-01-01');
# Cleanup
DROP PROCEDURE IF EXISTS do_repeat//
# Change the delimimter back
DELIMITER ;
# Add keys
ALTER TABLE
new_table
MODIFY COLUMN
num int(11) NOT NULL,
ADD PRIMARY KEY
(num),
ADD KEY
row_id (row_id) USING BTREE,
ADD KEY
row_date (row_date) USING BTREE;
You can also adapt it to loop over the "num" column if your table doesn't use a date.
Hope this helps someone!
That's right, but it doesn't change it permanently, but just for current command prompt, if you wanna to change it permanently you have to use for example this:
setx ENV_VAR_NAME "DESIRED_PATH" /m
This will change it permanently and yes you can overwrite it by another batch script.
OK, after days struggling with this issue, I finally fixed it.
Simple!
Apparently there was a permission error with my local system that the C# compiler (csc.exe) could not access some resources and source codes.
In order to change your AppPool identity follow steps given here: http://learn.iis.net/page.aspx/624/application-pool-identities/
String text = "In early March, the city of Topeka, Kansas," + "<br>" +
"temporarily changed its name to Google..." + "<br>" + "<br>" +
"...in an attempt to capture a spot" + "<br>" +
"in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
"source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");
for some reason sharex was set to True so I turned it back to False and it worked fine.
df.plot(........,sharex=False)
My program does exactly what you are after, no prompts or anything, please see the following code.
This code will create all of the necessary directories if they don't already exist:
Directory.CreateDirectory(C:\dir\dira\dirb); // This code will create all of these directories
This code will download the given file to the given directory (after it has been created by the previous snippet:
private void install()
{
WebClient webClient = new WebClient(); // Creates a webclient
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); // Uses the Event Handler to check whether the download is complete
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged); // Uses the Event Handler to check for progress made
webClient.DownloadFileAsync(new Uri("http://www.com/newfile.zip"), @"C\newfile.zip"); // Defines the URL and destination directory for the downloaded file
}
So using these two pieces of code you can create all of the directories and then tell the downloader (that doesn't prompt you to download the file to that location.
From http://spreadsheetpage.com/index.php/tip/making_an_exact_copy_of_a_range_of_formulas_take_2:
Note: If the paste operation back to Excel doesn't work correctly, chances are that you've used Excel's Text-to-Columns feature recently, and Excel is trying to be helpful by remembering how you last parsed your data. You need to fire up the Convert Text to Columns Wizard. Choose the Delimited option and click Next. Clear all of the Delimiter option checkmarks except Tab.
Or, from http://spreadsheetpage.com/index.php/tip/making_an_exact_copy_of_a_range_of_formulas/:
If you're a VBA programmer, you can simply execute the following code:
With Sheets("Sheet1")
.Range("A11:D20").Formula = .Range("A1:D10").Formula
End With
There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).
Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.
Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.
I faced a similar issue on Docker for Ubuntu. It's a DNS issue. You will have to add Google Public DNS Settings into your network. Instruction for adding those settings is OS dependant. In my case, I was using Ubuntu so I added via network manager. Visit this site for more info.
git config user.email "[email protected]"
Doing that one inside a repo will set the configuration on THAT repo, and not globally.
Seems like that's pretty much what you're after, unless I'm misreading you.
The .NET garbage collector takes care of all this for you.
It is able to determine when objects are no longer referenced and will (eventually) free the memory that had been allocated to them.
Engine must be before select:
CREATE TEMPORARY TABLE temp1 ENGINE=MEMORY
as (select * from table1)
It's a language abstraction - some languages have both, some one, some neither.
In the case of C++, the code is not run in either the stack or the heap. You can test what happens if you run out of heap memory by repeatingly calling new
to allocate memory in a loop without calling delete
to free it it. But make a system backup before doing this.
Using Ctrl+Shift+R to refresh was nice but didn't get everything I needed. still some things wouldn't refresh, such as data stored in js and css. found a solution: a toolbar of google for chrome web developers. After you install the toolbar select options and "reset page".
My solution, after trying EVERYTHING:
Bad deployment, an old PrecompiledApp.config was hanging around my deploy location, and making everything not work.
My final settings that worked:
Nothing changes in the web.config - this means no special handlers for routing. Here's my snapshot of the sections a lot of other posts reference. I'm using FluorineFX, so I do have that handler added, but I did not need any others:
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="None"/>
<pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
<httpRuntime requestPathInvalidCharacters=""/>
<httpModules>
<add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx"/>
</httpModules>
</system.web>
<system.webServer>
<!-- Modules for IIS 7.0 Integrated mode -->
<modules>
<add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx" />
</modules>
<!-- Disable detection of IIS 6.0 / Classic mode ASP.NET configuration -->
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
Global.ashx: (only method of any note)
void Application_Start(object sender, EventArgs e) {
// Register routes...
System.Web.Routing.Route echoRoute = new System.Web.Routing.Route(
"{*message}",
//the default value for the message
new System.Web.Routing.RouteValueDictionary() { { "message", "" } },
//any regular expression restrictions (i.e. @"[^\d].{4,}" means "does not start with number, at least 4 chars
new System.Web.Routing.RouteValueDictionary() { { "message", @"[^\d].{4,}" } },
new TestRoute.Handlers.PassthroughRouteHandler()
);
System.Web.Routing.RouteTable.Routes.Add(echoRoute);
}
PassthroughRouteHandler.cs - this achieved an automatic conversion from http://andrew.arace.info/stackoverflow to http://andrew.arace.info/#stackoverflow which would then be handled by the default.aspx:
public class PassthroughRouteHandler : IRouteHandler {
public IHttpHandler GetHttpHandler(RequestContext requestContext) {
HttpContext.Current.Items["IncomingMessage"] = requestContext.RouteData.Values["message"];
requestContext.HttpContext.Response.Redirect("#" + HttpContext.Current.Items["IncomingMessage"], true);
return null;
}
}
I'm late to this party but I'd like to add one bit to user756519's thorough, excellent answer. I don't believe the "RetainSameConnection on the Connection Manager" property is relevant in this instance based on my recent experience. In my case, the relevant point was their advice to set "ValidateExternalMetadata" to False.
I'm using a temp table to facilitate copying data from one database (and server) to another, hence the reason "RetainSameConnection" was not relevant in my particular case. And I don't believe it is important to accomplish what is happening in this example either, as thorough as it is.
adapter.remove(arraylist.get(position));
adapter.notifyDataSetChanged();
or you can call again
setListAdapter(adapter)
This has been answered in a separate question and resolved the problem for me. Be sure to vote up the original person's answer.
ASP.Net error: "The type 'foo' exists in both "temp1.dll" and "temp2.dll"
Add the batch="false" attribute to the "compilation" element of the web.config file.
This problem occurs because of the way in which ASP.NET 2.0 uses the application references and the folder structure of the application to compile the application. If the batch property of the element in the web.config file for the application is set to true, ASP.NET 2.0 compiles each folder in the application into a separate assembly.
http://www.sellsbrothers.com/news/showTopic.aspx?ixTopic=1995
public void javascriptclick(String element)
{
WebElement webElement=driver.findElement(By.xpath(element));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();",webElement);
System.out.println("javascriptclick"+" "+ element);
}
Why don't you go even more pythonic?
class AutoList:
def __init__(self, inp):
try: ## Assume an opened-file...
self.data = inp.read()
except AttributeError:
try: ## Assume an existent filename...
with open(inp, 'r') as fd:
self.data = fd.read()
except:
self.data = inp ## Who cares what that might be?
You can even make it fancier with extensions:
namespace Foo
{
public static class Extensions
{
public static byte[] ToByteArray(this Stream stream)
{
using (stream)
{
using (MemoryStream memStream = new MemoryStream())
{
stream.CopyTo(memStream);
return memStream.ToArray();
}
}
}
}
}
And then call it as a regular method:
byte[] arr = someStream.ToByteArray()
If your Windows 7 machine is a member of an AD, or if you have UAC enabled, or if security policies are in effect, telnet more often than not must be run as an admin. The easiest way to do this is as follows
Create a shortcut that calls cmd.exe
Go to the shortcut's properties
Click on the Advanced button
Check the "Run as an administrator" checkbox
After these steps you're all set and telnet should work now.
To remove all the constraints from the DB:
SELECT 'ALTER TABLE ' + Table_Name +' DROP CONSTRAINT ' + Constraint_Name
FROM Information_Schema.CONSTRAINT_TABLE_USAGE
TortoiseGit does this. see this blog post: http://jimmykeen.net/articles/03-nov-2012/how-migrate-from-svn-to-git-windows-using-tortoise-clients
Yeah, I know answering with links isn't splendid but it's a solution, eh?
It sounds like you installed (extracted) the source files instead of the binaries based on your path information. Try installing the binaries instead and following the other posters answer.
So what is the URL that Yii::app()->params['pdfUrl']
gives? You say it should be https, but the log shows it's connecting on port 80... which almost no server is setup to accept https connections on. cURL is smart enough to know https should be on port 443... which would suggest that your URL has something wonky in it like: https://196.41.139.168:80/serve/?r=pdf/generatePdf
That's going to cause the connection to be terminated, when the Apache at the other end cannot do https communication with you on that port.
You realize your first $body
definition gets replaced when you set $body
to an array two lines later? {Probably just an artifact of you trying to solve the problem} You're also not encoding the client_url
and client_id
values (the former quite possibly containing characters that need escaping!) Oh and you're appending to $body_str
without first initializing it.
From your verbose output we can see cURL is adding a content-length
header, but... is it correct? I can see some comments out on the internets of that number being wrong (especially with older versions)... if that number was to small (for example) you'd get a connection-reset before all the data is sent. You can manually insert the header:
curl_setopt ($c, CURLOPT_HTTPHEADER,
array("Content-Length: ". strlen($body_str)));
Oh and there's a handy function http_build_query
that'll convert an array of name/value pairs into a URL encoded string for you.
All this rolls up into the final code:
$post=http_build_query(array(
"client_url"=>Yii::app()->params['pdfClientURL'],
"client_id"=>Yii::app()->params['pdfClientID'],
"title"=>$title,
"content"=>$content));
//Open to URL
$c=curl_init(Yii::app()->params['pdfUrl']);
//Send post
curl_setopt ($c, CURLOPT_POST, true);
//Optional: [try with/without]
curl_setopt ($c, CURLOPT_HTTPHEADER, array("Content-Length: ".strlen($post)));
curl_setopt ($c, CURLOPT_POSTFIELDS, $post);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($c, CURLOPT_CONNECTTIMEOUT , 0);
curl_setopt ($c, CURLOPT_TIMEOUT , 20);
//Collect result
$pdf = curl_exec ($c);
$curlInfo = curl_getinfo($c);
curl_close($c);
I like to use phpDebug for profiling. http://phpdebug.sourceforge.net/www/index.html
It outputs all time / memory usage for any SQL used as well as all the included files. Obviously, it works best on code that's abstracted.
For function and class profiling I'll just use microtime()
+ get_memory_usage()
+ get_peak_memory_usage()
.
If you use XCode
5 you should do it in a different way.
UIViewController
in UIStoryboard
Identity Inspector
on the right top paneUse Storyboard ID
checkboxStoryboard ID
fieldThen write your code.
// Override point for customization after application launch.
if (<your implementation>) {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main"
bundle: nil];
YourViewController *yourController = (YourViewController *)[mainStoryboard
instantiateViewControllerWithIdentifier:@"YourViewControllerID"];
self.window.rootViewController = yourController;
}
return YES;
Within your <jre location>\lib\security\java.policy
try adding:
grant {
permission java.security.AllPermission;
};
And see if it allows you. If so, you will have to add more granular permissions.
See:
Java 8 Documentation for java.policy files
and
http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html
The max size for a column of type NVARCHAR(MAX)
is 2 GByte of storage.
Since NVARCHAR
uses 2 bytes per character, that's approx. 1 billion characters.
Leo Tolstoj's War and Peace is a 1'440 page book, containing about 600'000 words - so that might be 6 million characters - well rounded up. So you could stick about 166 copies of the entire War and Peace book into each NVARCHAR(MAX)
column.
Is that enough space for your needs? :-)
you can use this..
<select name="select_name">
<option value="1"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='1')?' selected="selected"':'');?>>Yes</option>
<option value="2"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='2')?' selected="selected"':'');?>>No</option>
<option value="3"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='3')?' selected="selected"':'');?>>Fine</option>
</select>
I found this helped where my words were breaking part way through the word in a WooThemes Testimonial plugin.
.testimonials-text {
white-space: normal;
}
play with it here http://nortronics.com.au/recomendations/
<blockquote class="testimonials-text" itemprop="reviewBody">
<a href="http://www.jacobs.com/" class="avatar-link">
<img width="100" height="100" src="http://nortronics.com.au/wp-content/uploads/2015/11/SKM-100x100.jpg" class="avatar wp-post-image" alt="SKM Sinclair Knight Merz">
</a>
<p>Tim continues to provide high-level technical applications advice and support for a very challenging IP video application. He has shown he will go the extra mile to ensure all avenues are explored to identify an innovative and practical solution.<br>Tim manages to do this with a very helpful and professional attitude which is much appreciated.
</p>
</blockquote>
If this is a BAT file in a different directory than the current directory, you may see an error like "python: can't open file 'somescript.py': [Errno 2] No such file or directory". This can be fixed by specifying an absolute path to the BAT file using %~dp0
(the drive letter and path of that batch file).
@echo off
python %~dp0\somescript.py %*
(This way you can ignore the c:\
or whatever, because perhaps you may want to move this script)
sed is line based, so I'm not sure why you want to do this with sed. The paradigm is more processing one line at a time( you could also programatically find the # of fields in the CSV and generate your header line with awk) Why not just
echo "c1, c2, ... " >> file
cat testfile.csv >> file
?
If you know the extension, you can use basename
$ basename /home/jsmith/base.wiki .wiki
base
It's because of x and y offset. Try this:
-webkit-box-shadow: 0 0 10px #fff;
box-shadow: 0 0 10px #fff;
edit (year later..): Made the answer more cross-browser, as requested in comments :)
btw: there are many css3 generator nowadays.. css3.me, css3maker, css3generator etc...
Not sure if this is still relevant, but I use this way
Public bEnableEvents As Boolean
Public bclickok As Boolean
Public booRestoreErrorChecking As Boolean 'put this at the top of the module
Private Declare Function apiGetComputerName Lib "kernel32" Alias _
"GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Function GetUserID() As String
' Returns the network login name
On Error Resume Next
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)
If lngX <> 0 Then
GetUserID = Left$(strUserName, lngLen - 1)
Else
GetUserID = ""
End If
Exit Function
End Function
This next bit I save file as PDF, but can change to suit
Public Sub SaveToDesktop()
Dim LoginName As String
LoginName = UCase(GetUserID)
ChDir "C:\Users\" & LoginName & "\Desktop\"
Debug.Print LoginName
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\" & LoginName & "\Desktop\MyFileName.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End Sub
Here's your script...
DIR=$(pwd)
echo $DIR
while [ "$DIR" != "/" ]; do
cd ..
DIR=$(pwd)
echo $DIR
done
Note the spaces, use of quotes, and $ signs.
Here's what i do to FORCE UNLOCK FOR some locked tables in MySQL
1) Enter MySQL
mysql -u your_user -p
2) Let's see the list of locked tables
mysql> show open tables where in_use>0;
3) Let's see the list of the current processes, one of them is locking your table(s)
mysql> show processlist;
4) Let's kill one of these processes
mysql> kill put_process_id_here;
VSCode is a code editor, not a full IDE. Think of VSCode as a notepad on steroids with IntelliSense code completion, richer semantic code understanding of multiple languages, code refactoring, including navigation, keyboard support with customizable bindings, syntax highlighting, bracket matching, auto indentation, and snippets.
It's not meant to replace Visual Studio, but making "Visual Studio" part of the name in VSCode will of course confuse some people at first.
If you want to use this with command line or function arguments, make sure you use size=${#1}
instead of size=${#$1}
. The second one may be more instinctual but is incorrect syntax.
Default values in appcompat-v7
<dimen name="abc_text_size_body_1_material">14sp</dimen>
<dimen name="abc_text_size_body_2_material">14sp</dimen>
<dimen name="abc_text_size_button_material">14sp</dimen>
<dimen name="abc_text_size_caption_material">12sp</dimen>
<dimen name="abc_text_size_display_1_material">34sp</dimen>
<dimen name="abc_text_size_display_2_material">45sp</dimen>
<dimen name="abc_text_size_display_3_material">56sp</dimen>
<dimen name="abc_text_size_display_4_material">112sp</dimen>
<dimen name="abc_text_size_headline_material">24sp</dimen>
<dimen name="abc_text_size_large_material">22sp</dimen>
<dimen name="abc_text_size_medium_material">18sp</dimen>
<dimen name="abc_text_size_menu_material">16sp</dimen>
<dimen name="abc_text_size_small_material">14sp</dimen>
<dimen name="abc_text_size_subhead_material">16sp</dimen>
<dimen name="abc_text_size_subtitle_material_toolbar">16dp</dimen>
<dimen name="abc_text_size_title_material">20sp</dimen>
<dimen name="abc_text_size_title_material_toolbar">20dp</dimen>
The value of hjust
and vjust
are only defined between 0 and 1:
Source: ggplot2, Hadley Wickham, page 196
(Yes, I know that in most cases you can use it beyond this range, but don't expect it to behave in any specific way. This is outside spec.)
hjust
controls horizontal justification and vjust
controls vertical justification.
An example should make this clear:
td <- expand.grid(
hjust=c(0, 0.5, 1),
vjust=c(0, 0.5, 1),
angle=c(0, 45, 90),
text="text"
)
ggplot(td, aes(x=hjust, y=vjust)) +
geom_point() +
geom_text(aes(label=text, angle=angle, hjust=hjust, vjust=vjust)) +
facet_grid(~angle) +
scale_x_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2)) +
scale_y_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2))
To understand what happens when you change the hjust
in axis text, you need to understand that the horizontal alignment for axis text is defined in relation not to the x-axis, but to the entire plot (where this includes the y-axis text). (This is, in my view, unfortunate. It would be much more useful to have the alignment relative to the axis.)
DF <- data.frame(x=LETTERS[1:3],y=1:3)
p <- ggplot(DF, aes(x,y)) + geom_point() +
ylab("Very long label for y") +
theme(axis.title.y=element_text(angle=0))
p1 <- p + theme(axis.title.x=element_text(hjust=0)) + xlab("X-axis at hjust=0")
p2 <- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab("X-axis at hjust=0.5")
p3 <- p + theme(axis.title.x=element_text(hjust=1)) + xlab("X-axis at hjust=1")
library(ggExtra)
align.plots(p1, p2, p3)
To explore what happens with vjust
aligment of axis labels:
DF <- data.frame(x=c("a\na","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()
p1 <- p + theme(axis.text.x=element_text(vjust=0, colour="red")) +
xlab("X-axis labels aligned with vjust=0")
p2 <- p + theme(axis.text.x=element_text(vjust=0.5, colour="red")) +
xlab("X-axis labels aligned with vjust=0.5")
p3 <- p + theme(axis.text.x=element_text(vjust=1, colour="red")) +
xlab("X-axis labels aligned with vjust=1")
library(ggExtra)
align.plots(p1, p2, p3)
For create circle button you are this codes:
.circle-right-btn {
display: block;
height: 50px;
width: 50px;
border-radius: 50%;
border: 1px solid #fefefe;
margin-top: 24px;
font-size:22px;
}
_x000D_
<input class="circle-right-btn" type="submit" value="<">
_x000D_
If the API says to use HTTP Basic authentication, then you need to add an Authorization header to your request. I'd alter your code to look like this:
WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value¶m2=value");
req.Method = "GET";
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
//req.Credentials = new NetworkCredential("username", "password");
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
Replacing "username"
and "password"
with the correct values, of course.
Since version 2020.1, you can activate Run on save for files directly in the Preferences of the Prettier plugin:
This script generates the command file then pipes the command file to the ftp program, creating a log along the way. Finally print the original bat file, the command files and the log of this session.
@echo on
@echo off > %0.ftp
::== GETmy!dir.bat
>> %0.ftp echo a00002t
>> %0.ftp echo iasdad$2
>> %0.ftp echo help
>> %0.ftp echo prompt
>> %0.ftp echo ascii
>> %0.ftp echo !dir REPORT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo get REPORT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo !dir REPORT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo *************************************************
>> %0.ftp echo !dir CONTENT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo get CONTENT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo !dir CONTENT.CP1C.ROLLEDUP.TXT
>> %0.ftp echo *************************************************
>> %0.ftp echo !dir WORKLOAD.CP1c.ROLLEDUP.TXT
>> %0.ftp echo get WORKLOAD.CP1C.ROLLEDUP.TXT
>> %0.ftp echo !dir WORKLOAD.CP1C.ROLLEDUP.TXT
>> %0.ftp echo *************************************************
>> %0.ftp echo !dir REPORT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo get REPORT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo !dir REPORT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo *************************************************
>> %0.ftp echo !dir CONTENT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo get CONTENT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo !dir CONTENT.TMMC.ROLLEDUP.TXT
>> %0.ftp echo **************************************************
>> %0.ftp echo !dir WORKLOAD.TMMC.ROLLEDUP.TXT
>> %0.ftp echo get WORKLOAD.TMMC.ROLLEDUP.TXT
>> %0.ftp echo !dir WORKLOAD.TMMC.ROLLEDUP.TXT
>> %0.ftp echo quit
ftp -d -v -s:%0.ftp 150.45.12.18 > %0.log
type %0.bat
type %0.ftp
type %0.log
The same will happen if your published version is not the same as the version you're testing on your phone.
For example, uploaded version is android:versionCode="1"
, and the version you're testing on your phone is android:versionCode="2"
With @Lob
I always end up with a LONGTEXT
in MySQL.
To get TEXT
I declare it that way (JPA 2.0):
@Column(columnDefinition = "TEXT")
private String text
Find this better, because I can directly choose which Text-Type the column will have in database.
For columnDefinition
it is also good to read this.
EDIT: Please pay attention to Adam Siemions comment and check the database engine you are using, before applying columnDefinition = "TEXT"
.
It's written down in the Fielding dissertation. But if you don't want to read a lot:
Just wanted to add a bit to Raphael's great answer. Here's how to get PHP to produce the same $_FILES
, regardless of whether you use JavaScript to submit.
HTML form:
<form enctype="multipart/form-data" action="/test.php"
method="post" class="putImages">
<input name="media[]" type="file" multiple/>
<input class="button" type="submit" alt="Upload" value="Upload" />
</form>
PHP produces this $_FILES
, when submitted without JavaScript:
Array
(
[media] => Array
(
[name] => Array
(
[0] => Galata_Tower.jpg
[1] => 518f.jpg
)
[type] => Array
(
[0] => image/jpeg
[1] => image/jpeg
)
[tmp_name] => Array
(
[0] => /tmp/phpIQaOYo
[1] => /tmp/phpJQaOYo
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 258004
[1] => 127884
)
)
)
If you do progressive enhancement, using Raphael's JS to submit the files...
var data = new FormData($('input[name^="media"]'));
jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
data.append(i, file);
});
$.ajax({
type: ppiFormMethod,
data: data,
url: ppiFormActionURL,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
}
});
... this is what PHP's $_FILES
array looks like, after using that JavaScript to submit:
Array
(
[0] => Array
(
[name] => Galata_Tower.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpAQaOYo
[error] => 0
[size] => 258004
)
[1] => Array
(
[name] => 518f.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpBQaOYo
[error] => 0
[size] => 127884
)
)
That's a nice array, and actually what some people transform $_FILES
into, but I find it's useful to work with the same $_FILES
, regardless if JavaScript was used to submit. So, here are some minor changes to the JS:
// match anything not a [ or ]
regexp = /^[^[\]]+/;
var fileInput = $('.putImages input[type="file"]');
var fileInputName = regexp.exec( fileInput.attr('name') );
// make files available
var data = new FormData();
jQuery.each($(fileInput)[0].files, function(i, file) {
data.append(fileInputName+'['+i+']', file);
});
(14 April 2017 edit: I removed the form element from the constructor of FormData() -- that fixed this code in Safari.)
That code does two things.
input
name attribute automatically, making the HTML more maintainable. Now, as long as form
has the class putImages, everything else is taken care of automatically. That is, the input
need not have any special name.With these changes, submitting with JavaScript now produces precisely the same $_FILES
array as submitting with simple HTML.
Try something like this:
foreach (ListItem listItem in clbIncludes.Items)
{
if (listItem.Selected) {
//do some work
}
else {
//do something else
}
}
Similar as they are, merge!
and store
treat existing hashes differently depending on keynames, and will therefore affect your preference. Other than that from a syntax standpoint, merge!
's key: "value"
syntax closely matches up against JavaScript and Python. I've always hated comma-separating key-value pairs, personally.
hash = {}
hash.merge!(key: "value")
hash.merge!(:key => "value")
puts hash
{:key=>"value"}
hash = {}
hash.store(:key, "value")
hash.store("key", "value")
puts hash
{:key=>"value", "key"=>"value"}
To get the shovel operator <<
working, I would advise using Mark Thomas's answer.
I had a requirement to register user. In that case I need to check whether that username is already present in the database or not. I have tried the below in C# windows form application(EntityFramework) and it worked.
var result = incomeExpenseManagementDB.Users.FirstOrDefault(x => x.userName == registerUserView.uNameText);
if (result == null) {
register.registerUser(registerUserView.fnameText, registerUserView.lnameText, registerUserView.eMailText, registerUserView.mobileText, registerUserView.bDateText, registerUserView.uNameText, registerUserView.pWordText);
} else {
MessageBox.Show("User Alreay Exist. Try with Different Username");
}
I had a similar fault:
error: RPC failed; curl 56 GnuTLS recv error (-9): A TLS packet with unexpected length was received.
when trying to clone a repository from Github.
After trying most of the solutions posted here, none of which worked, it turned out to be the parental controls on our home network. Turning these parental controls off solved the problem.
Another cause of "TCP ACKed Unseen" is the number of packets that may get dropped in a capture. If I run an unfiltered capture for all traffic on a busy interface, I will sometimes see a large number of 'dropped' packets after stopping tshark.
On the last capture I did when I saw this, I had 2893204 packets captured, but once I hit Ctrl-C, I got a 87581 packets dropped message. Thats a 3% loss, so when wireshark opens the capture, its likely to be missing packets and report "unseen" packets.
As I mentioned, I captured a really busy interface with no capture filter, so tshark had to sort all packets, when I use a capture filter to remove some of the noise, I no longer get the error.
Here's an example of how you could implement a list view:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//We have our list view
final ListView dynamic = findViewById(R.id.dynamic);
//Create an array of elements
final ArrayList<String> classes = new ArrayList<>();
classes.add("Data Structures");
classes.add("Assembly Language");
classes.add("Calculus 3");
classes.add("Switching Systems");
classes.add("Analysis Tools");
//Create adapter for ArrayList
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, classes);
//Insert Adapter into List
dynamic.setAdapter(adapter);
//set click functionality for each list item
dynamic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("User clicked ", classes.get(position));
}
});
}
From Python Cookbook v.30
def myfun():
return 1, 2, 3
a, b, c = myfun()
Although it looks like
myfun()
returns multiple values, atuple
is actually being created. It looks a bit peculiar, but it’s actually the comma that forms a tuple, not the parentheses
So yes, what's going on in Python is an internal transformation from multiple comma separated values to a tuple and vice-versa.
Though there's no equivalent in java you can easily create this behaviour using array
's or some Collection
s like List
s:
private static int[] sumAndRest(int x, int y) {
int[] toReturn = new int[2];
toReturn[0] = x + y;
toReturn[1] = x - y;
return toReturn;
}
Executed in this way:
public static void main(String[] args) {
int[] results = sumAndRest(10, 5);
int sum = results[0];
int rest = results[1];
System.out.println("sum = " + sum + "\nrest = " + rest);
}
result:
sum = 15
rest = 5
For Windows Users :
If this issue occurs on your self hosted server (eg: your custom CDN) and the browser (Chrome) says something like ... ('text/plain') is not executable ...
when trying to load your javascript file ...
Here is what you need to do :
Win + R > regedit
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.js
application/javascript
or not application/javascript
and try again You should use the .offsetWidth
and .offsetHeight
properties.
Note they belong to the element, not .style
.
var width = document.getElementById('foo').offsetWidth;
Function .getBoundingClientRect()
returns dimensions and location of element as floating-point numbers after performing CSS transforms.
> console.log(document.getElementById('id').getBoundingClientRect())
DOMRect {
bottom: 177,
height: 54.7,
left: 278.5,?
right: 909.5,
top: 122.3,
width: 631,
x: 278.5,
y: 122.3,
}
Try this one -
WHERE DateDropped = 0
AND (
(ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0)
OR
(ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0)
)
Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.
OpenSessionInViewFilter
calls the openSession
method of the underlying SessionFactory
and obtains a new Session
.Session
is bound to the TransactionSynchronizationManager
.OpenSessionInViewFilter
calls the doFilter
of the javax.servlet.FilterChain
object reference and the request is further processedDispatcherServlet
is called, and it routes the HTTP request to the underlying PostController
.PostController
calls the PostService
to get a list of Post
entities.PostService
opens a new transaction, and the HibernateTransactionManager
reuses the same Session
that was opened by the OpenSessionInViewFilter
.PostDAO
fetches the list of Post
entities without initializing any lazy association.PostService
commits the underlying transaction, but the Session
is not closed because it was opened externally.DispatcherServlet
starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.OpenSessionInViewFilter
can close the Session
, and the underlying database connection is released as well.At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.
The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection
as read-only which would allow the database server to avoid writing to the transaction log.
There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.
The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize
for fetching associations in batches, and FetchMode.SUBSELECT
to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.
Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.
Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.
So, make sure that in the application.properties
configuration file, you have the following entry:
spring.jpa.open-in-view=false
This will disable OSIV so that you can handle the LazyInitializationException
the right way.
Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.
import urllib.request
import requests
from bs4 import BeautifulSoup
r = requests.get('https://icons8.com/icons/set/favicon')
If you try to connect to such a site, you will get an indent error.
import urllib.request
import requests
from bs4 import BeautifulSoup
r = requests.get('https://icons8.com/icons/set/favicon')
Python cares about indents
In your spring class, You can inject a bean annotated like as
@Autowired
@Qualifier("dbDataSource")
private DataSource dataSource;
and You add this in your context.xml
<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/>
</beans:bean>
You can declare the JNDI resource in tomcat's server.xml using
<Resource name="jdbc/TestDB"
global="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/TestDB"
username="pankaj"
password="pankaj123"
maxActive="100"
maxIdle="20"
minIdle="5"
maxWait="10000"/>
back to context.xml de spring add this
<ResourceLink name="jdbc/MyLocalDB"
global="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource" />
if, like this exmple you are injecting connection to database, make sure that MySQL jar is present in the tomcat lib directory, otherwise tomcat will not be able to create the MySQL database connection pool.
Check out this MD5 implementation for JavaScript. Its BSD Licensed and really easy to use. Example:
md5 = hex_md5("message to digest")
$timestamp = strtotime($row['DATETIMEAPP']);
gives you timestamp, which then you can use date to format:
$date = date('d-m-Y', $timestamp);
$time = date('Gi.s', $timestamp);
Alternatively
list($date, $time) = explode('|', date('d-m-Y|Gi.s', $timestamp));
Either one would work. It depends on your needs:
If your bean identifier contains special character(s) for example (/viewSummary.html
), it wont be allowed as the bean id
, because it's not a valid XML ID. In such cases you could skip defining the bean id
and supply the bean name
instead.
The name
attribute also helps in defining alias
es for your bean, since it allows specifying multiple identifiers for a given bean.
try to ad the following in your CSS:
body, html{
padding:0;
margin:0;
}
The R packages geosphere will calculate bearingRhumb, which is a constant bearing line given an origin point and easting/northing. The easting and northing must be in a matrix or vector. The origin point for a wind rose is 0,0. The following code seems to readily resolve the issue:
windE<-wind$uasE
windN<-wind$vasN
wind_matrix<-cbind(windE, windN)
wind$wind_dir<-bearingRhumb(c(0,0), wind_matrix)
wind$wind_dir<-round(wind$wind_dir, 0)
The S parameter does not do anything on its own.
/S Modifies the treatment of string after /C or /K (see below)
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
Try something like this instead
Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)
You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.
Shell("perl a.pl c:\temp")
-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn
Important behavior changes between old and new style classes
Exception
(example below)__slots__
addedIt was mentioned in other answers, but here goes a concrete example of the difference between classic MRO and C3 MRO (used in new style classes).
The question is the order in which attributes (which include methods and member variables) are searched for in multiple inheritance.
Classic classes do a depth-first search from left to right. Stop on the first match. They do not have the __mro__
attribute.
class C: i = 0
class C1(C): pass
class C2(C): i = 2
class C12(C1, C2): pass
class C21(C2, C1): pass
assert C12().i == 0
assert C21().i == 2
try:
C12.__mro__
except AttributeError:
pass
else:
assert False
New-style classes MRO is more complicated to synthesize in a single English sentence. It is explained in detail here. One of its properties is that a base class is only searched for once all its derived classes have been. They have the __mro__
attribute which shows the search order.
class C(object): i = 0
class C1(C): pass
class C2(C): i = 2
class C12(C1, C2): pass
class C21(C2, C1): pass
assert C12().i == 2
assert C21().i == 2
assert C12.__mro__ == (C12, C1, C2, C, object)
assert C21.__mro__ == (C21, C2, C1, C, object)
Exception
Around Python 2.5 many classes could be raised, and around Python 2.6 this was removed. On Python 2.7.3:
# OK, old:
class Old: pass
try:
raise Old()
except Old:
pass
else:
assert False
# TypeError, new not derived from `Exception`.
class New(object): pass
try:
raise New()
except TypeError:
pass
else:
assert False
# OK, derived from `Exception`.
class New(Exception): pass
try:
raise New()
except New:
pass
else:
assert False
# `'str'` is a new style object, so you can't raise it:
try:
raise 'str'
except TypeError:
pass
else:
assert False
Another option you could try is iptstate.
Maybe your mobile view port is not set.
Add following meta tag inside <head></head>
to allow menu to work on mobiles.
<meta name=viewport content="width=device-width, initial-scale=1">
If still not working you can call garbage collector to close the file and free up memory
System.gc();
if(new File("./__tmp.txt").delete()){
System.out.println("OK");
}
Don't forget to close that file, if any previous opening using code snippet fio.close()
I tested in Java 1.8, works well.
In HTML, elements containing nothing but normal whitespace characters are considered empty. A paragraph that contains just a normal space character will have zero height. A non-breaking space is a special kind of whitespace character that isn't considered to be insignificant, so it can be used as content for a non-empty paragraph.
Even if you consider CSS margins on paragraphs, since an "empty" paragraph has zero height, its vertical margins will collapse. This causes it to have no height and no margins, making it appear as if it were never there at all.
If you know that you'll want to see all Comment
s every time you retrieve a Topic
then change your field mapping for comments
to:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "topic", cascade = CascadeType.ALL)
private Collection<Comment> comments = new LinkedHashSet<Comment>();
Collections are lazy-loaded by default, take a look at this if you want to know more.
The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:
struct { 11
char a; 012345678901
short b; ------------
char c; axbbcxxxdddd
int d;
};
This structure will occupy 12 bytes of memory (x being pad bytes).
Python works similarly (see the struct documentation):
>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12
Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:
>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'
Beware of letting struct handle padding. In C, these structures:
struct A { struct B {
short a; int a;
char b; char b;
}; };
are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:
>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'
No, <!-- ... -->
is the only comment syntax in HTML.
ListBuffer
is a mutable list which has constant-time append, and constant-time conversion into a List
.
List
is immutable and has constant-time prepend and linear-time append.
How you construct your list depends on the algorithm you'll use the list for and the order in which you get the elements to create it.
For instance, if you get the elements in the opposite order of when they are going to be used, then you can just use a List
and do prepends. Whether you'll do so with a tail-recursive function, foldLeft
, or something else is not really relevant.
If you get the elements in the same order you use them, then a ListBuffer
is most likely a preferable choice, if performance is critical.
But, if you are not on a critical path and the input is low enough, you can always reverse
the list later, or just foldRight
, or reverse
the input, which is linear-time.
What you DON'T do is use a List
and append to it. This will give you much worse performance than just prepending and reversing at the end.
You can modify your AndroidManifest.xml
:
<activity android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
or use android:theme="@android:style/Theme.Black.NoTitleBar"
if you don't need a fullscreen Activity.
Note: If you've used a 'default' view before, you probably should also change the parent class from AppCompatActivity
to Activity
.
I have struggled for the past couple of days trying to download pdfs and images,all I was able to download was simple text files.
Most of the questions have the same components, but it took a while to figure out the right order to make it work.
Thank you @Nikolay Melnikov, your comment/reply to this question was what made it work.
In a nutshell, here is my AngularJS Service backend call:
getDownloadUrl(fileID){
//
//Get the download url of the file
let fullPath = this.paths.downloadServerURL + fileId;
//
// return the file as arraybuffer
return this.$http.get(fullPath, {
headers: {
'Authorization': 'Bearer ' + this.sessionService.getToken()
},
responseType: 'arraybuffer'
});
}
From my controller:
downloadFile(){
myService.getDownloadUrl(idOfTheFile).then( (response) => {
//Create a new blob object
let myBlobObject=new Blob([response.data],{ type:'application/pdf'});
//Ideally the mime type can change based on the file extension
//let myBlobObject=new Blob([response.data],{ type: mimeType});
var url = window.URL || window.webkitURL
var fileURL = url.createObjectURL(myBlobObject);
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href',fileURL);
downloadLink.attr('download',this.myFilesObj[documentId].name);
downloadLink.attr('target','_self');
downloadLink[0].click();//call click function
url.revokeObjectURL(fileURL);//revoke the object from URL
});
}
yes on your aspx page include a script tag with runat=server
<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
// some load code
}
</script>
You can also use classic ASP Syntax
<% if (this.MyTextBox.Visible) { %>
<span>Only show when myTextBox is visible</span>
<% } %>
Although this issue is quite old, i think this is relevant news / the most recent answer: Microsoft open-sourced XAML Behaviours and posted a blog post how to update to this version: https://devblogs.microsoft.com/dotnet/open-sourcing-xaml-behaviors-for-wpf/
To save you a click, this is the main steps to migrate:
Try to clean the project and rebuild it.
One more thing that I haven't seen mentioned here - Xcode supports .h files with "_private" in the name. Let's say you have a class MyClass - you have MyClass.m and MyClass.h and now you can also have MyClass_private.h. Xcode will recognize this and include it in the list of "Counterparts" in the Assistant Editor.
//MyClass.m
#import "MyClass.h"
#import "MyClass_private.h"
Maybe you are looking for jar
command to get the list of classes in terminal,
$ jar tf ~/.m2/repository/org/apache/spark/spark-assembly/1.2.0-SNAPSHOT/spark-assembly-1.2.0-SNAPSHOT-hadoop1.0.4.jar
META-INF/
META-INF/MANIFEST.MF
org/
org/apache/
org/apache/spark/
org/apache/spark/unused/
org/apache/spark/unused/UnusedStubClass.class
META-INF/maven/
META-INF/maven/org.spark-project.spark/
META-INF/maven/org.spark-project.spark/unused/
META-INF/maven/org.spark-project.spark/unused/pom.xml
META-INF/maven/org.spark-project.spark/unused/pom.properties
META-INF/NOTICE
where,
-t list table of contents for archive
-f specify archive file name
Or, just grep above result to see .class
es only
$ jar tf ~/.m2/repository/org/apache/spark/spark-assembly/1.2.0-SNAPSHOT/spark-assembly-1.2.0-SNAPSHOT-hadoop1.0.4.jar | grep .class
org/apache/spark/unused/UnusedStubClass.class
To see number of class
es,
jar tvf launcher/target/usergrid-launcher-1.0-SNAPSHOT.jar | grep .class | wc -l
61079
Late, but to be completed with options here: A handy tool to install any apk via gui to a running emulator is: http://apkinstaller.com
This can directly connect to a running instance via adb and can successfully install any kind of apk packages.
Maybe this is also helpful for other people. ;)
SELECT a.image_id
FROM list a
INNER JOIN list b
ON a.image_id = b.image_id
AND b.style_id = 25
AND b.style_value = 'big'
INNER JOIN list c
ON a.image_id = c.image_id
AND c.style_id = 27
AND c.style_value = 'round'
WHERE a.style_id = 24
AND a.style_value = 'red'
To me the best way is -
Hope this will help .
Add following Spark dependencies to POM file :
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>2.2.0</version>
</dependency>
//Spark configuration:
val spark = SparkSession.builder().master("local").appName("Sample App").getOrCreate()
//Read csv file:
val df = spark.read.option("header", "true").csv("FILE_PATH")
// Display output
df.show()
private Paint green = new Paint();
private int greenx , greeny;
green.setColor(Color.GREEN);
green.setAntiAlias(false);
canvas.drawCircle(greenx,greeny,20,green);
what about simply this:
byte[] args2 = getByteArry();
String byteStr = new String(args2);
In my case, another program had added PATH
changes to .bashrc
If the other program changed the PATH
after nvm's initialisation, then nvm's PATH
changes would be forgotten, and we would get the system node on our PATH
(or no node).
The solution was to move the nvm setup to the bottom of .bashrc
### BAD .bashrc ###
# NVM initialisation
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
# Some other program adding to the PATH:
export PATH="$ANT_ROOT:$PATH"
Solution:
### GOOD .bashrc ###
# Some other program adding to the PATH:
export PATH="$ANT_ROOT:$PATH"
# NVM initialisation
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
(This was with bash 4.2.46 on CentOS. It seems to me like a bug in bash, but I may be mistaken.)
Another option is set this value "tcp_keepalives_idle". Check more in documentation https://www.postgresql.org/docs/10/runtime-config-connection.html.
First, follow the instructions in this question to squash everything to a single commit. Then make a forced push to the remote:
$ git push origin +master
And optionally delete all other branches both locally and remotely:
$ git push origin :<branch>
$ git branch -d <branch>
The na.omit
function is what a lot of the regression routines use internally:
vec <- 1:1000
vec[runif(200, 1, 1000)] <- NA
max(vec)
#[1] NA
max( na.omit(vec) )
#[1] 1000
$("#btnAddProfile").html('Save').button('refresh');
My version:
while '' in all_lines:
all_lines.pop(all_lines.index(''))
EXCLUDE="foo bar blah jah"
DEST=$1
for i in *
do
for x in $EXCLUDE
do
if [ $x != $i ]; then
cp -a $i $DEST
fi
done
done
Untested...
Your Problem is because of getTime() . it always return following.
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
Because the max integer value is less then the return value by getTime()
that why is showing
wrong result.
You can try my function for merging images horizontally or vertically without changing image ratio. just copy paste will work.
function merge($filename_x, $filename_y, $filename_result, $mergeType = 0) {
//$mergeType 0 for horizandal merge 1 for vertical merge
// Get dimensions for specified images
list($width_x, $height_x) = getimagesize($filename_x);
list($width_y, $height_y) = getimagesize($filename_y);
$lowerFileName = strtolower($filename_x);
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
$image_x = imagecreatefromjpeg($filename_x);
}else if(substr_count($lowerFileName, '.png')>0){
$image_x = imagecreatefrompng($filename_x);
}else if(substr_count($lowerFileName, '.gif')>0){
$image_x = imagecreatefromgif($filename_x);
}
$lowerFileName = strtolower($filename_y);
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
$image_y = imagecreatefromjpeg($filename_y);
}else if(substr_count($lowerFileName, '.png')>0){
$image_y = imagecreatefrompng($filename_y);
}else if(substr_count($lowerFileName, '.gif')>0){
$image_y = imagecreatefromgif($filename_y);
}
if($mergeType==0){
//for horizandal merge
if($height_y<$height_x){
$new_height = $height_y;
$new_x_height = $new_height;
$precentageReduced = ($height_x - $new_height)/($height_x/100);
$new_x_width = ceil($width_x - (($width_x/100) * $precentageReduced));
$tmp = imagecreatetruecolor($new_x_width, $new_x_height);
imagecopyresampled($tmp, $image_x, 0, 0, 0, 0, $new_x_width, $new_x_height, $width_x, $height_x);
$image_x = $tmp;
$height_x = $new_x_height;
$width_x = $new_x_width;
}else{
$new_height = $height_x;
$new_y_height = $new_height;
$precentageReduced = ($height_y - $new_height)/($height_y/100);
$new_y_width = ceil($width_y - (($width_y/100) * $precentageReduced));
$tmp = imagecreatetruecolor($new_y_width, $new_y_height);
imagecopyresampled($tmp, $image_y, 0, 0, 0, 0, $new_y_width, $new_y_height, $width_y, $height_y);
$image_y = $tmp;
$height_y = $new_y_height;
$width_y = $new_y_width;
}
$new_width = $width_x + $width_y;
$image = imagecreatetruecolor($new_width, $new_height);
imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
imagecopy($image, $image_y, $width_x, 0, 0, 0, $width_y, $height_y);
}else{
//for verical merge
if($width_y<$width_x){
$new_width = $width_y;
$new_x_width = $new_width;
$precentageReduced = ($width_x - $new_width)/($width_x/100);
$new_x_height = ceil($height_x - (($height_x/100) * $precentageReduced));
$tmp = imagecreatetruecolor($new_x_width, $new_x_height);
imagecopyresampled($tmp, $image_x, 0, 0, 0, 0, $new_x_width, $new_x_height, $width_x, $height_x);
$image_x = $tmp;
$width_x = $new_x_width;
$height_x = $new_x_height;
}else{
$new_width = $width_x;
$new_y_width = $new_width;
$precentageReduced = ($width_y - $new_width)/($width_y/100);
$new_y_height = ceil($height_y - (($height_y/100) * $precentageReduced));
$tmp = imagecreatetruecolor($new_y_width, $new_y_height);
imagecopyresampled($tmp, $image_y, 0, 0, 0, 0, $new_y_width, $new_y_height, $width_y, $height_y);
$image_y = $tmp;
$width_y = $new_y_width;
$height_y = $new_y_height;
}
$new_height = $height_x + $height_y;
$image = imagecreatetruecolor($new_width, $new_height);
imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
imagecopy($image, $image_y, 0, $height_x, 0, 0, $width_y, $height_y);
}
$lowerFileName = strtolower($filename_result);
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
imagejpeg($image, $filename_result);
}else if(substr_count($lowerFileName, '.png')>0){
imagepng($image, $filename_result);
}else if(substr_count($lowerFileName, '.gif')>0){
imagegif($image, $filename_result);
}
// Clean up
imagedestroy($image);
imagedestroy($image_x);
imagedestroy($image_y);
}
merge('images/h_large.jpg', 'images/v_large.jpg', 'images/merged_har.jpg',0); //merge horizontally
merge('images/h_large.jpg', 'images/v_large.jpg', 'images/merged.jpg',1); //merge vertically
using System.Reflection;
{
string version = Assembly.GetEntryAssembly().GetName().Version.ToString();
}
Remarks from MSDN http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getentryassembly%28v=vs.110%29.aspx:
The GetEntryAssembly
method can return null
when a managed assembly has been loaded from an unmanaged application. For example, if an unmanaged application creates an instance of a COM component written in C#, a call to the GetEntryAssembly
method from the C# component returns null
, because the entry point for the process was unmanaged code rather than a managed assembly.
Luckily git stash pop
does not change the stash in the case of a conflict!
So nothing, to worry about, just clean up your code and try it again.
Say your codebase was clean before, you could go back to that state with: git checkout -f
Then do the stuff you forgot, e.g. git merge missing-branch
After that just fire git stash pop
again and you get the same stash, that conflicted before.
Keep in mind: The stash is safe, however, uncommitted changes in the working directory are of course not. They can get messed up.
Like Mike Samuel said, don't use jQuery.html().text() to decode html entities as it's unsafe.
Instead, use a template renderer like Mustache.js or decodeEntities from @VyvIT's comment.
Underscore.js utility-belt library comes with escape
and unescape
methods, but they are not safe for user input:
If it is going to be a web based application, you can also use the ServletContextListener interface.
public class SLF4JBridgeListener implements ServletContextListener {
@Autowired
ThreadPoolTaskExecutor executor;
@Autowired
ThreadPoolTaskScheduler scheduler;
@Override
public void contextInitialized(ServletContextEvent sce) {
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
scheduler.shutdown();
executor.shutdown();
}
}
Any component added to the GridLayout will be resized to the same size as the largest component added. If you want a component to remain at its preferred size, then wrap that component in a JPanel and then the panel will be resized:
JPanel displayPanel = new JPanel(new GridLayout(4, 2));
JTextField titleText = new JTextField("title");
JPanel wrapper = new JPanel( new FlowLayout(0, 0, FlowLayout.LEADING) );
wrapper.add( titleText );
displayPanel.add(wrapper);
//displayPanel.add(titleText);
Use the --prefix
or -p
option to specify where to write the environment files. For example:
conda create --prefix /tmp/test-env python=2.7
Will create the environment named /tmp/test-env
which resides in /tmp/
instead of the default .conda
.
Try this
val intent = Intent(this, Page2::class.java)
startActivity(intent)
Theta Join:
When you make a query for join using any operator,(e.g., =, <, >, >= etc.), then that join query comes under Theta join.
Equi Join:
When you make a query for join using equality operator only, then that join query comes under Equi join.
Example:
> SELECT * FROM Emp JOIN Dept ON Emp.DeptID = Dept.DeptID; > SELECT * FROM Emp INNER JOIN Dept USING(DeptID)
This will show: _________________________________________________ | Emp.Name | Emp.DeptID | Dept.Name | Dept.DeptID | | | | | |
Note: Equi join is also a theta join!
Natural Join:
a type of Equi Join which occurs implicitly by comparing all the same names columns in both tables.
Note: here, the join result has only one column for each pair of same named columns.
Example
SELECT * FROM Emp NATURAL JOIN Dept
This will show: _______________________________ | DeptID | Emp.Name | Dept.Name | | | | |
You can create extension method like:
public static IEnumerable<TResult> LeftOuterJoin<TSource, TInner, TKey, TResult>(this IEnumerable<TSource> source, IEnumerable<TInner> other, Func<TSource, TKey> func, Func<TInner, TKey> innerkey, Func<TSource, TInner, TResult> res)
{
return from f in source
join b in other on func.Invoke(f) equals innerkey.Invoke(b) into g
from result in g.DefaultIfEmpty()
select res.Invoke(f, result);
}
As far as I know, the default value is only inserted when you don't specify a value in the insert statement. So, for example, you'd need to do something like the following in a table with three fields (value2 being defaulted)
INSERT INTO t (value1, value3) VALUES ('value1', 'value3')
And then value2 would be defaulted. Maybe someone will chime in on how to accomplish this for a table with a single field.
I try to write working code example, I test it and everything works.
Hare is code:
HTML:
<input type="file" class="attachment_input" name="file" onchange="checkFileSize(this, @Model.MaxSize.ToString(),@Html.Raw(Json.Encode(Model.FileExtensionsList)))" />
Javascript:
//function for check attachment size and extention match
function checkFileSize(element, maxSize, extentionsArray) {
var val = $(element).val(); //get file value
var ext = val.substring(val.lastIndexOf('.') + 1).toLowerCase(); // get file extention
if ($.inArray(ext, extentionsArray) == -1) {
alert('false extension!');
}
var fileSize = ($(element)[0].files[0].size / 1024 / 1024); //size in MB
if (fileSize > maxSize) {
alert("Large file");// if Maxsize from Model > real file size alert this
}
}
The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:
var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
The code above depends on the nuget package RestSharp, which you can easily install.
Here's some simple code that prints all the C(n,m) combinations. It works by initializing and moving a set of array indices that point to next valid combination. The indices are initialized to point to the lowest m indices (lexicographically the smallest combination). Then on, starting with the m-th index, we try to move the indices forward. if an index has reached its limit, we try the previous index (all the way down to index 1). If we can move an index forward, then we reset all greater indices.
m=(rand()%n)+1; // m will vary from 1 to n
for (i=0;i<n;i++) a[i]=i+1;
// we want to print all possible C(n,m) combinations of selecting m objects out of n
printf("Printing C(%d,%d) possible combinations ...\n", n,m);
// This is an adhoc algo that keeps m pointers to the next valid combination
for (i=0;i<m;i++) p[i]=i; // the p[.] contain indices to the a vector whose elements constitute next combination
done=false;
while (!done)
{
// print combination
for (i=0;i<m;i++) printf("%2d ", a[p[i]]);
printf("\n");
// update combination
// method: start with p[m-1]. try to increment it. if it is already at the end, then try moving p[m-2] ahead.
// if this is possible, then reset p[m-1] to 1 more than (the new) p[m-2].
// if p[m-2] can not also be moved, then try p[m-3]. move that ahead. then reset p[m-2] and p[m-1].
// repeat all the way down to p[0]. if p[0] can not also be moved, then we have generated all combinations.
j=m-1;
i=1;
move_found=false;
while ((j>=0) && !move_found)
{
if (p[j]<(n-i))
{
move_found=true;
p[j]++; // point p[j] to next index
for (k=j+1;k<m;k++)
{
p[k]=p[j]+(k-j);
}
}
else
{
j--;
i++;
}
}
if (!move_found) done=true;
}
const result = sortingArr.map((i) => {
const pos = itemsArray.findIndex(j => j[1] === i);
const item = itemsArray[pos];
itemsArray.splice(pos, 1);
return item;
});
Pros: Host on Google has benefits
Cons:
I wonder if you can INCLUDE from Google, and then check the presence of some Global variable, or somesuch, and if absence load from your server?
Try:
ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 tar xvfz
Then Try:
ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 rm
This will untar all .tar.gz files in the current directory and then delete all the .tar.gz files. If you want an explanation, the "|" takes the stdout of the command before it, and uses that as the stdin of the command after it. Use "man command" w/o the quotes to figure out what those commands and arguments do. Or, you can research online.
function isMobileNumber(evt, sender) { // Allows only 10 numbers // ONKEYPRESS FUNCTION
//evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
var NumValue = $(sender).val();
if (charCode > 31 && (charCode < 48 || charCode > 57)) {//|| NumValue.length > 9) {
return false;
}
return true;}
function isProperMobileNumber(txtMobId) { //// VALIDATOR FUNCTION
var txtMobile = document.getElementById(txtMobId);
if (!isNumeric(txtMobile.value)) { $(txtMobile).css("border-color", "red"); return false; }
if (txtMobile.value.length < 10) {
$(txtMobile).css("border-color", "red");
return false;
}
$(txtMobile).css("border-color", "")
return true; }
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n) }
I needed to do a similar operation for a Stream
, but couldn't find a good example. Here's what I came up with.
public static <T> boolean areUnique(final Stream<T> stream) {
final Set<T> seen = new HashSet<>();
return stream.allMatch(seen::add);
}
This has the advantage of short-circuiting when duplicates are found early rather than having to process the whole stream and isn't much more complicated than just putting everything in a Set
and checking the size. So this case would roughly be:
List<T> list = ...
boolean allDistinct = areUnique(list.stream());
I had some trouble with nested classes from any depth so I figured this out. It will select only the first level it encounters of a containing Jquery Object:
var $elementsAll = $("#container").find(".fooClass");4_x000D_
_x000D_
var $levelOneElements = $elementsAll.not($elementsAll.children().find($elementsAll));_x000D_
_x000D_
$levelOneElements.css({"color":"red"})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div class="fooClass" style="color:black">_x000D_
Container_x000D_
<div id="container">_x000D_
<div class="fooClass" style="color:black">_x000D_
Level One_x000D_
<div>_x000D_
<div class="fooClass" style="color:black">_x000D_
Level Two_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="fooClass" style="color:black">_x000D_
Level One_x000D_
<div>_x000D_
<div class="fooClass" style="color:black">_x000D_
Level Two_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Check if your firewall didn't add a rule and blocked the connection to adb server. It uses newdev.dll and your network. It just happened here, I removed the blocking rule from the firewall, and now it is fine.
You can use jQuery UI Dialog.
These libraries create HTML elements that look and behave like a dialog box, allowing you to put anything you want (including form elements or video) in the dialog.
Starting with .NET 4.0 you can use ExpressionVisitor
to find properties:
class ExprVisitor : ExpressionVisitor {
public bool IsFound { get; private set; }
public string MemberName { get; private set; }
public Type MemberType { get; private set; }
protected override Expression VisitMember(MemberExpression node) {
if (!IsFound && node.Member.MemberType == MemberTypes.Property) {
IsFound = true;
MemberName = node.Member.Name;
MemberType = node.Type;
}
return base.VisitMember(node);
}
}
Here is how you use this visitor:
var visitor = new ExprVisitor();
visitor.Visit(expr);
if (visitor.IsFound) {
Console.WriteLine("First property in the expression tree: Name={0}, Type={1}", visitor.MemberName, visitor.MemberType.FullName);
} else {
Console.WriteLine("No properties found.");
}
I am using Guava which has annotation included:
(Gradle code )
compile 'com.google.guava:guava:23.4-jre'
Hmmm hi to the 10 years old party ?
Why not put some condition in your for ?
var condition = true
for (var i = 0 ; i < Args.length && condition ; i++) {
for (var j = 0 ; j < Args[i].length && condition ; j++) {
if (Args[i].obj[j] == "[condition]") {
condition = false
}
}
}
Like this you stop when you want
In my case, using Typescript, we can use some() which go through the array and stop when condition is met So my code become like this :
Args.some((listObj) => {
return listObj.some((obj) => {
return !(obj == "[condition]")
})
})
Like this, the loop stopped right after the condition is met
Reminder : This code run in TypeScript
Linux
To impress your friends
ps aux | grep -i node | awk '{print $2}' | xargs kill -9
But this is the one you will remember
killall node
function cleanup_func {
sleep 0.5
echo cleanup
}
trap "exit \$exit_code" INT TERM
trap "exit_code=\$?; cleanup_func; kill 0" EXIT
# exit 1
# exit 0
Like https://stackoverflow.com/a/22644006/10082476, but with added exit-code
I'm not sure what happened in your case that fixed the issue, but your issue was on this line:
Caused by: java.lang.NoClassDefFoundError: javax/xml/rpc/handler/soap/SOAPMessageContext
You need to add jaxrpc-api.jar
to your /lib
s or add
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxrpc-api</artifactId>
<version>x.x.x</version>
</dependency>
to your maven dependencies.
You can use like bellow:
(( var0 = var1<98?9:21 ))
the same as
if [ "$var1" -lt 98 ]; then
var0=9
else
var0=21
fi
extends
condition?result-if-true:result-if-false
I found the interested thing on the book "Advanced Bash-Scripting Guide"
Edit /etc/sudoers
file either manually or using the visudo application.
Remember: System reads /etc/sudoers
file from top to the bottom, so you could overwrite a particular setting by putting the next one below.
So to be on the safe side - define your access setting at the bottom.
You can keep your work stashed away, without commiting it, with git stash
. You
would than use git stash pop
to get it back. Or you can (as carleeto said) git commit
it to a separate branch.
You can checkout a commit by a specific date using rev-parse
like this:
git checkout 'master@{1979-02-26 18:30:00}'
More details on the available options can be found in the git-rev-parse
.
As noted in the comments this method uses the reflog to find the commit in your history. By default these entries expire after 90 days. Although the syntax for using the reflog is less verbose you can only go back 90 days.
The other option, which doesn't use the reflog, is to use rev-list
to get the commit at a particular point in time with:
git checkout `git rev-list -n 1 --first-parent --before="2009-07-27 13:37" master`
Note the --first-parent if you want only your history and not versions brought in by a merge. That's what you usually want.
//this will work for user in time zone MST with 7 off set or UTC with saving time
//I have tried all the above and they fail the only solution is to use some math
//the trick is to rely on $newdate is time() //strtotime is corrupt it tries to read to many minds
//convert to time to use with javascript*1000
$dnol = strtotime('today')*1000;
$dn = ($newdate*1000)-86400000;
$dz=$dn/86400000; //divide into days
$dz=floor($dz); //filter off excess time
$dzt=$dz*86400000; // put back into days UTC
$jsDate=$dzt*1+(7*3600000); // 7 is the off set you can store the 7 in database
$dzt=$dzt-3600000; //adjusment for summerTime UTC additional table for these dates will drive you crazy
//solution get users [time off sets] with browser, up date to data base for user with ajax when they ain't lookin
<?php
$t=time();
echo($t . "<br>");
echo(date("Y-m-d",$t));
echo '<BR>'.$dnol;
echo '<BR>'.$dzt.'<BR>';
echo(date("Y-m-d",$dzt/1000)); //convert back for php /1000
echo '<BR>';
echo(date('Y-m-d h:i:s',$dzt/1000));
?>
Following is my TypeScript code which can be converted easily into JavaScript and you can use
/**
* Convert BASE64 to BLOB
* @param base64Image Pass Base64 image data to convert into the BLOB
*/
private convertBase64ToBlob(base64Image: string) {
// Split into two parts
const parts = base64Image.split(';base64,');
// Hold the content type
const imageType = parts[0].split(':')[1];
// Decode Base64 string
const decodedData = window.atob(parts[1]);
// Create UNIT8ARRAY of size same as row data length
const uInt8Array = new Uint8Array(decodedData.length);
// Insert all character code into uInt8Array
for (let i = 0; i < decodedData.length; ++i) {
uInt8Array[i] = decodedData.charCodeAt(i);
}
// Return BLOB image after conversion
return new Blob([uInt8Array], { type: imageType });
}
They are normal symbols as 'a' or '?' or any other. Just (invisible) entries in a string. \r moves cursor to the beginning of the line. \n goes one line down.
As for your replacement, you haven't specified what language you're using, so here's the sketch:
someString.replace("\r\n", "\n").replace("\r", "\n")
You will try this
<?php $url = wp_get_attachment_url(get_post_thumbnail_id($post->ID), 'full'); ?> // Here you can manage your image size like medium, thumbnail, or custom size
<img src="<?php echo $url ?>"
/>
If you are OK to run Java command line then you can do it with Apache POI HSSF's Excel Extractor. It has a main
method that says to be the command line extractor. This one seems to just dump everything out. They point out to this example that converts to CSV. You would have to compile it before you can run it but it too has a main
method so you should not have to do much coding per se to make it work.
Another option that might fly but will require some work on the other end is to make your Excel files come to you as Excel XML Data or XML Spreadsheet of whatever MS calls that format these days. It will open a whole new world of opportunities for you to slice and dice it the way you want.
General benefits of functional programming over imperative languages:
You can formulate many problems much easier, closer to their definition and more concise in a functional programming language like F# and your code is less error-prone (immutability, more powerful type system, intuitive recurive algorithms). You can code what you mean instead of what the computer wants you to say ;-) You will find many discussions like this when you google it or even search for it at SO.
Special F#-advantages:
Asynchronous programming is extremely easy and intuitive with async {}
-expressions - Even with ParallelFX, the corresponding C#-code is much bigger
Very easy integration of compiler compilers and domain-specific languages
Extending the language as you need it: LOP
More flexible syntax
Often shorter and more elegant solutions
Take a look at this document
The advantages of C# are that it's often more accurate to "imperative"-applications (User-interface, imperative algorithms) than a functional programming language, that the .NET-Framework it uses is designed imperatively and that it's more widespread.
Furthermore you can have F# and C# together in one solution, so you can combine the benefits of both languages and use them where they're needed.
You should use the setString()
method to set the userID
. This both ensures that the statement is formatted properly, and prevents SQL injection
:
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
There is a nice tutorial on how to use PreparedStatement
s properly in the Java Tutorials.
In Android Studio 4.0.1, Help -> About shows the details of the Java version used by the studio, in my case:
Android Studio 4.0.1
Build #AI-193.6911.18.40.6626763, built on June 25, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 1237M
Cores: 8
Registry: ide.new.welcome.screen.force=true
Non-Bundled Plugins: com.google.services.firebase
I think my answer to my own question here is the simplest solution to what you are trying to do:
Select the cell where the first line of text from the file should be.
Use the Data
/Get External Data
/From File
dialog to select the text file to import.
Format the imported text as required.
In the Import Data
dialog that opens, click on Properties...
Uncheck the Prompt for file name on refresh
box.
Whenever the external file changes, click the Data
/Get External Data
/Refresh All
button.
Note: in your case, you should probably want to skip step #5.
Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?
By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...
-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications
If you are running you should be able to access any of those system properties to see if they have been set:
if (System.getProperty("com.sun.management.jmxremote") == null) {
System.out.println("JMX remote is disabled");
} else [
String portString = System.getProperty("com.sun.management.jmxremote.port");
if (portString != null) {
System.out.println("JMX running on port "
+ Integer.parseInt(portString));
}
}
Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts
or if it is set to an incorrect interface address then you can override it with the following:
-Djava.rmi.server.hostname=<IP address>
As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port
is actually the RMI port. This tells the client what port the JMX server is running on.
Checking the documentation shows that its returns false
on an error. So use the return status rather than or die()
. It will return false if it fails, which you can log (or whatever you want to do) and then continue.
$rv = mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'");
if ( $rv === false ){
//handle the error here
}
//page continues loading
You can use Github for Unity, a Unity Extension that brings the git workflow into the UI of Unity.
Github for Unity just released version 1.0 of the extension.
Perhaps the most beginner-friendly way to compile a JAR from your Java code is to use an IDE (integrated development environment; essentially just user-friendly software for development) like Netbeans or Eclipse.
You can always do this all very easily with the command line. Make sure that you are in the same directory as the files targeted before executing a command such as this:
javac YourApp.java
jar -cf YourJar.jar YourApp.class
...changing "YourApp" and "YourJar" to the proper names of your files, respectively.
The Substr function allows you to use a minus to get the last character.
var string = "hello";
var last = string.substr(-1);
It's very flexible. For example:
// Get 2 characters, 1 character from end
// The first part says how many characters
// to go back and the second says how many
// to go forward. If you don't say how many
// to go forward it will include everything
var string = "hello!";
var lasttwo = string.substr(-3,2);
// = "lo"
This error is because your server doesn't have a valid SSL certificate. Hence we need to tell the client to use a different TrustManager. Here is a sample code:
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
client = new DefaultHttpClient(ccm, base.getParams());
How about a regex?
function getNum(str) {
return /[-+]?[0-9]*\.?[0-9]+/.test(str)?parseFloat(str):0;
}
The code below will ignore NaN to allow a calculation of properly entered numbers
function getNum(str) {_x000D_
return /[-+]?[0-9]*\.?[0-9]+/.test(str)?parseFloat(str):0;_x000D_
}_x000D_
var inputsArray = document.getElementsByTagName('input');_x000D_
_x000D_
function computeTotal() {_x000D_
var tot = 0;_x000D_
tot += getNum(inputsArray[0].value);_x000D_
tot += getNum(inputsArray[1].value);_x000D_
tot += getNum(inputsArray[2].value);_x000D_
inputsArray[3].value = tot;_x000D_
}
_x000D_
<input type="text"></input>_x000D_
<input type="text"></input>_x000D_
<input type="text"></input>_x000D_
<input type="text" disabled></input>_x000D_
<button type="button" onclick="computeTotal()">Calculate</button>
_x000D_
You can execute sql queries directly as follows :
private int DeleteData()
{
using (var ctx = new MyEntities(this.ConnectionString))
{
if (ctx != null)
{
//Delete command
return ctx.ExecuteStoreCommand("DELETE FROM ALARM WHERE AlarmID > 100");
}
}
return 0;
}
For select we may use
using (var context = new MyContext())
{
var blogs = context.MyTable.SqlQuery("SELECT * FROM dbo.MyTable").ToList();
}
Flow allows interface specification, without having to convert your whole code base to TypeScript.
Interfaces are a way of breaking dependencies, while stepping cautiously within existing code.
Use WinSCP for file transfer over SSH, putty is only for SSH commands.
In my application I ended up with two different elements having the same id (bad). One element was a div and the other an input. I was trying to sum up my inputs and took me a while to realise the duplicate ids. By placing the type of the element I wanted in front of #, I was able to grab the value of the input element and discard the div:
$("input#_myelementid").val();
I hope it helps.
On browsers that support the ECMAScript® 2016 Internationalization API Specification (ECMA-402), you can use an Intl.NumberFormat
instance:
var nf = Intl.NumberFormat();
var x = 42000000;
console.log(nf.format(x)); // 42,000,000 in many locales
// 42.000.000 in many other locales
if (typeof Intl === "undefined" || !Intl.NumberFormat) {_x000D_
console.log("This browser doesn't support Intl.NumberFormat");_x000D_
} else {_x000D_
var nf = Intl.NumberFormat();_x000D_
var x = 42000000;_x000D_
console.log(nf.format(x)); // 42,000,000 in many locales_x000D_
// 42.000.000 in many other locales_x000D_
}
_x000D_
outside device,we can use :
adb install file.apk
or adb install -r file.apk
adb install [-l] [-r] [-s] [--algo <algorithm name> --key <hex-encoded key> --iv <hex-encoded iv>] <file>
- push this package file to the device and install it
('-l' means forward-lock the app)
('-r' means reinstall the app, keeping its data)
('-s' means install on SD card instead of internal storage)
('--algo', '--key', and '--iv' mean the file is encrypted already)
inside devices also, we can use:
pm install file.apk
or pm install -r file.apk
pm install: installs a package to the system. Options:
-l: install the package with FORWARD_LOCK.
-r: reinstall an exisiting app, keeping its data.
-t: allow test .apks to be installed.
-i: specify the installer package name.
-s: install package on sdcard.
-f: install package on internal flash.
-d: allow version code downgrade.
For more then one apk file on Linux we can use xargs
and on windows we can use for loop
.
Linux / Unix sample :
ls -1 *.apk | xargs -I xxx adb install -r xxx
All hover is doing behind the scenes is binding to the mouseover and mouseout property. I would bind and unbind your functions from those events individually.
For example, say you have the following html:
<a href="#" class="myLink">Link</a>
then your jQuery would be:
$(document).ready(function() {
function mouseOver()
{
$(this).css('color', 'red');
}
function mouseOut()
{
$(this).css('color', 'blue');
}
// either of these might work
$('.myLink').hover(mouseOver, mouseOut);
$('.myLink').mouseover(mouseOver).mouseout(mouseOut);
// otherwise use this
$('.myLink').bind('mouseover', mouseOver).bind('mouseout', mouseOut);
// then to unbind
$('.myLink').click(function(e) {
e.preventDefault();
$('.myLink').unbind('mouseover', mouseOver).unbind('mouseout', mouseOut);
});
});
Use integers instead of strings.
make sure to cast your string to ints
price = int('1') * 9
The actual example code you posted will return 9
not 111111111
Finally I get the solution for my problem. The asp.net account not appear in the IIS manager because I didn't check its check Box in IIS to do this in windows 7 follow the steps
Now you will see the Asp.net account on the IIS manager and by default you see IIS account Now you should move you asp.net website from “my document” to another place the IIS have permission to access it (to any partition on your computer) Now browse your website from IIS manager and it should work.
In Python 2.x this is not guaranteed as it is possible for True
and False
to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons.
In Python 3.x True
and False
are keywords and will always be equal to 1
and 0
.
Under normal circumstances in Python 2, and always in Python 3:
False
object is of type bool
which is a subclass of int
:
object
|
int
|
bool
It is the only reason why in your example, ['zero', 'one'][False]
does work. It would not work with an object which is not a subclass of integer, because list indexing only works with integers, or objects that define a __index__
method (thanks mark-dickinson).
Edit:
It is true of the current python version, and of that of Python 3. The docs for python 2 and the docs for Python 3 both say:
There are two types of integers: [...] Integers (int) [...] Booleans (bool)
and in the boolean subsection:
Booleans: These represent the truth values False and True [...] Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.
There is also, for Python 2:
In numeric contexts (for example when used as the argument to an arithmetic operator), they [False and True] behave like the integers 0 and 1, respectively.
So booleans are explicitly considered as integers in Python 2 and 3.
So you're safe until Python 4 comes along. ;-)
If you are using Reactive Forms you can use this:
<button [disabled]="!contactForm.valid" type="submit" class="btn btn-lg btn primary" (click)="printSomething()">Submit</button>
Step 1: check your default authentication plugin
SHOW VARIABLES LIKE 'default_authentication_plugin';
Step 2: veryfing your password validation requirements
SHOW VARIABLES LIKE 'validate_password%';
Step 3: setting up your user with correct password requirements
CREATE USER '<your_user>'@'localhost' IDENTIFIED WITH '<your_default_auth_plugin>' BY 'password';
$("#cform")[0].reset();
or in plain javascript:
document.getElementById("cform").reset();
Try this working for Firefox:
driver.manage().window.maximize();
I am running Ubuntu 16.04 (Xenial Xerus). This is what worked for me:
/etc/apache2/sites-available
. There
you will find a file called 000-default.conf
.cp 000-default.conf example.local.conf
<VirtualHost *:80>
to <VirtualHost example.local:80>
ServerName example.local
And if you need to, add this line: ServerAlias www.example.local
service Apache2 restart
Open a browser and navigate to example.local
. You should see your website.
You can do
jQuery.fn.reverse = function() {
return this.pushStack(this.get().reverse(), arguments);
};
followed by
$(selector).reverse().each(...)
It's difficult to answer this question with the information given. Nothing looks particularly wrong with how you are using HashSet.
Well, I'll hazard a guess that it's not a compilation issue and, when you say "getting errors," you mean "not getting the behavior [you] want."
I'll also go out on a limb and suggest that maybe your Block's equals an hashCode methods are not properly overridden.
Using like might take longer time so use full_text_search:
SELECT * FROM items WHERE MATCH(items.xml) AGAINST ('your_search_word')
Underscore-java library has static method U.formatXml(xmlstring). I am the maintainer of the project. Live example
import com.github.underscore.lodash.U;
import com.github.underscore.lodash.Xml;
public class MyClass {
public static void main(String[] args) {
System.out.println(U.formatXml("<a>\n <b></b>\n <b></b>\n</a>",
Xml.XmlStringBuilder.Step.COMPACT));
}
}
// output: <a><b></b><b></b></a>
Fun fact!
The 'modulus' operation is defined as:
a % n ==> a - (a/n) * n
So you could roll your own, although it will be FAR slower than the built in % operator:
public static int Mod(int a, int n)
{
return a - (int)((double)a / n) * n;
}
Edit: wow, misspoke rather badly here originally, thanks @joren for catching me
Now here I'm relying on the fact that division + cast-to-int in C# is equivalent to Math.Floor
(i.e., it drops the fraction), but a "true" implementation would instead be something like:
public static int Mod(int a, int n)
{
return a - (int)Math.Floor((double)a / n) * n;
}
In fact, you can see the differences between % and "true modulus" with the following:
var modTest =
from a in Enumerable.Range(-3, 6)
from b in Enumerable.Range(-3, 6)
where b != 0
let op = (a % b)
let mod = Mod(a,b)
let areSame = op == mod
select new
{
A = a,
B = b,
Operator = op,
Mod = mod,
Same = areSame
};
Console.WriteLine("A B A%B Mod(A,B) Equal?");
Console.WriteLine("-----------------------------------");
foreach (var result in modTest)
{
Console.WriteLine(
"{0,-3} | {1,-3} | {2,-5} | {3,-10} | {4,-6}",
result.A,
result.B,
result.Operator,
result.Mod,
result.Same);
}
Results:
A B A%B Mod(A,B) Equal?
-----------------------------------
-3 | -3 | 0 | 0 | True
-3 | -2 | -1 | -1 | True
-3 | -1 | 0 | 0 | True
-3 | 1 | 0 | 0 | True
-3 | 2 | -1 | 1 | False
-2 | -3 | -2 | -2 | True
-2 | -2 | 0 | 0 | True
-2 | -1 | 0 | 0 | True
-2 | 1 | 0 | 0 | True
-2 | 2 | 0 | 0 | True
-1 | -3 | -1 | -1 | True
-1 | -2 | -1 | -1 | True
-1 | -1 | 0 | 0 | True
-1 | 1 | 0 | 0 | True
-1 | 2 | -1 | 1 | False
0 | -3 | 0 | 0 | True
0 | -2 | 0 | 0 | True
0 | -1 | 0 | 0 | True
0 | 1 | 0 | 0 | True
0 | 2 | 0 | 0 | True
1 | -3 | 1 | -2 | False
1 | -2 | 1 | -1 | False
1 | -1 | 0 | 0 | True
1 | 1 | 0 | 0 | True
1 | 2 | 1 | 1 | True
2 | -3 | 2 | -1 | False
2 | -2 | 0 | 0 | True
2 | -1 | 0 | 0 | True
2 | 1 | 0 | 0 | True
2 | 2 | 0 | 0 | True
As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.
ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)
As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().
The below code will return username group membership using the samaccountname. You can modify it to get input from a file or change the query to get accounts with non expiring passwords etc
$location = "c:\temp\Peace2.txt"
$users = (get-aduser -filter *).samaccountname
$le = $users.length
for($i = 0; $i -lt $le; $i++){
$output = (get-aduser $users[$i] | Get-ADPrincipalGroupMembership).name
$users[$i] + " " + $output
$z = $users[$i] + " " + $output
add-content $location $z
}
Sample Output:
Administrator Domain Users Administrators Schema Admins Enterprise Admins Domain Admins Group Policy Creator Owners Guest Domain Guests Guests krbtgt Domain Users Denied RODC Password Replication Group Redacted Domain Users CompanyUsers Production Redacted Domain Users CompanyUsers Production Redacted Domain Users CompanyUsers Production
You can also delete cookies without using jquery.cookie plugin:
document.cookie = 'NAMEOFYOURCOOKIE' + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
for me @"^[\w ]+$" is working, allow number, alphabet and space, but need to type at least one letter or number.
Binding RelativeSource={
RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemType}
}
...
The default attribute of RelativeSource
is the Mode
property. A complete set of valid values is given here (from MSDN):
PreviousData Allows you to bind the previous data item (not that control that contains the data item) in the list of data items being displayed.
TemplatedParent Refers to the element to which the template (in which the data-bound element exists) is applied. This is similar to setting a TemplateBindingExtension and is only applicable if the Binding is within a template.
Self Refers to the element on which you are setting the binding and allows you to bind one property of that element to another property on the same element.
FindAncestor Refers to the ancestor in the parent chain of the data-bound element. You can use this to bind to an ancestor of a specific type or its subclasses. This is the mode you use if you want to specify AncestorType and/or AncestorLevel.
I had a similar issue to this and clearing Temporary ASP.NET Files fixed it. Hope this helps someone.
Add a @JsonProperty
annotated getter, which returns a String
, for the favoriteNumber
field:
public class Person {
public String name;
public int age;
private int favoriteNumber;
public Person(String name, int age, int favoriteNumber) {
this.name = name;
this.age = age;
this.favoriteNumber = favoriteNumber;
}
@JsonProperty
public String getFavoriteNumber() {
return String.valueOf(favoriteNumber);
}
public static void main(String... args) throws Exception {
Person p = new Person("Joe", 25, 123);
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(p));
// {"name":"Joe","age":25,"favoriteNumber":"123"}
}
}
You have updated the android sdk but not updated the adt to match with it.
You can update the adt from here
You might need to update the software source for your adt update
Go to eclipse > help > Check for updates.
It should list the latest update of adt. If it is not working try the same *Go to eclipse > help > Install new software * but now please do the follwing:
Click on add
Add this url : https://dl-ssl.google.com/android/eclipse/
Give it any name.
It will list the updates available- which should ideally be adt 20.xx
Eclipse will restart and hopefully everything should work fine for you.
actually the STL can do this without much code, I advise you learn a bit about the STL because it lets you do some fancy things, anyways this is what I use.
std::string GetFileExtension(const std::string& FileName)
{
if(FileName.find_last_of(".") != std::string::npos)
return FileName.substr(FileName.find_last_of(".")+1);
return "";
}
this solution will always return the extension even on strings like "this.a.b.c.d.e.s.mp3" if it cannot find the extension it will return "".
Getting overly clever with obscure-er HTTP error codes is a bad idea. Browsers sometimes react in unhelpful ways that obfuscate the situation. Stick with 404.
Sometimes, I try to use anonymous function to achieve defining and assigning happen at the same line. like below:
a, b = 4, 8
c := func() int {
if a >b {
return a
}
return b
} ()
Python sequence slice addresses can be written as a[start:end:step] and any of start, stop or end can be dropped. a[::3]
is every third element of the sequence.
Do something like this:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
First, create a folder named “menu” in the “res” folder.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/search"
android:icon="@android:drawable/ic_menu_search"
android:title="Search"/>
<item
android:id="@+id/add"
android:icon="@android:drawable/ic_menu_add"
android:title="Add"/>
<item
android:id="@+id/edit"
android:icon="@android:drawable/ic_menu_edit"
android:title="Edit">
<menu>
<item
android:id="@+id/share"
android:icon="@android:drawable/ic_menu_share"
android:title="Share"/>
</menu>
</item>
</menu>
Then, create your Activity Class:
public class PopupMenu1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_menu_1);
}
public void onPopupButtonClick(View button) {
PopupMenu popup = new PopupMenu(this, button);
popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(PopupMenu1.this,
"Clicked popup menu item " + item.getTitle(),
Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
}
Followed this.
I have solved it with adding some key in info.plist. The steps I followed are:
Opened my Projects info.plist
file
Added a Key called NSAppTransportSecurity
as a Dictionary
.
NSAllowsArbitraryLoads
as Boolean
and set its value to YES
as like following image.
Clean the Project and Now Everything is Running fine as like before.
Ref Link.
HashSet
is O(1) to access elements, so it certainly does matter. But maintaining order of the objects in the set isn't possible.
TreeSet
is useful if maintaining an order(In terms of values and not the insertion order) matters to you. But, as you've noted, you're trading order for slower time to access an element: O(log n) for basic operations.
From the javadocs for TreeSet
:
This implementation provides guaranteed log(n) time cost for the basic operations (
add
,remove
andcontains
).
Try it
Thread.currentThread().getStackTrace()[1].getClassName()
Or
Thread.currentThread().getStackTrace()[2].getClassName()
All the content and examples here are from
Operating Systems: Internals and Design Principles
William Stallings
8º Edition
Deadlock: A situation in which two or more processes are unable to proceed because each is waiting for one the others to do something.
For example, consider two processes, P1 and P2, and two resources, R1 and R2. Suppose that each process needs access to both resources to perform part of its function. Then it is possible to have the following situation: the OS assigns R1 to P2, and R2 to P1. Each process is waiting for one of the two resources. Neither will release the resource that it already owns until it has acquired the other resource and performed the function requiring both resources. The two processes are deadlocked
Livelock: A situation in which two or more processes continuously change their states in response to changes in the other process(es) without doing any useful work:
Starvation: A situation in which a runnable process is overlooked indefinitely by the scheduler; although it is able to proceed, it is never chosen.
Suppose that three processes (P1, P2, P3) each require periodic access to resource R. Consider the situation in which P1 is in possession of the resource, and both P2 and P3 are delayed, waiting for that resource. When P1 exits its critical section, either P2 or P3 should be allowed access to R. Assume that the OS grants access to P3 and that P1 again requires access before P3 completes its critical section. If the OS grants access to P1 after P3 has finished, and subsequently alternately grants access to P1 and P3, then P2 may indefinitely be denied access to the resource, even though there is no deadlock situation.
APPENDIX A - TOPICS IN CONCURRENCY
Deadlock Example
If both processes set their flags to true before either has executed the while statement, then each will think that the other has entered its critical section, causing deadlock.
/* PROCESS 0 */
flag[0] = true; // <- get lock 0
while (flag[1]) // <- is lock 1 free?
/* do nothing */; // <- no? so I wait 1 second, for example
// and test again.
// on more sophisticated setups we can ask
// to be woken when lock 1 is freed
/* critical section*/; // <- do what we need (this will never happen)
flag[0] = false; // <- releasing our lock
/* PROCESS 1 */
flag[1] = true;
while (flag[0])
/* do nothing */;
/* critical section*/;
flag[1] = false;
Livelock Example
/* PROCESS 0 */
flag[0] = true; // <- get lock 0
while (flag[1]){
flag[0] = false; // <- instead of sleeping, we do useless work
// needed by the lock mechanism
/*delay */; // <- wait for a second
flag[0] = true; // <- and restart useless work again.
}
/*critical section*/; // <- do what we need (this will never happen)
flag[0] = false;
/* PROCESS 1 */
flag[1] = true;
while (flag[0]) {
flag[1] = false;
/*delay */;
flag[1] = true;
}
/* critical section*/;
flag[1] = false;
[...] consider the following sequence of events:
This sequence could be extended indefinitely, and neither process could enter its critical section. Strictly speaking, this is not deadlock, because any alteration in the relative speed of the two processes will break this cycle and allow one to enter the critical section. This condition is referred to as livelock. Recall that deadlock occurs when a set of processes wishes to enter their critical sections but no process can succeed. With livelock, there are possible sequences of executions that succeed, but it is also possible to describe one or more execution sequences in which no process ever enters its critical section.
Not content from the book anymore.
And what about spinlocks?
Spinlock is a technique to avoid the cost of the OS lock mechanism. Typically you would do:
try
{
lock = beginLock();
doSomething();
}
finally
{
endLock();
}
A problem start to appear when beginLock()
costs much more than doSomething()
. In very exagerated terms, imagine what happens when the beginLock
costs 1 second, but doSomething
cost just 1 millisecond.
In this case if you waited 1 millisecond, you would avoid being hindered for 1 second.
Why the beginLock
would cost so much? If the lock is free is does not cost a lot (see https://stackoverflow.com/a/49712993/5397116), but if the lock is not free the OS will "freeze" your thread, setup a mechanism to wake you when the lock is freed, and then wake you again in the future.
All of this is much more expensive than some loops checking the lock. That is why sometimes is better to do a "spinlock".
For example:
void beginSpinLock(lock)
{
if(lock) loopFor(1 milliseconds);
else
{
lock = true;
return;
}
if(lock) loopFor(2 milliseconds);
else
{
lock = true;
return;
}
// important is that the part above never
// cause the thread to sleep.
// It is "burning" the time slice of this thread.
// Hopefully for good.
// some implementations fallback to OS lock mechanism
// after a few tries
if(lock) return beginLock(lock);
else
{
lock = true;
return;
}
}
If your implementation is not careful, you can fall on livelock, spending all CPU on the lock mechanism.
Also see:
https://preshing.com/20120226/roll-your-own-lightweight-mutex/
Is my spin lock implementation correct and optimal?
Summary:
Deadlock: situation where nobody progress, doing nothing (sleeping, waiting etc..). CPU usage will be low;
Livelock: situation where nobody progress, but CPU is spent on the lock mechanism and not on your calculation;
Starvation: situation where one procress never gets the chance to run; by pure bad luck or by some of its property (low priority, for example);
Spinlock: technique of avoiding the cost waiting the lock to be freed.
Be careful with the @
operator - while it suppresses warnings it also suppresses fatal errors. I spent a lot of time debugging a problem in a system where someone had written @mysql_query( '...' )
and the problem was that mysql support was not loaded into PHP and it threw a silent fatal error. It will be safe for those things that are part of the PHP core but please use it with care.
bob@mypc:~$ php -a
Interactive shell
php > echo @something(); // this will just silently die...
No further output - good luck debugging this!
bob@mypc:~$ php -a
Interactive shell
php > echo something(); // lets try it again but don't suppress the error
PHP Fatal error: Call to undefined function something() in php shell code on line 1
PHP Stack trace:
PHP 1. {main}() php shell code:0
bob@mypc:~$
This time we can see why it failed.
There's literature about it:
Optimized Pagination using MySQL, making the difference between counting the total amount of rows, and pagination.
Efficient Pagination Using MySQL, by Yahoo Inc. in the Percona Performance Conference 2009. The Percona MySQL team provides it also as a Youtube video: Efficient Pagination Using MySQL (video),
The main problem happens with the usage of large OFFSET
s. They avoid using OFFSET
with a variety of techniques, ranging from id
range selections in the WHERE
clause, to some kind of caching or pre-computing pages.
There are suggested solutions at Use the INDEX, Luke:
You could always try doing a ulimit -n 2048
. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit
Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system.
set rlim_fd_max = 166384
set rlim_fd_cur = 8192
On OS X, this same data must be set in /etc/sysctl.conf.
kern.maxfilesperproc=166384
kern.maxfiles=8192
Under Linux, these settings are often in /etc/security/limits.conf.
There are two kinds of limits:
Soft limits could be set by any user while hard limits are changeable only by root. Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits.
There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default.
Yes, you can make dynamic styles. You can pass values from Components.
First create StyleSheetFactory.js
import { StyleSheet } from "react-native";
export default class StyleSheetFactory {
static getSheet(backColor) {
return StyleSheet.create({
jewelStyle: {
borderRadius: 10,
backgroundColor: backColor,
width: 20,
height: 20,
}
})
}
}
then use it in your component following way
import React from "react";
import { View } from "react-native";
import StyleSheetFactory from './StyleSheetFactory'
class Main extends React.Component {
getRandomColor = () => {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
render() {
return (
<View>
<View
style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
/>
<View
style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
/>
<View
style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
/>
</View>
);
}
}
Look at the API from hostip.info - it provides lots of information.
Example in PHP:
$data = file_get_contents("http://api.hostip.info/country.php?ip=12.215.42.19");
//$data contains: "US"
$data = file_get_contents("http://api.hostip.info/?ip=12.215.42.19");
//$data contains: XML with country, lat, long, city, etc...
If you trust hostip.info, it seems to be a very useful API.
Here is more info. First you are dealing with a frozen distribution (frozen in this case means its parameters are set to specific values). To create a frozen distribution:
import scipy.stats
scipy.stats.norm(loc=100, scale=12)
#where loc is the mean and scale is the std dev
#if you wish to pull out a random number from your distribution
scipy.stats.norm.rvs(loc=100, scale=12)
#To find the probability that the variable has a value LESS than or equal
#let's say 113, you'd use CDF cumulative Density Function
scipy.stats.norm.cdf(113,100,12)
Output: 0.86066975255037792
#or 86.07% probability
#To find the probability that the variable has a value GREATER than or
#equal to let's say 125, you'd use SF Survival Function
scipy.stats.norm.sf(125,100,12)
Output: 0.018610425189886332
#or 1.86%
#To find the variate for which the probability is given, let's say the
#value which needed to provide a 98% probability, you'd use the
#PPF Percent Point Function
scipy.stats.norm.ppf(.98,100,12)
Output: 124.64498692758187
protected void grdDis_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
#region Dynamically Show gridView header From data base
getAllheaderName();/*To get all Allowences master headerName*/
TextBox txt_Days = (TextBox)grdDis.HeaderRow.FindControl("txtDays");
txt_Days.Text = hidMonthsDays.Value;
#endregion
}
}
You've shadowed the builtin set by accidentally using it as a variable name, here is a simple way to replicate your error
>>> set=set()
>>> set=set()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable
The first line rebinds set to an instance of set. The second line is trying to call the instance which of course fails.
Here is a less confusing version using different names for each variable. Using a fresh interpreter
>>> a=set()
>>> b=a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable
Hopefully it is obvious that calling a
is an error
Edit: By request, I added a check to make sure the value entered was within the ASCII range of 0 to 127. Whether you want to limit this is up to you. In C# (and I believe .NET in general), char
s are represented using UTF-16, so any valid UTF-16 character value could be cast into it. However, it is possible a system does not know what every Unicode character should look like so it may show up incorrectly.
// Read a line of input
string input = Console.ReadLine();
int value;
// Try to parse the input into an Int32
if (Int32.TryParse(input, out value)) {
// Parse was successful
if (value >= 0 and value < 128) {
//value entered was within the valid ASCII range
//cast value to a char and print it
char c = (char)value;
Console.WriteLine(c);
}
}
I use this code and it works:
.slider - this is slider block
.count - selector which use for return counter
$(".slider").on("init", function(event, slick){
$(".count").text(parseInt(slick.currentSlide + 1) + ' / ' + slick.slideCount);
});
$(".slider").on("afterChange", function(event, slick, currentSlide){
$(".count").text(parseInt(slick.currentSlide + 1) + ' / ' + slick.slideCount);
});
$(".page-article-item_image-slider").slick({
slidesToShow: 1,
arrows: true
});
Take out the parentheses and the curly braces, neither are required when adding columns.
The loop in your code is only an over-simplified example, right?
It would be better to create the PreparedStatement
only once, and re-use it over and over again in the loop.
In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement
, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.
To address the situation that you want to re-use the Java-side PreparedStatement
, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement
for the same SQL on the same connection, it will give you the same (cached) instance.
About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.
I wanted to write this as a comment but I do not have 50 reputation.
All of the answers in this thread are essentially to use Invoke-Item or to use explorer.exe directly; however, this isn't completely synonymous with "open containing folder", so in terms of opening an Explorer window as the question states, if we wanted to apply the answer to a particular file the question still hasn't really been answered.
e.g.,
Invoke-Item C:\Users\Foo\bar.txt
explorer.exe C:\Users\Foo\bar.html
^ those two commands would result in Notepad.exe or Firefox.exe being invoked on the two files respectively, not an explorer.exe window on C:\Users\Foo\ (the containing directory).
Whereas if one was issuing this command from powershell, this would be no big deal (less typing anyway), if one is scripting and needs to "open containing folder" on a variable, it becomes a matter of string matching to extract the directory from the full path to the file.
Is there no simple command "Open-Containing-Folder" such that a variable could be substituted?
e.g.,
$foo = "C:\Users\Foo\foo.txt"
[some code] $fooPath
# opens C:\Users\Foo\ and not the default program for .txt file extension
i had the same problem, i fixed it by removing the transform:translateY
CSS i placed on the footer
of the page.
The .NET projects are always recompiled regardless. Part of this is to keep the IDE up to date (such as IntelliSense). I remember asking this question on an Microsoft forum years ago, and this was the answer I was given.
My usual way of doing this is:
my %unique = ();
foreach my $item (@myarray)
{
$unique{$item} ++;
}
my @myuniquearray = keys %unique;
If you use a hash and add the items to the hash. You also have the bonus of knowing how many times each item appears in the list.
I got this error when calling this code: wks.Range[startCell, endCell]
where the startCell
Range and endCell
Range were pointing to different worksheet then the variable wks
.
Using the appropriate VerificationMode:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");
You are passing the value of the memory location of the first member of the array.
Therefore when you start modifying the array inside the function, you are modifying the original array.
Remember that a[1]
is *(a+1)
.
I have just tested this and works fine.
string test = "Testing 1-2-3";
// convert string to stream
byte[] byteArray = Encoding.ASCII.GetBytes(test);
MemoryStream stream = new MemoryStream(byteArray);
// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
If stream
has already been written to, you might want to seek to the beginning before first before reading out the text: stream.Seek(0, SeekOrigin.Begin);
There are several problems in your code.
First the big ones:
You are creating a new figure and a new axes in every iteration of your loop ?
put fig = plt.figure
and ax = fig.add_subplot(1,1,1)
outside of the loop.
Don't use the Locators. Call the functions ax.set_xticks()
and ax.grid()
with the correct keywords.
With plt.axes()
you are creating a new axes again. Use ax.set_aspect('equal')
.
The minor things:
You should not mix the MATLAB-like syntax like plt.axis()
with the objective syntax.
Use ax.set_xlim(a,b)
and ax.set_ylim(a,b)
This should be a working minimal example:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)
ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)
# And a corresponding grid
ax.grid(which='both')
# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)
plt.show()
Output is this:
I couldn't get the other answers to work within the evaluate console in Intellij so...
groovy.json.JsonOutput.toJson(myObject)
This works quite well, but unfortunately
groovy.json.JsonOutput.prettyString(myObject)
didn't work for me.
To get it pretty printed I had to do this...
groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(myObject))
If you want to do this the C++ way, do it like this:
#include <fstream>
#include <iterator>
#include <algorithm>
int main()
{
std::ifstream input( "C:\\Final.gif", std::ios::binary );
std::ofstream output( "C:\\myfile.gif", std::ios::binary );
std::copy(
std::istreambuf_iterator<char>(input),
std::istreambuf_iterator<char>( ),
std::ostreambuf_iterator<char>(output));
}
If you need that data in a buffer to modify it or something, do this:
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
std::ifstream input( "C:\\Final.gif", std::ios::binary );
// copies all data into buffer
std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});
}
You could add a method to String to make it more semantic:
String.metaClass.getNotBlank = { !delegate.allWhitespace }
which let's you do:
groovy:000> foo = ''
===>
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true
Get rid of the notion of vector entirely
template< typename IT, typename VT>
int index_of(IT begin, IT end, const VT& val)
{
int index = 0;
for (; begin != end; ++begin)
{
if (*begin == val) return index;
}
return -1;
}
This will allow you more flexibility and let you use constructs like
int squid[] = {5,2,7,4,1,6,3,0};
int sponge[] = {4,2,4,2,4,6,2,6};
int squidlen = sizeof(squid)/sizeof(squid[0]);
int position = index_of(&squid[0], &squid[squidlen], 3);
if (position >= 0) { std::cout << sponge[position] << std::endl; }
You could also search any other container sequentially as well.
Just use --repo
option for git push command. Like this:
$ git push --repo https://name:[email protected]/name/repo.git
var array: Int[][] = [[1,2,3],[4,5,6],[7,8,9]]
for first in array {
for second in first {
println("value \(second)")
}
}
To achieve what you're looking for you need to initialize the array to the correct template and then loop to add the row and column arrays:
var NumColumns = 27
var NumRows = 52
var array = Array<Array<Int>>()
var value = 1
for column in 0..NumColumns {
var columnArray = Array<Int>()
for row in 0..NumRows {
columnArray.append(value++)
}
array.append(columnArray)
}
println("array \(array)")
WARNING: This deletes all commits on the email branch. It's like deleting the email branch and creating it anew at the head of the staging branch.
The easiest way to do it:
//the branch you want to overwrite
git checkout email
//reset to the new branch
git reset --hard origin/staging
// push to remote
git push -f
Now the email branch and the staging are the same.
Have you tried int 21h
service 2? DL
is the character to print.
mov dl,'A' ; print 'A'
mov ah,2
int 21h
To print the integer value, you'll have to write a loop to decompose the integer to individual characters. If you're okay with printing the value in hex, this is pretty trivial.
If you can't rely on DOS services, you might also be able to use the BIOS int 10h
with AL
set to 0Eh
or 0Ah
.
Hotswap Agent is an extension to DCEVM which supports many Java frameworks (reload Spring bean definition, Hibernate entity mapping, logger level setup, ...).
There is also lot of documentation how to setup DCEVM and compiled binaries for Java 1.7.
You're using non-standard xhtml code (values should be framed with double quotes, not single quotes)
Try this:
<form>
<label>Do you want to accept American Express?</label>
Yes<input id="amex" style="width: 20px;" type="radio" name="Contact0_AmericanExpress" />
No<input style="width: 20px;" type="radio" name="Contact0_AmericanExpress" class="check" checked="checked" />
</form>
You could use *ngIf="teamMembers != 0"
to check whether data is present
Thanks HansUp for your answer, it is very helpful and it works!
I found three patterns working in Access, yours is the best, because it works in all cases.
INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM
((class
INNER JOIN person AS cr
ON class.C_P_ClassRep=cr.P_Nr
)
INNER JOIN person AS cr2
ON class.C_P_ClassRep2nd=cr2.P_Nr
)
;
INNER JOIN "chained-set pattern"
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM person AS cr
INNER JOIN ( class
INNER JOIN ( person AS cr2
) ON class.C_P_ClassRep2nd=cr2.P_Nr
) ON class.C_P_ClassRep=cr.P_Nr
;
CROSS JOIN with WHERE
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM class, person AS cr, person AS cr2
WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
;