Rather than escape my password I left it out and was prompted for it, but only when I included the domain name before my username:
git clone https://some-dom-name\[email protected]/tfs/...
I opened XCode -> Preferences -> Accounts and clicked on Download certificate. That fixed my problem
I am facing Same Problem i do following Setup Now Application Work fine
1-
<compilation debug="true" targetFramework="4.7.1">
<assemblies>
<add assembly="netstandard, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=cc7b13ffcd2ddd51"/>
</assemblies>
</compilation>
2- Add Reference
**C:\Program Files (x86)\Microsoft Visual
Studio\2017\Professional\Common7\IDE\Extensions\Microsoft\ADL
Tools\2.4.0000.0\ASALocalRun\netstandard.dll**
3-
Copy Above Path Dll to Application Bin Folder on web server
php artisan config:clear
(NOT cache)
You could use moment.js with Postman to give you that timestamp format.
You can add this to the pre-request script:
const moment = require('moment');
pm.globals.set("today", moment().format("MM/DD/YYYY"));
Then reference {{today}}
where ever you need it.
If you add this to the Collection Level Pre-request Script
, it will be run for each request in the Collection
. Rather than needing to add it to all the requests individually.
For more information about using moment
in Postman, I wrote a short blog post: https://dannydainton.com/2018/05/21/hold-on-wait-a-moment/
You should make sure your test case function is public rather than private to make it accessible by Test Runner.
@Test
private void testmethod(){}
to
@Test
public void testmethod(){}
I guess the answer you need is referenced here Python sets are not json serializable
Not all datatypes can be json serialized . I guess pickle module will serve your purpose.
My system version: ubuntu 20.04 LTS.
I solved this by generate a new MOK and enroll it into shim.
Without disable of Secure Boot, although it also really works for me.
Simply execute this command and follow what it suggests:
sudo update-secureboot-policy --enroll-key
According to ubuntu's wiki: How can I do non-automated signing of drivers
json.loads
take a string as input and returns a dictionary as output.
json.dumps
take a dictionary as input and returns a string as output.
With json.loads({"('Hello',)": 6, "('Hi',)": 5})
,
You are calling json.loads
with a dictionary as input.
You can fix it as follows (though I'm not quite sure what's the point of that):
d1 = {"('Hello',)": 6, "('Hi',)": 5}
s1 = json.dumps(d1)
d2 = json.loads(s1)
In Python 3 this can be done in 2 steps:
datetime
objectdatetime
object by 1000 to convert it to milliseconds.For example like this:
from datetime import datetime
dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
'%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000
print(millisec)
Output:
1482223122760.0
strptime
accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime
object. The format string (second argument) specifies the actual format of the string that you have passed.
Here is the explanation of the format specifiers from the official documentation:
%d
- Day of the month as a zero-padded decimal number.%m
- Month as a zero-padded decimal number.%Y
- Year with century as a decimal number%H
- Hour (24-hour clock) as a zero-padded decimal number.%M
- Minute as a zero-padded decimal number.%S
- Second as a zero-padded decimal number.%f
- Microsecond as a decimal number, zero-padded on the left.iloc
df1 = datasX.iloc[:, :72]
df2 = datasX.iloc[:, 72:]
There are two problems with your code:
LocalDateTime
does not support timezone. Given below is an overview of java.time types and you can see that the type which matches with your date-time string, 2016-12-01T23:00:00+00:00
is OffsetDateTime
because it has a zone offset of +00:00
.
Change your declaration as follows:
private OffsetDateTime startDate;
There are two problems with the format:
y
(year-of-era ) instead of Y
(week-based-year). Check this discussion to learn more about it. In fact, I recommend you use u
(year) instead of y
(year-of-era ). Check this answer for more details on it.XXX
or ZZZZZ
for the offset part i.e. your format should be uuuu-MM-dd'T'HH:m:ssXXX
.Check the documentation page of DateTimeFormatter
for more details about these symbols/formats.
Demo:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String strDateTime = "2019-10-21T13:00:00+02:00";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:m:ssXXX");
OffsetDateTime odt = OffsetDateTime.parse(strDateTime, dtf);
System.out.println(odt);
}
}
Output:
2019-10-21T13:00+02:00
Learn more about the modern date-time API from Trail: Date Time.
x = x.replace("'", '"')
j = json.loads(x)
Although this is the correct solution, but it may lead to quite a headache if there a JSON like this -
{'status': 'success', 'data': {'equity': {'enabled': True, 'net': 66706.14510000008, 'available': {'adhoc_margin': 0, 'cash': 1277252.56, 'opening_balance': 1277252.56, 'live_balance': 66706.14510000008, 'collateral': 249823.93, 'intraday_payin': 15000}, 'utilised': {'debits': 1475370.3449, 'exposure': 607729.3129, 'm2m_realised': 0, 'm2m_unrealised': -9033, 'option_premium': 0, 'payout': 0, 'span': 858608.032, 'holding_sales': 0, 'turnover': 0, 'liquid_collateral': 0, 'stock_collateral': 249823.93}}, 'commodity': {'enabled': True, 'net': 0, 'available': {'adhoc_margin': 0, 'cash': 0, 'opening_balance': 0, 'live_balance': 0, 'collateral': 0, 'intraday_payin': 0}, 'utilised': {'debits': 0, 'exposure': 0, 'm2m_realised': 0, 'm2m_unrealised': 0, 'option_premium': 0, 'payout': 0, 'span': 0, 'holding_sales': 0, 'turnover': 0, 'liquid_collateral': 0, 'stock_collateral': 0}}}}
Noticed that "True" value? Use this to make things are double checked for Booleans. This will cover those cases -
x = x.replace("'", '"').replace("True", '"True"').replace("False", '"False"').replace("null", '"null"')
j = json.loads(x)
Also, make sure you do not make
x = json.loads(x)
It has to be another variable.
You could add the default rule with the alter table,
ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()
then immediately set to null all the current existing rows:
UPDATE mytable SET created_at = NULL
Then from this point on the DEFAULT
will take effect.
I got this issue when I used an ajax call to retrieve data from the database. When the controller returned the array it converted it to a boolean. The problem was that I had "invalid characters" like ú (u with accent).
The simplest thing to do is, change the default table name assigned for the model. Simply put following code,
protected $table = 'category_posts';
instead of protected $table = 'posts';
then it'll do the trick.
However, if you refer Laravel documentation you'll find the answer. Here what it says,
By convention, the "snake case", plural name of the class(model) will be used as the table name unless another name is explicitly specified
Better to you use artisan command to make model and the migration file at the same time, use the following command,
php artisan make:model Test --migration
This will create a model class and a migration class in your Laravel project. Let's say it created following files,
Test.php
2018_06_22_142912_create_tests_table.php
If you look at the code in those two files you'll see,
2018_06_22_142912_create_tests_table.php files' up function,
public function up()
{
Schema::create('tests', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
Here it automatically generated code with the table name of 'tests' which is the plural name of that class which is in Test.php file.
Replace the * with a /
So instead of
COPY * <destination>
use
COPY / <destination>
Put the default value in single quote and it will work as intended. An example of migration:
$table->increments('id');
$table->string('name');
$table->string('url');
$table->string('country');
$table->tinyInteger('status')->default('1');
$table->timestamps();
EDIT : in your case ->default('100.0');
I tried all the steps described above but failed.
Like, connect to the internet with Data connection
, Turning off the MIUI optimization and reboot
, Turning on Install via USB
from Security settings etc.
Then I found a solution.
Steps:
China-Shanghai
serverInstall via USB
from Developer option.That's all.
No, you can't!
However, having bumped into that issue should make you rethink on how you organize your code.
Before ES6 modules, we had CommonJS modules which used the require() syntax. These modules were "dynamic", meaning that we could import new modules based on conditions in our code. - source: https://bitsofco.de/what-is-tree-shaking/
I guess one of the reasons they dropped that support on ES6 onward is the fact that compiling it would be very difficult or impossible.
One notable difference in Python 2 is that if you're using ensure_ascii=False
, dump
will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):
dumps
on the other hand, with ensure_ascii=False
can produce a str
or unicode
just depending on what types you used for strings:
Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a
unicode
instance.
(emphasis mine). Note that it may still be a str
instance as well.
Thus you cannot use its return value to save the structure into file without checking which
format was returned and possibly playing with unicode.encode
.
This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.
As for load
vs loads
, load
considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.
There are just so many gotchas when creating deployment packages for AWS Lambda (for Python). I have spent hours and hours on debugging sessions until I found a formula that rarely fails.
I have created a script that automates the entire process and therefore makes it less error prone. I have also wrote tutorial that explains how everything works. You may want to check it out:
This worked for me.
My component named 'my-component', for example, was displayed using *ngIf="showMe" like so:
<my-component [showMe]="showMe" *ngIf="showMe"></my-component>
So, when the component is initialized the component is not yet displayed until "showMe" is true. Thus, my @ViewChild references were all undefined.
This is where I used @ViewChildren and the QueryList that it returns. See angular article on QueryList and a @ViewChildren usage demo.
You can use the QueryList that @ViewChildren returns and subscribe to any changes to the referenced items using rxjs as seen below. @ViewChild does not have this ability.
import { Component, ViewChildren, ElementRef, OnChanges, QueryList, Input } from '@angular/core';
import 'rxjs/Rx';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnChanges {
@ViewChildren('ref') ref: QueryList<any>; // this reference is just pointing to a template reference variable in the component html file (i.e. <div #ref></div> )
@Input() showMe; // this is passed into my component from the parent as a
ngOnChanges () { // ngOnChanges is a component LifeCycle Hook that should run the following code when there is a change to the components view (like when the child elements appear in the DOM for example)
if(showMe) // this if statement checks to see if the component has appeared becuase ngOnChanges may fire for other reasons
this.ref.changes.subscribe( // subscribe to any changes to the ref which should change from undefined to an actual value once showMe is switched to true (which triggers *ngIf to show the component)
(result) => {
// console.log(result.first['_results'][0].nativeElement);
console.log(result.first.nativeElement);
// Do Stuff with referenced element here...
}
); // end subscribe
} // end if
} // end onChanges
} // end Class
Hope this helps somebody save some time and frustration.
cat ~/.docker/config.json
Sample Result:
{
"auths": {
"https://55511155511.dkr.ecr.us-east-1.amazonaws.com": {}
},
"HttpHeaders": {
"User-Agent": "Docker-Client/19.03.5 (darwin)"
},
"credsStore": "osxkeychain"
}
Notice that the "auths" value is an empty object and docker is using a credential store "osxkeychain".
Notice the Where:
field
auths
key in ~/.docker/config.json
matches the Where:
field in Keychain Access.If the auths
key in ~/.docker/config.json does NOT match they Where:
field in the keychain, you may get a Login Succeeded
from docker login...
but still get
ERROR: Service 'web' failed to build: Get https://55511155511.dkr.ecr.us-east-1.amazonaws.com/v2/path/to/image/latest: no basic auth credentials
when you try to pull.
In my case, I needed to add https://
Original
"auths": {
"55511155511.dkr.ecr.us-east-1.amazonaws.com": {}
},
Fixed
"auths": {
"https://55511155511.dkr.ecr.us-east-1.amazonaws.com": {}
},
json.dumps()
is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.
For instance, if one of the values is None
, the str()
would produce an invalid JSON which cannot be loaded:
>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
But the dumps()
would convert None
into null
making a valid JSON string that can be loaded:
>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
On the model set $incrementing
to false
public $incrementing = false;
This will stop it from thinking it is an auto increment field.
How to do what @connor said:
iOS
platforms/ios
on XCodeio.ionic.starter
in all files for a unique identifierionic cordova run ios --device --livereload
json.loads()
takes a JSON encoded string, not a filename. You want to use json.load()
(no s
) instead and pass in an open file object:
with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
data = json.load(jsonfile)
The open()
command produces a file object that json.load()
can then read from, to produce the decoded Python object for you. The with
statement ensures that the file is closed again when done.
The alternative is to read the data yourself and then pass it into json.loads()
.
I had the same problem and I've already tried everything and nothing seemed to work until I just changed the 'host' value in config.php to:
'host' => env('smtp.mailtrap.io'),
When I changed that it worked nicely, somehow it was using the default host " smtp.mailtrap.org" and ignoring the .env variable I was setting.
After making some test I realize that if I placed the env variable in this order it would worked as it shoulded:
MAIL_HOST=smtp.mailtrap.io
?MAIL_DRIVER=smtp
?MAIL_PORT=2525?
MAIL_USERNAME=xxxx
?MAIL_PASSWORD=xxx
?MAIL_ENCRYPTION=null
You can use the Time.String()
method to convert a time.Time
to a string
. This uses the format string "2006-01-02 15:04:05.999999999 -0700 MST"
.
If you need other custom format, you can use Time.Format()
. For example to get the timestamp in the format of yyyy-MM-dd HH:mm:ss
use the format string "2006-01-02 15:04:05"
.
Example:
t := time.Now()
fmt.Println(t.String())
fmt.Println(t.Format("2006-01-02 15:04:05"))
Output (try it on the Go Playground):
2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:00:00
Note: time on the Go Playground is always set to the value seen above. Run it locally to see current date/time.
Also note that using Time.Format()
, as the layout string
you always have to pass the same time –called the reference time– formatted in a way you want the result to be formatted. This is documented at Time.Format()
:
Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be
Mon Jan 2 15:04:05 -0700 MST 2006
would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.
First composer requires doctrine/dbal
, then:
$table->longText('column_name')->change();
json loads -> returns an object from a string representing a json object.
json dumps -> returns a string representing a json object from an object.
load and dump -> read/write from/to file instead of string
I had also faced same error when i was trying to call bootstrap modal from jquery. But this happens because we are using bootstrap modal and for this we need to attach one cdn bootstrap.min.js which is
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Hope this will help as I missed that when i was trying to call bootstrap modal from jQuery using
$('#button').on('click',function(){
$('#myModal').modal();
});
myModal
is the id of Bootstrap modal
and you have to give a click event to a button when you call click that button a pop up modal will be displayed.
Check Following Things
In order to give a value in the table, we need to give a command:
php artisan make:migration create_users_table
and after then this command line
php artisan migrate
......
[OOT]
A bit OOT, but this question is the most closest topic with my question.
Here is an example if you want to show Event where ALL participant meet certain requirement. Let's say, event where ALL the participant has fully paid. So, it WILL NOT return events which having one or more participants that haven't fully paid .
Simply use the whereDoesntHave
of the others 2 statuses.
Let's say the statuses are haven't paid at all [eq:1], paid some of it [eq:2], and fully paid [eq:3]
Event::whereDoesntHave('participants', function ($query) {
return $query->whereRaw('payment = 1 or payment = 2');
})->get();
Tested on Laravel 5.8 - 7.x
First, convert the timestamp using the built-in eloquent functionality, as described in this answer.
Then you can just use Carbon's min()
or max()
function for comparison. For example:
$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0);
$dt2 = Carbon::create(2014, 1, 30, 0, 0, 0);
echo $dt1->min($dt2);
This will echo
the lesser of the two dates, which in this case is $dt1
.
One thing no one has pointed out is that you can use LATERAL
queries to apply a user-defined function on every selected row.
For instance:
CREATE OR REPLACE FUNCTION delete_company(companyId varchar(255))
RETURNS void AS $$
BEGIN
DELETE FROM company_settings WHERE "company_id"=company_id;
DELETE FROM users WHERE "company_id"=companyId;
DELETE FROM companies WHERE id=companyId;
END;
$$ LANGUAGE plpgsql;
SELECT * FROM (
SELECT id, name, created_at FROM companies WHERE created_at < '2018-01-01'
) c, LATERAL delete_company(c.id);
That's the only way I know how to do this sort of thing in PostgreSQL.
You forgot @Service annotation in your service class.
Opening the new empty tab within same window in chrome browser is not possible up to my knowledge but you can open the new tab with web-link.
So far I surfed net and I got good working content on this question. Please try to follow the steps without missing.
import selenium.webdriver as webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get('https://www.google.com?q=python#q=python')
first_link = driver.find_element_by_class_name('l')
# Use: Keys.CONTROL + Keys.SHIFT + Keys.RETURN to open tab on top of the stack
first_link.send_keys(Keys.CONTROL + Keys.RETURN)
# Switch tab to the new tab, which we will assume is the next one on the right
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
driver.quit()
I think this is better solution so far.
"Allocation Failure" is a cause of GC cycle to kick in.
"Allocation Failure" means that no more space left in Eden to allocate object. So, it is normal cause of young GC.
Older JVM were not printing GC cause for minor GC cycles.
"Allocation Failure" is almost only possible cause for minor GC. Another reason for minor GC to kick could be CMS remark phase (if +XX:+ScavengeBeforeRemark
is enabled).
Nice answer by Alex and Sameer, but maybe just additional info on why is necessary to put
public $timestamps = false;
Timestamps are nicely explained on official Laravel page:
By default, Eloquent expects created_at and updated_at columns to exist on your >tables. If you do not wish to have these columns automatically managed by >Eloquent, set the $timestamps property on your model to false.
json.dumps()
returns the JSON string representation of the python dict. See the docs
You can't do r['rating']
because r is a string, not a dict anymore
Perhaps you meant something like
r = {'is_claimed': 'True', 'rating': 3.5}
json = json.dumps(r) # note i gave it a different name
file.write(str(r['rating']))
To rename a column, you may use the renameColumn method on the Schema builder. *Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file.*
Or you can simply required the package using composer...
composer require doctrine/dbal
Source: https://laravel.com/docs/5.0/schema#renaming-columns
Note: Use make:migration and not migrate:make for Laravel 5.x
In my case, I wanted to unit test that users weren't able to verify their email addresses after 1 hour had passed, so I didn't want to do any of the other answers since they would also persist when not unit testing, so I ended up just manually updating the row after insert:
// Create new user
$user = factory(User::class)->create();
// Add an email verification token to the
// email_verification_tokens table
$token = $user->generateNewEmailVerificationToken();
// Get the time 61 minutes ago
$created_at = (new Carbon())->subMinutes(61);
// Do the update
\DB::update(
'UPDATE email_verification_tokens SET created_at = ?',
[$created_at]
);
Note: For anything other than unit testing, I would look at the other answers here.
>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14
I was also facing the same problem, I followed the same process but my problem was not resolving so I try another thing. I dropped the tables from my database and use a header file
use Illuminate\Support\Facades\Schema;
and increase the default string length in boot
method to add this:
Schema::defaultStringLength(191);
then again php artisan migrate
. Problem is resolved, all tables are created in the database.
The high spike that you have is due to the DC (non-varying, i.e. freq = 0) portion of your signal. It's an issue of scale. If you want to see non-DC frequency content, for visualization, you may need to plot from the offset 1 not from offset 0 of the FFT of the signal.
Modifying the example given above by @PaulH
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
# Number of samplepoints
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = 10 + np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = scipy.fftpack.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)
plt.subplot(2, 1, 1)
plt.plot(xf, 2.0/N * np.abs(yf[0:N/2]))
plt.subplot(2, 1, 2)
plt.plot(xf[1:], 2.0/N * np.abs(yf[0:N/2])[1:])
The output plots:
Another way, is to visualize the data in log scale:
Using:
plt.semilogy(xf, 2.0/N * np.abs(yf[0:N/2]))
Will show:
My answer is for everyone who comes here (like I did) to find an answer for a bug caused by the hiding address bare / browser interface.
The hiding address bar causes the resize-event to trigger. But different than other resize-events, like switching to landscape mode, this doesn't change the width of the window. So my solution is to hook into the resize event and check if the width is the same.
// Keep track of window width
let myWindowWidth = window.innerWidth;
window.addEventListener( 'resize', function(event) {
// If width is the same, assume hiding address bar
if( myWindowWidth == window.innerWidth ) {
return;
}
// Update the window width
myWindowWidth = window.innerWidth;
// Do your thing
// ...
});
You can chain your where
s directly, without function(q)
. There's also a nice date handling package in laravel, called Carbon. So you could do something like:
$projects = Project::where('recur_at', '>', Carbon::now())
->where('recur_at', '<', Carbon::now()->addWeek())
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();
Just make sure you require Carbon in composer and you're using Carbon namespace (use Carbon\Carbon;) and it should work.
EDIT: As Joel said, you could do:
$projects = Project::whereBetween('recur_at', array(Carbon::now(), Carbon::now()->addWeek()))
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();
You can simplify your code down to
url = "http://worldcup.kimonolabs.com/api/players?apikey=xxx"
json_obj = urllib2.urlopen(url).read
player_json_list = json.loads(json_obj)
for player in readable_json_list:
print player['firstName']
You were trying to access a list element using dictionary syntax. the equivalent of
foo = [1, 2, 3, 4]
foo["1"]
It can be confusing when you have lists of dictionaries and keeping the nesting in order.
Give your body
tag an overflow: scroll;
body {
overflow: scroll;
}
or if you only want a vertical scrollbar use overflow-y
body {
overflow-y: scroll;
}
Few Operation relates to Array in Swift
Create Array
var stringArray = ["One", "Two", "Three", "Four"]
Add Object in Array
stringArray = stringArray + ["Five"]
Get Value from Index object
let x = stringArray[1]
Append Object
stringArray.append("At last position")
Insert Object at Index
stringArray.insert("Going", at: 1)
Remove Object
stringArray.remove(at: 3)
Concat Object value
var string = "Concate Two object of Array \(stringArray[1]) + \(stringArray[2])"
The same error pops up because of the way Laravel unique() function works.
The only thing you need to do is specify a shorter index name eg.
$table->unique(['email', 'users_email_uniq'],'my_custom_uniq');
Windows 10 x64 released August 2015 - same issue arising. MSVCR110.dll is also found in the sysWOW64 folder (which is where I found it, copying to system32 does not help). To resolve:
Hopefully like me you have a MySQL database backup handy!
I think that you should make the reference to your config file
26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf
you can try to start your redis server like
./redis-server /path/to/redis-stable/redis.conf
For Apache 2.4.9
in addition, look at the httpd-vhosts.conf file in C:\wamp\bin\apache\apache2.4.9\conf\extra
<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot C:/wamp/www
<Directory "C:/wamp/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require local
</Directory>
</VirtualHost>
Change to:
<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot C:/wamp/www
<Directory "C:/wamp/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require all granted
</Directory>
</VirtualHost>
changing from "Require local" to "Require all granted" solved the error 403 in my local network
EasyDict
library (doc):EasyDict allows to access dict values as attributes (works recursively). A Javascript-like properties dot notation for python dicts.
USEAGE
>>> from easydict import EasyDict as edict >>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}}) >>> d.foo 3 >>> d.bar.x 1 >>> d = edict(foo=3) >>> d.foo 3
[INSTALLATION]:
pip install easydict
>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')
The man pages is the best source of information you can find... and is at your fingertips: man mkdir
yields this about -p
switch:
-p, --parents
no error if existing, make parent directories as needed
Use case example: Assume I want to create directories hello/goodbye
but none exist:
$mkdir hello/goodbye
mkdir:cannot create directory 'hello/goodbye': No such file or directory
$mkdir -p hello/goodbye
$
-p
created both, hello
and goodbye
This means that the command will create all the directories necessaries to fulfill your request, not returning any error in case that directory exists.
About rlidwka
, Google has a very good memory for acronyms :). My search returned this for example: http://www.cs.cmu.edu/~help/afs/afs_acls.html
Directory permissions
l (lookup)
Allows one to list the contents of a directory. It does not allow the reading of files.
i (insert)
Allows one to create new files in a directory or copy new files to a directory.
d (delete)
Allows one to remove files and sub-directories from a directory.
a (administer)
Allows one to change a directory's ACL. The owner of a directory can always change the ACL of a directory that s/he owns, along with the ACLs of any subdirectories in that directory.
File permissions
r (read)
Allows one to read the contents of file in the directory.
w (write)
Allows one to modify the contents of files in a directory and use chmod on them.
k (lock)
Allows programs to lock files in a directory.
Hence rlidwka
means: All permissions on.
It's worth mentioning, as @KeithThompson pointed out in the comments, that not all Unix systems support ACL. So probably the rlidwka
concept doesn't apply here.
If none of the solutions above work for newbies check if both IDs have the same type: both are integer
or both are bigInteger
, ... You can have something like this:
Main Table (users for example)
$table->bigIncrements('id');
Child Table (priorities for example)
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
This query will failed because users.id
is a BIG INTEGER
whereas priorities.user_id
is an INTEGER
.
The right query in this case would be the following:
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
One possible issue I see is you set your JSON unconventionally within an array/list object. I would recommend using JSON in its most accepted form, i.e.:
test_json = { "a": 1, "b": 2}
Once you do this, adding a json element only involves the following line:
test_json["c"] = 3
This will result in:
{'a': 1, 'b': 2, 'c': 3}
Afterwards, you can add that json back into an array or a list of that is desired.
On read csv
, I added an encoding method:
import pandas as pd
dataset = pd.read_csv('sample_data.csv', header= 0,
encoding= 'unicode_escape')
ATTENTION ::
-- because of poorly made caching system, in Atom loss of data occurs often when using big files.
It has been proven numerous times.
If you are using Microsoft Drivers 3.1, 3.0, and 2.0.
Please check your PHP version already install with IIS.
Use this script to check the php version:
<?php echo phpinfo(); ?>
OR
If you have installed PHP Manager in IIS using web platform Installer you can check the version from it.
Then:
If you are using new PHP version (5.6) please download Drivers from here
For PHP version Lower than 5.6 - please download Drivers from here
Then use the PHP Manager to add that downloaded drivers into php config
file.You can do it as shown below (browse the files and press OK).
Then Restart the IIS Server
If this method not work please change the php version and try to run your php script.
Tip:Change the php version
to lower and try to understand what happened.then you can download relevant drivers.
If I get you right, you want to add the sensors
collection to the node
. If you have a mapping between both models you can either use the include
functionality explained here or the values
getter defined on every instance. You can find the docs for that here.
The latter can be used like this:
db.Sensors.findAll({
where: {
nodeid: node.nodeid
}
}).success(function (sensors) {
var nodedata = node.values;
nodedata.sensors = sensors.map(function(sensor){ return sensor.values });
// or
nodedata.sensors = sensors.map(function(sensor){ return sensor.toJSON() });
nodesensors.push(nodedata);
response.json(nodesensors);
});
There is chance that nodedata.sensors = sensors
could work as well.
I wrote an HTML5 video player around broadway h264 codec (emscripten) that can play live (no delay) h264 video on all browsers (desktop, iOS, ...).
Video stream is sent through websocket to the client, decoded frame per frame and displayed in a canva (using webgl for acceleration)
Check out https://github.com/131/h264-live-player on github.
I tried doing something similar, which took me a lot of time before I could figure out the collect() function. So you can have something this way:
collect($items)->sum('amount');
This will give you the sum total of all the items.
Adding to what @Hitesh-sahu said you need all the VC++ redistribution packages for it to turn green. I referred to this thread from wampserver forum. You can install this little tool (check_vcredist) from the tools section here which will check if all the needed dependencies are installed (see attached image) and it will also provide links to missing ones. If you are using x64 version of Windows like I do and your wampserver does not turn green even after installing all the packages then uninstall and do a fresh installation again. Hope it helps.
The accepted answers animation does not work on Safari, I've updated it using translate instead of padding-left which makes for a smoother, bulletproof animation.
Also, the accepted answers demo fiddle has a lot of unnecessary styles.
So I created a simple version if you just want to cut and paste the useful code and not spend 5 mins clearing through the demo.
.marquee {_x000D_
margin: 0 auto;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
box-sizing: border-box;_x000D_
padding: 0;_x000D_
height: 16px;_x000D_
display: block;_x000D_
}_x000D_
.marquee span {_x000D_
display: inline-block;_x000D_
text-indent: 0;_x000D_
overflow: hidden;_x000D_
-webkit-transition: 15s;_x000D_
transition: 15s;_x000D_
-webkit-animation: marquee 15s linear infinite;_x000D_
animation: marquee 15s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
0% { transform: translate(100%, 0); -webkit-transform: translateX(100%); }_x000D_
100% { transform: translate(-100%, 0); -webkit-transform: translateX(-100%); }_x000D_
}
_x000D_
<p class="marquee"><span>Simple CSS Marquee - Lorem ipsum dolor amet tattooed squid microdosing taiyaki cardigan polaroid single-origin coffee iPhone. Edison bulb blue bottle neutra shabby chic. Kitsch affogato you probably haven't heard of them, keytar forage plaid occupy pitchfork. Enamel pin crucifix tilde fingerstache, lomo unicorn chartreuse plaid XOXO yr VHS shabby chic meggings pinterest kickstarter.</span></p>
_x000D_
NoneType
is the type for the None
object, which is an object that indicates no value. None
is the return value of functions that "don't return anything". It is also a common default return value for functions that search for something and may or may not find it; for example, it's returned by re.search
when the regex doesn't match, or dict.get
when the key has no entry in the dict. You cannot add None
to strings or other objects.
One of your variables is None
, not a string. Maybe you forgot to return
in one of your functions, or maybe the user didn't provide a command-line option and optparse
gave you None
for that option's value. When you try to add None
to a string, you get that exception:
send_command(child, SNMPGROUPCMD + group + V3PRIVCMD)
One of group
or SNMPGROUPCMD
or V3PRIVCMD
has None
as its value.
@Amaynut Thanks
SELECT *
FROM eventList
WHERE date BETWEEN UNIX_TIMESTAMP('2017-08-01') AND UNIX_TIMESTAMP('2017/08/01');
above mention, code works and my problem solved.
Try to change where Member class
public function users() {
return $this->hasOne('User');
}
return $this->belongsTo('User');
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
just declare the public
timestamps variable in your Model
to false
and everything will work great.
public $timestamps = false;
Add the indent
parameter to json.dumps
data = {'this': ['has', 'some', 'things'],
'in': {'it': 'with', 'some': 'more'}}
print(json.dumps(data, indent=4))
Also note that, you can simply use json.dump
with the open jsonfile
:
json.dump(data, jsonfile)
You need a more specific expression. Try grep " OK$"
or grep "[0-9]* OK"
. You want to choose a pattern that matches what you want, but won't match what you don't want. That pattern will depend upon what your whole file contents might look like.
You can also do: grep -w "OK"
which will only match a whole word "OK", such as "1 OK" but won't match "1OK" or "OKFINE".
$ cat test.txt | grep -w "OK"
1 OK
2 OK
4 OK
Instant.now()
.toString()
2018-02-02T00:28:02.487114Z
Instant.parse(
"2018-02-02T00:28:02.487114Z"
)
The accepted Answer by ppeterka is correct. Your abuse of the formatting pattern results in an erroneous display of data, while the internal value is always limited milliseconds.
The troublesome SimpleDateFormat
and Date
classes you are using are now legacy, supplanted by the java.time classes. The java.time classes handle nanoseconds resolution, much finer than the milliseconds limit of the legacy classes.
The equivalent to java.util.Date
is java.time.Instant
. You can even convert between them using new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Capture the current moment in UTC. Java 8 captures the current moment in milliseconds, while a new Clock
implementation in Java 9 captures the moment in finer granularity, typically microseconds though it depends on the capabilities of your computer hardware clock & OS & JVM implementation.
Instant instant = Instant.now() ;
Generate a String in standard ISO 8601 format.
String output = instant.toString() ;
2018-02-02T00:28:02.487114Z
To generate strings in other formats, search Stack Overflow for DateTimeFormatter
, already covered many times.
To adjust into a time zone other than UTC, use ZonedDateTime
.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Or you can just use the <center></center>
tags.
Found a solution not involving Flex, because Flex doesn't work in older Browsers. Example:
.container {
display:block;
position:relative;
height:150px;
width:1024px;
margin:0 auto;
padding:0px;
border:0px;
background:#ececec;
margin-bottom:10px;
text-align:justify;
box-sizing:border-box;
white-space:nowrap;
font-size:0pt;
letter-spacing:-1em;
}
.cols {
display:inline-block;
position:relative;
width:32%;
height:100%;
margin:0 auto;
margin-right:2%;
border:0px;
background:lightgreen;
box-sizing:border-box;
padding:10px;
font-size:10pt;
letter-spacing:normal;
}
.cols:last-child {
margin-right:0;
}
If you are loading JSON string from a file & file contents arabic texts. Then this will work.
{
"key1" : "?????????",
"key2" : "????? ??????"
}
with open(arabic.json, encoding='utf-8') as f:
# deserialises it
json_data = json.load(f)
f.close()
# json formatted string
json_data2 = json.dumps(json_data, ensure_ascii = False)
# If have to get the JSON index in Django Template file, then simply decode the encoded string.
json.JSONDecoder().decode(json_data2)
done! Now we can get the results as JSON index with arabic value.
You have 2 options delete
and truncate
:
delete from mytable
This will delete all the content of the table, not reseting the autoincremental id, this process is very slow. If you want to delete specific records append a where clause at the end.
truncate myTable
This will reset the table i.e. all the auto incremental fields will be reset. Its a DDL and its very fast. You cannot delete any specific record through truncate
.
Use Paulo Freitas suggestion instead.
Until Laravel fixes this, you can run a standard database query after the Schema::create
have been run.
Schema::create("users", function($table){
$table->increments('id');
$table->string('email', 255);
$table->string('given_name', 100);
$table->string('family_name', 100);
$table->timestamp('joined');
$table->enum('gender', ['male', 'female', 'unisex'])->default('unisex');
$table->string('timezone', 30)->default('UTC');
$table->text('about');
});
DB::statement("ALTER TABLE ".DB::getTablePrefix()."users CHANGE joined joined TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL");
It worked wonders for me.
I have uninstalled the WampServer completelly, and deleted all files in /wamp folder, except www. This folder is preserved when uninstalling. After that I've installed it again and it works fine.
Important: This is helpful only in case when you already have your database backed up. All data from the database will be wiped out this way.
please refer http://complete-concrete-concise.com/web-tools/how-to-change-localhost-to-a-domain-name
this is best solution ever
Works and is simpler than every other solution I see here :
Pump().getPumps()
This is great if you don't need to reuse a class instance. Tested on Python 3.7.3.
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;
These are deprecated use the following..
// Connects to your Database
$link = mysqli_connect("localhost", "root", "", "");
and to insert data use the following
$sql = "INSERT INTO Table-Name (Column-Name)
VALUES ('$filename')" ;
try
CREATE TABLE [dbo].[Names]
(
[Name] [nvarchar](64) NOT NULL,
[CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [smalldatetime] NOT NULL
)
PS I think a smalldatetime is good enough. You may decide differently.
Can you not do this at the "moment of impact" ?
In Sql Server, this is common:
Update dbo.MyTable
Set
ColA = @SomeValue ,
UpdateDS = CURRENT_TIMESTAMP
Where...........
Sql Server has a "timestamp" datatype.
But it may not be what you think.
Here is a reference:
http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx
Here is a little RowVersion (synonym for timestamp) example:
CREATE TABLE [dbo].[Names]
(
[Name] [nvarchar](64) NOT NULL,
RowVers rowversion ,
[CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [datetime] NOT NULL
)
INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Update dbo.Names Set Name = Name
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Maybe a complete working example:
DROP TABLE [dbo].[Names]
GO
CREATE TABLE [dbo].[Names]
(
[Name] [nvarchar](64) NOT NULL,
RowVers rowversion ,
[CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [datetime] NOT NULL
)
GO
CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS
BEGIN
Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where
triggerInsertedTable.Name = myAlias.Name
END
GO
INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Matching on the "Name" value is probably not wise.
Try this more mainstream example with a SurrogateKey
DROP TABLE [dbo].[Names]
GO
CREATE TABLE [dbo].[Names]
(
SurrogateKey int not null Primary Key Identity (1001,1),
[Name] [nvarchar](64) NOT NULL,
RowVers rowversion ,
[CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [datetime] NOT NULL
)
GO
CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS
BEGIN
UPDATE dbo.Names
SET UpdateTS = CURRENT_TIMESTAMP
From dbo.Names myAlias
WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)
END
GO
INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Another great way of solving it while using a model is by using the values()
function.
def returnResponse(date):
response = ScheduledDate.objects.filter(date__startswith=date).values()
return Response(response)
I'd recommend using a regular expressions instead of string operations for this:
Set fso = CreateObject("Scripting.FileSystemObject")
filename = "C:\VBS\filediprova.txt"
newtext = vbLf & "<tr><td><a href=""..."">Beginning_of_DD_TC5</a></td></tr>"
Set re = New RegExp
re.Pattern = "(\n.*?Test Case \d)"
re.Global = False
re.IgnoreCase = True
text = f.OpenTextFile(filename).ReadAll
f.OpenTextFile(filename, 2).Write re.Replace(text, newText & "$1")
The regular expression will match a line feed (\n
) followed by a line containing the string Test Case
followed by a number (\d
), and the replacement will prepend that with the text you want to insert (variable newtext
). Setting re.Global = False
makes the replacement stop after the first match.
If the line breaks in your text file are encoded as CR-LF
(carriage return + line feed) you'll have to change \n
into \r\n
and vbLf
into vbCrLf
.
If you have to modify several text files, you could do it in a loop like this:
For Each f In fso.GetFolder("C:\VBS").Files
If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
text = f.OpenAsTextStream.ReadAll
f.OpenAsTextStream(2).Write re.Replace(text, newText & "$1")
End If
Next
It's worth noting that the QuerySet.values_list()
method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet
, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.
Somewhat irritatingly, though, this object has a custom __repr__
method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.
The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...
my_list = list(self.get_queryset().values_list('code', flat=True))
...then you can convert it to JSON with...
json_data = json.dumps(my_list)
You'll also have to place the resulting JSON data in an HttpResponse
object, which, apparently, should have a Content-Type
of application/json
, with...
response = HttpResponse(json_data, content_type='application/json')
...which you can then return from your function.
SELECT Salary,EmpName
FROM
(
SELECT Salary,EmpName,DENSE_RANK() OVER(ORDER BY Salary DESC) Rno from EMPLOYEE
) tbl
WHERE Rno=3
This line
except Vehicle.vehicledevice.device.DoesNotExist
means look for device instance for DoesNotExist exception, but there's none, because it's on class level, you want something like
except Device.DoesNotExist
If your file is really big try to use following formula: =A1 / 86400 + 25569
A1 should be replaced to what your need. Should work faster than =(((COLUMN_ID_HERE/60)/60)/24)+DATE(1970,1,1) cause of less number of calculations needed.
from django.http import JsonResponse
def SomeFunction(): dict1 = {}
obj = list( Mymodel.objects.values() )
dict1['data']=obj
return JsonResponse(dict1)
Try this code for Django
Use Integer.toString(tmpInt)
instead.
Concat gives the flexibility to join based on the axis( all rows or all columns)
Append is the specific case(axis=0, join='outer') of concat
Join is based on the indexes (set by set_index) on how variable =['left','right','inner','couter']
Merge is based on any particular column each of the two dataframes, this columns are variables on like 'left_on', 'right_on', 'on'
In the thread dump you can find the Line Number as below.
for the main thread which is currently running...
"main" #1 prio=5 os_prio=0 tid=0x0000000002120800 nid=0x13f4 runnable [0x0000000001d9f000]
java.lang.Thread.State: **RUNNABLE**
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:313)
at com.rana.samples.**HighCPUUtilization.main(HighCPUUtilization.java:17)**
But the thing is that the .chapter class is not dynamic you're declaring a height:1200px
so it's better to use background:cover and set with media queries specific height's for popular resolutions.
Because of the condition in while
, the loop might never break:
while (entry != null) {
// If entry never becomes null here, loop will never break.
}
Instead of the null
check there, you can try this:
ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
// Rest of your code
}
I remember one time when I stumbled upon this issue a few years ago, it's because windows don't have readline, therefore no interactive shell, to use php interactive mode without readline support, you can do this instead:
C:\>php -a
Interactive mode enabled
<?php
echo "Hello, world!";
?>
^Z
Hello, world!
After entering interactive mode, type using opening (<?php
) and closing (?>
) php tag, and end with control Z (^Z
) which denotes the end of file.
I also recall that I found the solution from php's site user comment: http://www.php.net/manual/en/features.commandline.interactive.php#105729
You close the second Scanner
which closes the underlying InputStream
, therefore the first Scanner
can no longer read from the same InputStream
and a NoSuchElementException
results.
The solution: For console apps, use a single Scanner
to read from System.in
.
Aside: As stated already, be aware that Scanner#nextInt
does not consume newline characters. Ensure that these are consumed before attempting to call nextLine
again by using Scanner#newLine()
.
See: Do not create multiple buffered wrappers on a single InputStream
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
The argument order seems to matter... to exclude subdirectories, I used
robocopy \\source\folder C:\destinationfolder /XD * /MIR
...and that works for me (Windows 10 copy from Windows Server 2016)
To delete all objects in a list, you can directly write list = []
Here is example:
>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a = []
>>> a
[]
I think you are a little messed up with what you doing. Athlete is an object, athlete has a name, i has a city where he lives. Athlete can dive.
public class Athlete {
private String name;
private String city;
public Athlete (String name, String city){
this.name = name;
this.city = city;
}
--create method dive, (i am not sure what exactly i has to do)
public void dive (){}
}
public class Main{
public static void main (String [] args){
String name = in.next(); //enter name from keyboad
String city = in.next(); //enter city form keybord
--create a new object athlete and pass paramenters name and city into the object
Athlete a = new Athlete (name, city);
}
}
If you try to call requestFocus()
before layout is inflated, it will return false. This code runs after layout get inflated. You don't need 200 ms delay as mentioned above.
editText.post(Runnable {
if(editText.requestFocus()) {
val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
imm?.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0)
}
})
you need to edit the "c:\Program Files\wamp\bin\php\php5.3.13\php.ini" file search for: ;extension=php_openssl.dll
remove the semicolon at the beginning
note: if saving the file doesn't work then you need to edit it as administrator. (on win7) go to start menu, search for notepad, right-click on notepad, click "Run As Administrator"
in the composer installation windows just click back then next (or close it and start again) and it should work
This error can also occur if you accidentally use commas instead of AND
in the ON
clause of a JOIN
:
JOIN joined_table ON (joined_table.column = table.column, joined_table.column2 = table.column2)
^
should be AND, not a comma
select age(timestamp_A, timestamp_B)
Answering to Igor's comment:
select age('2013-02-28 11:01:28'::timestamp, '2011-12-31 11:00'::timestamp);
age
-------------------------------
1 year 1 mon 28 days 00:01:28
I had a similar problem which I solved by changing the Port Settings in the port driver (located in Ports in device manager) to fit the device I was using.
For me it was that wrong Bits per second value was set.
Usually the problem is not closing brackets (}) or missing semicolon (;)
def updateJsonFile():
jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
data = json.load(jsonFile) # Read the JSON into the buffer
jsonFile.close() # Close the JSON file
## Working with buffered content
tmp = data["location"]
data["location"] = path
data["mode"] = "replay"
## Save our changes to JSON file
jsonFile = open("replayScript.json", "w+")
jsonFile.write(json.dumps(data))
jsonFile.close()
SQL Server doesn't support the SQL standard interval data type. Your best bet is to calculate the difference in seconds, and use a function to format the result. The native function CONVERT() might appear to work fine as long as your interval is less than 24 hours. But CONVERT() isn't a good solution for this.
create table test (
id integer not null,
ts datetime not null
);
insert into test values (1, '2012-01-01 08:00');
insert into test values (1, '2012-01-01 09:00');
insert into test values (1, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 10:30');
insert into test values (2, '2012-01-01 09:00');
insert into test values (3, '2012-01-01 09:00');
insert into test values (3, '2012-01-02 12:00');
Values were chosen in such a way that for
This SELECT statement includes one column that calculates seconds, and one that uses CONVERT() with subtraction.
select t.id,
min(ts) start_time,
max(ts) end_time,
datediff(second, min(ts),max(ts)) elapsed_sec,
convert(varchar, max(ts) - min(ts), 108) do_not_use
from test t
group by t.id;
ID START_TIME END_TIME ELAPSED_SEC DO_NOT_USE
1 January, 01 2012 08:00:00 January, 01 2012 09:00:00 3600 01:00:00
2 January, 01 2012 08:30:00 January, 01 2012 10:30:00 7200 02:00:00
3 January, 01 2012 09:00:00 January, 02 2012 12:00:00 97200 03:00:00
Note the misleading "03:00:00" for the 27-hour difference on id number 3.
On a Scientific Linux 6.7 system, the man page on rsync says:
--ignore-times don't skip files that match size and time
I have two files with identical contents, but with different creation dates:
[root@windstorm ~]# ls -ls /tmp/master/usercron /tmp/new/usercron
4 -rwxrwx--- 1 root root 1595 Feb 15 03:45 /tmp/master/usercron
4 -rwxrwx--- 1 root root 1595 Feb 16 04:52 /tmp/new/usercron
[root@windstorm ~]# diff /tmp/master/usercron /tmp/new/usercron
[root@windstorm ~]# md5sum /tmp/master/usercron /tmp/new/usercron
368165347b09204ce25e2fa0f61f3bbd /tmp/master/usercron
368165347b09204ce25e2fa0f61f3bbd /tmp/new/usercron
With --size-only
, the two files are regarded the same:
[root@windstorm ~]# rsync -v --size-only -n /tmp/new/usercron /tmp/master/usercron
sent 29 bytes received 12 bytes 82.00 bytes/sec
total size is 1595 speedup is 38.90 (DRY RUN)
With --ignore-times
, the two files are regarded different:
[root@windstorm ~]# rsync -v --ignore-times -n /tmp/new/usercron /tmp/master/usercron
usercron
sent 32 bytes received 15 bytes 94.00 bytes/sec
total size is 1595 speedup is 33.94 (DRY RUN)
So it does not looks like --ignore-times
has any effect at all.
I face this error on testing WebAPI in Postman tool.
After building the code, If we remove any line (For Example: In my case when I remove one Commented line this error was occur...) in debugging mode then the "Non-static method requires a target" error will occur.
Again, I tried to send the same request. This time code working properly. And I get the response properly in Postman.
I hope it will use to someone...
Please find example below, it might help you
package jersey.rest.test;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@Path("/hello")
public class SimpleService {
@GET
@Path("/{param}")
public Response getMsg(@PathParam("param") String msg) {
String output = "Get:Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
@POST
@Path("/{param}")
public Response postMsg(@PathParam("param") String msg) {
String output = "POST:Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
@POST
@Path("/post")
//@Consumes(MediaType.TEXT_XML)
public Response postStrMsg( String msg) {
String output = "POST:Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
@PUT
@Path("/{param}")
public Response putMsg(@PathParam("param") String msg) {
String output = "PUT: Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
@DELETE
@Path("/{param}")
public Response deleteMsg(@PathParam("param") String msg) {
String output = "DELETE:Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
@HEAD
@Path("/{param}")
public Response headMsg(@PathParam("param") String msg) {
String output = "HEAD:Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
}
for testing you can use any tool like RestClient (http://code.google.com/p/rest-client/)
To get just a correct number of dimensions in NumPy:
len(a.shape)
In the first case:
import numpy as np
a = np.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
print("shape = ",np.shape(a))
print("dimensions = ",len(a.shape))
The output will be:
shape = (2, 2, 3)
dimensions = 3
Go via POSIXct
and you want to set a TZ
there -- here you see my (Chicago) default:
R> val <- 1352068320
R> as.POSIXct(val, origin="1970-01-01")
[1] "2012-11-04 22:32:00 CST"
R> as.Date(as.POSIXct(val, origin="1970-01-01"))
[1] "2012-11-05"
R>
Edit: A few years later, we can now use the anytime package:
R> library(anytime)
R> anytime(1352068320)
[1] "2012-11-04 16:32:00 CST"
R> anydate(1352068320)
[1] "2012-11-04"
R>
Note how all this works without any format or origin arguments.
Try this command, it will help you to get ipaddress
adb shell ifconfig tiwlan0
tiwlan0 is the name of the wi-fi network interface on the device. This is generic command for getting ipaddress,
adb shell netcfg
It will output like this
usb0 DOWN 0.0.0.0 0.0.0.0 0×00001002
sit0 DOWN 0.0.0.0 0.0.0.0 0×00000080
ip6tnl0 DOWN 0.0.0.0 0.0.0.0 0×00000080
gannet0 DOWN 0.0.0.0 0.0.0.0 0×00001082
rmnet0 UP 112.79.87.220 255.0.0.0 0x000000c1
rmnet1 DOWN 0.0.0.0 0.0.0.0 0×00000080
rmnet2 DOWN 0.0.0.0 0.0.0.0 0×00000080
You are right, that test
"and"s the two operands. But the result is discarded, the only thing that stays, and thats the important part, are the flags. They are set and thats the reason why the test
instruction is used (and exist).
JE
jumps not when equal (it has the meaning when the instruction before was a comparison), what it really does, it jumps when the ZF
flag is set. And as it is one of the flags that is set by test
, this instruction sequence (test x,x; je...) has the meaning that it is jumped when x is 0.
For questions like this (and for more details) I can just recommend a book about x86 instruction, e.g. even when it is really big, the Intel documentation is very good and precise.
I tried the accepted solution of using the Invoke-Expression cmdlet but it didn't work for me because my arguments had spaces on them. I tried to parse the arguments and escape the spaces but I couldn't properly make it work and also it was really a dirty work around in my opinion. So after some experimenting, my take on the problem is this:
function Invoke-Script
{
param
(
[Parameter(Mandatory = $true)]
[string]
$Script,
[Parameter(Mandatory = $false)]
[object[]]
$ArgumentList
)
$ScriptBlock = [Scriptblock]::Create((Get-Content $Script -Raw))
Invoke-Command -NoNewScope -ArgumentList $ArgumentList -ScriptBlock $ScriptBlock -Verbose
}
# example usage
Invoke-Script $scriptPath $argumentList
The only drawback of this solution is that you need to make sure that your script doesn't have a "Script" or "ArgumentList" parameter.
I tried this DB insert method, but as it does not use the model, it ignored a sluggable trait I had on the model. So, given the Model for this table exists, as soon as its migrated, I figured the model would be available to use to insert data. And I came up with this:
public function up() {
Schema::create('parent_categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug');
$table->timestamps();
});
ParentCategory::create(
[
'id' => 1,
'name' => 'Occasions',
],
);
}
This worked correctly, and also took into account the sluggable trait on my Model to automatically generate a slug for this entry, and uses the timestamps too. NB. Adding the ID was no neccesary, however, I wanted specific IDs for my categories in this example. Tested working on Laravel 5.8
I didn't find it listed so updating the list.
You need to have the apk installed and running in front on your phone for this solution:
Windows CMD line:
adb shell dumpsys window windows | findstr <any unique string from your pkg Name>
Linux Terminal:
adb shell dumpsys window windows | grep -i <any unique string from your Pkg Name>
OUTPUT for Calculator package would be:
Window #7 Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}:
mOwnerUid=10036 mShowToOwnerOnly=true package=com.android.calculator2 appop=NONE
mToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}
mRootToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}
mAppToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}
WindowStateAnimator{3e160d22 com.android.calculator2/com.android.calculator2.Calculator}:
mSurface=Surface(name=com.android.calculator2/com.android.calculator2.Calculator)
mCurrentFocus=Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}
mFocusedApp=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}
Main part is, First Line:
Window #7 Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}:
First part of the output is package name:
com.android.calculator2
Second Part of output (which is after /
) can be two things, in our case its:
com.android.calculator2.Calculator
<PKg name>.<activity name>
=
<com.android.calculator2>.<Calculator>
so .Calculator
is our activity
If second part is entirely different from Package name and doesn't seem to contain pkg name which was before /
in out output, then entire
second part can be used as main activity.
You can try with this code
var result = (from item in List
select new
{
EmpLoc = item.empLoc,
EmpPL= item.empPL,
EmpShift= item.empShift
})
.ToList()
.Distinct();
I deleted the "Temporary ASP.NET Files" folder and my localhost page load improved dramatically. Here is the path... %temp%\Temporary ASP.NET Files\
You can open the Windows event viewer to try to get more information about the errors : in the "Application" section of the Windows logs, there is a good chance you will find error messages from Apache. (At least I found what was wrong in my case there !)
You can use MD5 hash function to check if two files are the same, with this you can not see the differences in a low level, but is a quick way to compare two files.
md5 <filename1>
md5 <filename2>
If both MD5 hashes (the command output) are the same, then, the two files are not different.
I convert arguments
to Array using Array.prototype.slice
so that I can concat
with another Array of what I want to add, then pass it into console.log.apply(console, /*here*/)
;
var log = function () {
return console.log.apply(
console,
['['+new Date().toISOString().slice(11,-5)+']'].concat(
Array.prototype.slice.call(arguments)
)
);
};
log(['foo']); // [18:13:17] ["foo"]
It seems that arguments
can be Array.prototype.unshift
ed too, but I don't know if modifying it like this is a good idea/will have other side effects
var log = function () {
Array.prototype.unshift.call(
arguments,
'['+new Date().toISOString().slice(11,-5)+']'
);
return console.log.apply(console, arguments);
};
log(['foo']); // [18:13:39] ["foo"]
MultiMarkdown 4.7 has a {{TOC}} macro that inserts a table of contents.
You have Numpy Data Type, Just change to normal int()
or float()
data type. it will work fine.
Method1:
Inline elements do not use any width or height you specify. To avoid two div and use like this:
<div id="container">
<img src="tree.png" align="left"/>
<h1> A very long text(about 300 words) </h1>
</div>
<style>
img {
display: inline;
width: 100px;
height: 100px;
}
h1 {
display: inline;
}
</style>
Method2:
Change your CSS as follows
.container div {
display: inline-block;
}
Method3:
It is the simple method set width Try the following css:
.container div {
overflow:hidden;
position:relative;
width:90%;
margin-bottom:20px;
margin-top:20px;
margin-left:auto;
margin-right:auto;
}
.image {
width:70%;
display: inline-block;
float: left;
}
.texts {
height: auto;
width: 30%;
display: inline;
}
It seems to me, that it is by design that this file is empty.
A similar question has been asked here: https://stackoverflow.com/questions/2567432/ubuntu-apache-httpd-conf-or-apache2-conf
So, you should have a look for /etc/apache2/apache2.conf
I've posted here some methods to convert interval to nanoseconds and nanoseconds to interval. These methods have a nanosecond precision.
You just need to adjust it to get milliseconds instead of nanoseconds.
A shorter method to convert interval to nanoseconds.
SELECT (EXTRACT(DAY FROM (
INTERVAL '+18500 09:33:47.263027' DAY(5) TO SECOND --Replace line with desired interval --Maximum value: INTERVAL '+694444 10:39:59.999999999' DAY(6) TO SECOND(9) or up to 3871 year
) * 24 * 60) * 60 + EXTRACT(SECOND FROM (
INTERVAL '+18500 09:33:47.263027' DAY(5) TO SECOND --Replace line with desired interval
))) * 100 AS MILLIS FROM DUAL;
MILLIS
1598434427263.027
You need to add a name
attribute.
Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3
.
In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]
) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.
Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs
For PHP you can use:
<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">
I'd like to offer an alternative that appears to perform at least 10% faster than craigdfrench's answer in my tests (.NET 4.7.2):
public static string GetMD5Hash(string text)
{
using ( var md5 = MD5.Create() )
{
byte[] computedHash = md5.ComputeHash( Encoding.UTF8.GetBytes(text) );
return new System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary(computedHash).ToString();
}
}
If you prefer to have using System.Runtime.Remoting.Metadata.W3cXsd2001;
at the top, the method body can be made an easier to read one-liner:
using ( var md5 = MD5.Create() )
{
return new SoapHexBinary( md5.ComputeHash( Encoding.UTF8.GetBytes(text) ) ).ToString();
}
Obvious enough, but for completeness, in OP's context it would be used as:
sSourceData = "MySourceData";
tmpHash = GetMD5Hash(sSourceData);
According to official Android information about dumpsys:
The dumpsys tool runs on the device and provides information about the status of system services.
To get a list of available services use
adb shell dumpsys -l
I wrote a class to normalize the data in my dictionary. The 'element' in the NormalizeData class below, needs to be of dict type. And you need to replace in the __iterate() with either your custom class object or any other object type that you would like to normalize.
class NormalizeData:
def __init__(self, element):
self.element = element
def execute(self):
if isinstance(self.element, dict):
self.__iterate()
else:
return
def __iterate(self):
for key in self.element:
if isinstance(self.element[key], <ClassName>):
self.element[key] = str(self.element[key])
node = NormalizeData(self.element[key])
node.execute()
The order of a dictionary doesn't have any relationship to the order it was defined in. This is true of all dictionaries, not just those turned into JSON.
>>> {"b": 1, "a": 2}
{'a': 2, 'b': 1}
Indeed, the dictionary was turned "upside down" before it even reached json.dumps
:
>>> {"id":1,"name":"David","timezone":3}
{'timezone': 3, 'id': 1, 'name': 'David'}
I'm facing this problem in a TYPO3 website, where all "Content Elements" are wrapped with something like:
<div id="c1234" class="contentElement">...</div>
and i changed the rendering so it renders like this:
<div id="c1234" class="anchor"></div>
<div class="contentElement">...</div>
And this CSS:
.anchor{
position: relative;
top: -50px;
}
The fixed topbar being 40px high, now the anchors work again and start 10px under the topbar.
Only drawback of this technique is you can no longer use :target
.
JSON is not really meant for serializing arbitrary Python objects. It's great for serializing dict
objects, but the pickle
module is really what you should be using in general. Output from pickle
is not really human-readable, but it should unpickle just fine. If you insist on using JSON, you could check out the jsonpickle
module, which is an interesting hybrid approach.
The ConnectTimeout option allows you to tell your ssh client how long you're willing to wait for a connection before returning an error. By setting ConnectTimeout to 1, you're effectively saying "try for at most 1 second and then fail if you haven't connected yet".
The problem is that when you connect by name, the DNS lookup can take several seconds. Connecting by IP address is much faster, and may actually work in one second or less. What sinelaw is experiencing is that every attempt to connect by DNS name is failing to occur within one second. The default setting of ConnectTimeout defers to the linux kernel connect timeout, which is usually pretty long.
$unixtime_to_date = date('jS F Y h:i:s A (T)', $unixtime);
This should work to.
WAMP Server may turn orange for various reason as it is not working. This is also a another type of issue. that can be due to webservices is running in services.msc This is explained in the below blog. Please try it. How to resolve HTTP Error 404 and launch localhost with WAMP Server for PHP & MySql?
Checkout Xdebbug's var_dump settings, particularly the values of these settings:
xdebug.var_display_max_children
xdebug.var_display_max_data
xdebug.var_display_max_depth
If you are not allowed to use C++'s string class (which is terrible teaching C++ imho), a raw, safe array version would look something like this.
#include <cstring>
#include <iostream>
int main()
{
char array1[] ="The dog jumps ";
char array2[] = "over the log";
char * newArray = new char[std::strlen(array1)+std::strlen(array2)+1];
std::strcpy(newArray,array1);
std::strcat(newArray,array2);
std::cout << newArray << std::endl;
delete [] newArray;
return 0;
}
This assures you have enough space in the array you're doing the concatenation to, without assuming some predefined MAX_SIZE
. The only requirement is that your strings are null-terminated, which is usually the case unless you're doing some weird fixed-size string hacking.
Edit, a safe version with the "enough buffer space" assumption:
#include <cstring>
#include <iostream>
int main()
{
const unsigned BUFFER_SIZE = 50;
char array1[BUFFER_SIZE];
std::strncpy(array1, "The dog jumps ", BUFFER_SIZE-1); //-1 for null-termination
char array2[] = "over the log";
std::strncat(array1,array2,BUFFER_SIZE-strlen(array1)-1); //-1 for null-termination
std::cout << array1 << std::endl;
return 0;
}
Another way to navigate to the location of a function definition would be to break in debugger somewhere you can access the function and enter the functions fully qualified name in the console. This will print the function definition in the console and give a link which on click opens the script location where the function is defined.
Just refrain from catching the exception and the traceback that Python prints will tell you what exception occurred.
tmpColumnsSQL = ("show columns in dim.date_dim")
hiveCursor.execute(tmpColumnsSQL)
columnlist = hiveCursor.fetchall()
for columns in jayscolumnlist:
print columns[0]
for i in range(len(jayscolumnlist)):
print columns[i][0])
The easiest way of getting UTC time in a conventional format is as follows:
new Date().toISOString()
"2016-06-03T23:15:33.008Z"
datetime.datetime.fromtimestamp()
is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp()
expects Unix timestamp, in seconds.
Do it like that:
>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)
and the result is:
>>> date
datetime.datetime(2012, 3, 16, 1, 0)
Does it answer your question?
EDIT: J.F. Sebastian correctly suggested to use true division by 1e3
(float 1000
). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int
when dividing (using /
operator) int
by int
(this is called floor division). By replacing the divisor 1000
(being an int
) with the 1e3
divisor (being representation of 1000
as float) or with float(1000)
(or 1000.
etc.), the division becomes true division. Python 2.x returns float
when dividing int
by float
, float
by int
, float
by float
etc. And when there is some fractional part in the timestamp passed to fromtimestamp()
method, this method's result also contains information about that fractional part (as the number of microseconds).
The better way is:
url = "http://xxx.xxxx.xx"
data = {
"cardno": "6248889874650987",
"systemIdentify": "s08",
"sourceChannel": 12
}
resp = requests.post(url, json=data)
The Z stands for 'Zulu' - your times are in UTC. From Wikipedia:
The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time. This is especially true in aviation, where Zulu is the universal standard.
I don't think there is a way to ignore adding DEFINER
s to the dump. But there are ways to remove them after the dump file is created.
Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost
with an empty string ""
Edit the dump (or pipe the output) using perl
:
perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
Your data is poorly formed. The value fields in particular have numerous spaces and new lines. Automated formatters won't work on this, as they will not modify the actual data. As you generate the data for output, filter it as needed to avoid the spaces.
Apple already includes a DEBUG
flag in debug builds, so you don't need to define your own.
You might also want to consider just redefining NSLog
to a null operation when not in DEBUG
mode, that way your code will be more portable and you can just use regular NSLog
statements:
//put this in prefix.pch
#ifndef DEBUG
#undef NSLog
#define NSLog(args, ...)
#endif
You need to use to_timestamp()
to convert your string to a proper timestamp
value:
to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
If your column is of type DATE
(which also supports seconds), you need to use to_date()
to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
To get this into a where
condition use the following:
select *
from TableA
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')
You never need to use to_timestamp()
on a column that is of type timestamp
.
Below are two methods that are superior to looping. Both handle a "no-find" case.
VLOOKUP
with error-handling if the variable doesn't exist (INDEX/MATCH
may be a better route than VLOOKUP
, ie if your two columns A and B were in reverse order, or were far apart)VBAs FIND
method (matching a whole string in column A given I use the xlWhole
argument)
Sub Method1()
Dim strSearch As String
Dim strOut As String
Dim bFailed As Boolean
strSearch = "trees"
On Error Resume Next
strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
If Err.Number <> 0 Then bFailed = True
On Error GoTo 0
If Not bFailed Then
MsgBox "corresponding value is " & vbNewLine & strOut
Else
MsgBox strSearch & " not found"
End If
End Sub
Sub Method2()
Dim rng1 As Range
Dim strSearch As String
strSearch = "trees"
Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
Else
MsgBox strSearch & " not found"
End If
End Sub
the question is a little confused. timestamps are not UTC - they're a Unix thing. the date might be UTC? assuming it is, and if you're using Python 3.2+, simple-date makes this trivial:
>>> SimpleDate(date(2011,1,1), tz='utc').timestamp
1293840000.0
if you actually have the year, month and day you don't need to create the date
:
>>> SimpleDate(2011,1,1, tz='utc').timestamp
1293840000.0
and if the date is in some other timezone (this matters because we're assuming midnight without an associated time):
>>> SimpleDate(date(2011,1,1), tz='America/New_York').timestamp
1293858000.0
[the idea behind simple-date is to collect all python's date and time stuff in one consistent class, so you can do any conversion. so, for example, it will also go the other way:
>>> SimpleDate(1293858000, tz='utc').date
datetime.date(2011, 1, 1)
]
I took Michael Berkowski's answer a step (or two) farther and created a more flexible function allowing any lookup field and any target field. For fun I threw splat (*) capability in there incase someone might want to do a replace all. jQuery is NOT needed. checkAllRows allows the option to break from the search on found for performance or the previously mentioned replace all.
function setVal(update) {
/* Included to show an option if you care to use jQuery
var defaults = { jsonRS: null, lookupField: null, lookupKey: null,
targetField: null, targetData: null, checkAllRows: false };
//update = $.extend({}, defaults, update); */
for (var i = 0; i < update.jsonRS.length; i++) {
if (update.jsonRS[i][update.lookupField] === update.lookupKey || update.lookupKey === '*') {
update.jsonRS[i][update.targetField] = update.targetData;
if (!update.checkAllRows) { return; }
}
}
}
var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
{'Id':'2','Username':'Steve','FatherName':'Johnson'},
{'Id':'3','Username':'Albert','FatherName':'Einstein'}]
With your data you would use like:
var update = {
jsonRS: jsonObj,
lookupField: "Id",
lookupKey: 2,
targetField: "Username",
targetData: "Thomas",
checkAllRows: false
};
setVal(update);
And Bob's your Uncle. :) [Works great]
You need NGNIX or Apache HTTP server as a proxy server for forwarding http requests to appropriate application -> which listens particular port (or do it with CNAME which provides Hosting company). It is most powerful solution and this is just a really easy way to keep adding new subdomains, or to add new domains automatically when DNS records are pointed at the server.
Apache era call it Virtual host -> httpd.apache.org/docs/trunk/vhosts/examples.html
NGINX -> Server Block https://www.nginx.com/resources/wiki/start/topics/examples/server_blocks/
CharMatcher.retainFrom
can be used, if you're using the Google Guava library:
String s = "A função";
String stripped = CharMatcher.ascii().retainFrom(s);
System.out.println(stripped); // Prints "A funo"
Press ESC to first go into command mode
. Then Press Shift+D.
If you need just quick dump and don't want to implement custom encoder. You can use the following:
json_string = json.dumps(data, iterable_as_array=True)
This will convert all sets (and other iterables) into arrays. Just beware that those fields will stay arrays when you parse the json back. If you want to preserve the types, you need to write custom encoder.
for i in count:
means for i in 7:
, which won't work. The bit after the in
should be of an iterable type, not a number. Try this:
for i in range(count):
This is flask.jsonify()
def jsonify(*args, **kwargs):
if __debug__:
_assert_have_json()
return current_app.response_class(json.dumps(dict(*args, **kwargs),
indent=None if request.is_xhr else 2), mimetype='application/json')
The json
module used is either simplejson
or json
in that order. current_app
is a reference to the Flask()
object i.e. your application. response_class()
is a reference to the Response()
class.
I haven't been able to get it to work without specifying a width but the following css worked
.wrapper {
background: #DDD;
padding: 10px;
display: inline-block;
height: 20px;
width: auto;
}
.contents {
background: #c3c;
overflow: hidden;
white-space: nowrap;
display: inline-block;
visibility: hidden;
width: 1px;
-webkit-transition: width 1s ease-in-out, visibility 1s linear;
-moz-transition: width 1s ease-in-out, visibility 1s linear;
-o-transition: width 1s ease-in-out, visibility 1s linear;
transition: width 1s ease-in-out, visibility 1s linear;
}
.wrapper:hover .contents {
width: 200px;
visibility: visible;
}
I'm not sure you will be able to get it working without setting a width on it.
For URL or file, use json.load()
. For string with .json content, use json.loads()
.
#! /usr/bin/python
import json
# from pprint import pprint
json_file = 'my_cube.json'
cube = '1'
with open(json_file) as json_data:
data = json.load(json_data)
# pprint(data)
print "Dimension: ", data['cubes'][cube]['dim']
print "Measures: ", data['cubes'][cube]['meas']
Other answers cover why parameters are important, but there is a downside! In .net, there are several methods for creating parameters (Add, AddWithValue), but they all require you to worry, needlessly, about the parameter name, and they all reduce the readability of the SQL in the code. Right when you're trying to meditate on the SQL, you need to hunt around above or below to see what value has been used in the parameter.
I humbly claim my little SqlBuilder class is the most elegant way to write parameterized queries. Your code will look like this...
C#
var bldr = new SqlBuilder( myCommand );
bldr.Append("SELECT * FROM CUSTOMERS WHERE ID = ").Value(myId);
//or
bldr.Append("SELECT * FROM CUSTOMERS WHERE NAME LIKE ").FuzzyValue(myName);
myCommand.CommandText = bldr.ToString();
Your code will be shorter and much more readable. You don't even need extra lines, and, when you're reading back, you don't need to hunt around for the value of parameters. The class you need is here...
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
public class SqlBuilder
{
private StringBuilder _rq;
private SqlCommand _cmd;
private int _seq;
public SqlBuilder(SqlCommand cmd)
{
_rq = new StringBuilder();
_cmd = cmd;
_seq = 0;
}
public SqlBuilder Append(String str)
{
_rq.Append(str);
return this;
}
public SqlBuilder Value(Object value)
{
string paramName = "@SqlBuilderParam" + _seq++;
_rq.Append(paramName);
_cmd.Parameters.AddWithValue(paramName, value);
return this;
}
public SqlBuilder FuzzyValue(Object value)
{
string paramName = "@SqlBuilderParam" + _seq++;
_rq.Append("'%' + " + paramName + " + '%'");
_cmd.Parameters.AddWithValue(paramName, value);
return this;
}
public override string ToString()
{
return _rq.ToString();
}
}
This is how I end up doing it. This will not cover all formats. You have to adjust accordingly. I have control on the format, so it works for me
function isValidDate(s) {
var dt = "";
var bits = [];
if (s && s.length >= 6) {
if (s.indexOf("/") > -1) {
bits = s.split("/");
}
else if (s.indexOf("-") > -1) {
bits = s.split("-");
}
else if (s.indexOf(".") > -1) {
bits = s.split(".");
}
try {
dt = new Date(bits[2], bits[0] - 1, bits[1]);
} catch (e) {
return false;
}
return (dt.getMonth() + 1) === parseInt(bits[0]);
} else {
return false;
}
}
From the documentation here: https://trac.ffmpeg.org/wiki/Concatenate
If you have MP4 files, these could be losslessly concatenated by first transcoding them to MPEG-2 transport streams. With H.264 video and AAC audio, the following can be used:
ffmpeg -i input1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts intermediate1.ts
ffmpeg -i input2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts intermediate2.ts
ffmpeg -i "concat:intermediate1.ts|intermediate2.ts" -c copy -bsf:a aac_adtstoasc output.mp4
This approach works on all platforms.
I needed the ability to encapsulate this in a cross platform script, so I used fluent-ffmpeg
and came up with the following solution:
const unlink = path =>
new Promise((resolve, reject) =>
fs.unlink(path, err => (err ? reject(err) : resolve()))
)
const createIntermediate = file =>
new Promise((resolve, reject) => {
const out = `${Math.random()
.toString(13)
.slice(2)}.ts`
ffmpeg(file)
.outputOptions('-c', 'copy', '-bsf:v', 'h264_mp4toannexb', '-f', 'mpegts')
.output(out)
.on('end', () => resolve(out))
.on('error', reject)
.run()
})
const concat = async (files, output) => {
const names = await Promise.all(files.map(createIntermediate))
const namesString = names.join('|')
await new Promise((resolve, reject) =>
ffmpeg(`concat:${namesString}`)
.outputOptions('-c', 'copy', '-bsf:a', 'aac_adtstoasc')
.output(output)
.on('end', resolve)
.on('error', reject)
.run()
)
names.map(unlink)
}
concat(['file1.mp4', 'file2.mp4', 'file3.mp4'], 'output.mp4').then(() =>
console.log('done!')
)
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
I just came back to this issue after a while, and decided to publish a plugin based on the answer by Aaron Mast.
https://www.npmjs.com/package/mongoose-recursive-upsert
Use it as a mongoose plugin. It sets up a static method which will recursively merge the object passed in.
Model.upsert({unique: 'value'}, updateObject});
Check out the manual: http://www.php.net/manual/en/datetime.format.php
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Will output: 2000-01-01 00:00:00
3 steps:
Check the sorce code (HTML) of YouTube, you'll get the link like this (http%253A%252F%252Fo-o.preferred.telemar-cnf1.v18.lscache6.c.youtube.com%252Fvideoplayback ...);
Decode the url (remove the codes %2B,%25 etc), create a decoder with the codes: http://www.w3schools.com/tags/ref_urlencode.asp and use the function Uri.decode(url) to replace invalid escaped octets;
Use the code to download stream:
URL u = null;
InputStream is = null;
try {
u = new URL(url);
is = u.openStream();
HttpURLConnection huc = (HttpURLConnection)u.openConnection(); //to know the size of video
int size = huc.getContentLength();
if(huc != null) {
String fileName = "FILE.mp4";
String storagePath = Environment.getExternalStorageDirectory().toString();
File f = new File(storagePath,fileName);
FileOutputStream fos = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int len1 = 0;
if(is != null) {
while ((len1 = is.read(buffer)) > 0) {
fos.write(buffer,0, len1);
}
}
if(fos != null) {
fos.close();
}
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(is != null) {
is.close();
}
} catch (IOException ioe) {
// just going to ignore this one
}
}
That's all, most of stuff you'll find on the web!!!
This is working fine for me
I have add dependency
compile 'commons-codec:commons-codec:1.9'
ref: http://mvnrepository.com/artifact/commons-codec/commons-codec/1.9
my function
public String encode(String key, String data) {
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
return new String(Hex.encodeHex(sha256_HMAC.doFinal(data.getBytes("UTF-8"))));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
Update based on latest Android documentation (March 2017):
When you get this type of error:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:374)
at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:209)
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
the issue could be one of the following:
The solution is to teach HttpsURLConnection
to trust a specific set of CAs. How? Please check https://developer.android.com/training/articles/security-ssl.html#CommonProblems
Others who are using AsyncHTTPClient
from com.loopj.android:android-async-http
library, please check Setup AsyncHttpClient to use HTTPS.
It is n for next and N for previous.
And if you use reverse search with ?
(for example, ?cake
) instead of /
, it is the other way round.
If it is installed on your system, you should try to run vimtutor
command from your terminal, which will start a tutorial of the basic Vim commands.
Rob Wells advice about * and # is also very pertinent.
If the goal is to randomly shuffle each column, some of the above answers don't work since the columns are shuffled jointly (this preserves inter-column correlations). Others require installing a package. Yet a one-liner exist:
df2 = lapply(df1, function(x) { sample(x) })
The ALL_DIRECTORIES
data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
There's also a pretty handy tool called binwalk, written in python, which provides for binary pattern matching (and quite a lot more besides). Here's how you would search for a binary string, which outputs the offset in decimal and hex (from the docs):
$ binwalk -R "\x00\x01\x02\x03\x04" firmware.bin
DECIMAL HEX DESCRIPTION
--------------------------------------------------------------------------
377654 0x5C336 Raw string signature
Follow the tutorial you listed above for setting up your key preferences in iterm2.
you can use
var FirstString = YourString.Split().First();
to split string .
Here is an example that should help. If you have a timestamp with a timezone, you can convert that timestamp into any other timezone. If you haven't got a base timezone it won't be converted correctly.
SELECT now(),
now()::timestamp,
now() AT TIME ZONE 'CST',
now()::timestamp AT TIME ZONE 'CST'
Output:
-[ RECORD 1 ]---------------------------
now | 2018-09-15 17:01:36.399357+03
now | 2018-09-15 17:01:36.399357
timezone | 2018-09-15 08:01:36.399357
timezone | 2018-09-16 02:01:36.399357+03
You need to add in the seconds, too:
unsigned long time_in_micros = 1000000 * tv.tv_sec + tv.tv_usec;
Note that this will only last for about 232/106 =~ 4295 seconds, or roughly 71 minutes though (on a typical 32-bit system).
In my case the files were appeared as modified after changing the files permissions.
To make git ignore permission changes, do the following :
# For the current repository
git config core.filemode false
# Globally
git config --global core.filemode false
I used Mercury/32 and Pegasus Mail to get the mail() functional. It works great too as a mail server if you want an email address ending with your domain name.
Look for assigning the output to Clipboard (in your first script) and then in second script parse Clipboard value.
The best solution I found this to work for me guys after trying all the other solutions.... Basically i set the sScrollX to 200% then set the individual column widths to the required % that I wanted. The more columns that you have and the more space that you require then you need to raise the sScrollX %... The null means that I want those columns to retain the datatables auto width they have set in their code.
$('#datatables').dataTable
({
"sScrollX": "200%", //This is what made my columns increase in size.
"bScrollCollapse": true,
"sScrollY": "320px",
"bAutoWidth": false,
"aoColumns": [
{ "sWidth": "10%" }, // 1st column width
{ "sWidth": "null" }, // 2nd column width
{ "sWidth": "null" }, // 3rd column width
{ "sWidth": "null" }, // 4th column width
{ "sWidth": "40%" }, // 5th column width
{ "sWidth": "null" }, // 6th column width
{ "sWidth": "null" }, // 7th column width
{ "sWidth": "10%" }, // 8th column width
{ "sWidth": "10%" }, // 9th column width
{ "sWidth": "40%" }, // 10th column width
{ "sWidth": "null" } // 11th column width
],
"bPaginate": true,
"sDom": '<"H"TCfr>t<"F"ip>',
"oTableTools":
{
"aButtons": [ "copy", "csv", "print", "xls", "pdf" ],
"sSwfPath": "copy_cvs_xls_pdf.swf"
},
"sPaginationType":"full_numbers",
"aaSorting":[[0, "desc"]],
"bJQueryUI":true
});
I won't make such a big deal from this question.
It's not like choosing your new wife or car.
I'd never run any of these on a production server, so, to run just some quick tests any of them are equally good.
Also look into the PEAR mail package Pear Mail Page
It seems to be a little more robust than the standard mail() function that is built in (if the standard function isn't adequate).
Here is an excerpt from this page showing how it is used. PEAR Mail send() usage
<?php
include('Mail.php');
$recipients = '[email protected]';
$headers['From'] = '[email protected]';
$headers['To'] = '[email protected]';
$headers['Subject'] = 'Test message';
$body = 'Test message';
$smtpinfo["host"] = "smtp.server.com";
$smtpinfo["port"] = "25";
$smtpinfo["auth"] = true;
$smtpinfo["username"] = "smtp_user";
$smtpinfo["password"] = "smtp_password";
// Create the mail object using the Mail::factory method
$mail_object =& Mail::factory("smtp", $smtpinfo);
$mail_object->send($recipients, $headers, $body);
?>
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
Check this link: http://css-tricks.com/snippets/jquery/smooth-scrolling/ for a demo, I've used it before and it works quite nicely.
document.onkeydown = keydown;
function keydown (evt) {
if (!evt) evt = event;
if (evt.ctrlKey && evt.altKey && evt.keyCode === 115) {
alert("CTRL+ALT+F4");
} else if (evt.shiftKey && evt.keyCode === 9) {
alert("Shift+TAB");
}
}
I use Handler
with Looper.getMainLooper()
. It worked fine for me.
Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
// Any UI task, example
textView.setText("your text");
}
};
handler.sendEmptyMessage(1);
step1:
class CNAME:
...
def as_dict(self):
return {item.name: getattr(self, item.name) for item in self.__table__.columns}
step2:
list = []
for data in session.query(CNAME).all():
list.append(data.as_dict())
step3:
return jsonify(list)
Use this command at rails console
rails generate migration add_fieldname_to_tablename fieldname:string
and
rake db:migrate
to run this migration
The font may exist with different names, and not at all on some systems, so you need to use different variations and fallback to get the closest possible look on all systems:
font-family: "Comic Sans MS", "Comic Sans", cursive;
Be careful what you use this font for, though. Many consider it as ugly and overused, so it should not be use for something that should look professional.
Yes, it is mainly to anchor your keywords, in particular the location of your page, so whenever URL loads the page with particular anchor name, then it will be pointed to that particular location.
For example, www.something.com/some_page/#computer if it is very lengthy page and you want to show exactly computer then you can anchor.
<p> adfadsf </p>
<p> adfadsf </p>
<p> adfadsf </p>
<a name="computer"></a><p> Computer topics </p>
<p> adfadsf </p>
Now the page will scroll and bring computer-related topics to the top.
As has been pointed out in some other answers and comments, what you are missing here is a call to the JVM System class to print out the string generated by your toString() method.
LinkedList myLinkedList = new LinkedList();
System.out.println(myLinkedList.toString());
This will get the job done, but I wouldn't recommend doing it that way. If we take a look at the javadocs for the Object class, we find this description for toString():
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The emphasis added there is my own. You are creating a string that contains the entire state of the linked list, which somebody using your class is probably not expecting. I would recommend the following changes:
In LinkedListNode:
public String toString(){
return "LinkedListNode with data: " + getData();
}
In LinkedList:
public int size(){
int currentSize = 0;
LinkedListNode current = head;
while(current != null){
currentSize = currentSize + 1;
current = current.getNext();
}
return currentSize;
}
public String toString(){
return "LinkedList with " + size() + "elements.";
}
public void printList(){
System.out.println("Contents of " + toString());
LinkedListNode current = head;
while(current != null){
System.out.println(current.toString());
current = current.getNext();
}
}
The problem is in new PHP Version in macOS Sierra
Please add
stream_context_set_option($ctx, 'ssl', 'verify_peer', false);
If you don't have non-ASCII characters (codepoints 128 and above) in your file, UTF-8 without BOM is the same as ASCII, byte for byte - so Notepad++ will guess wrong.
What you need to do is to specify the character encoding when serving the AJAX response - e.g. with PHP, you'd do this:
header('Content-Type: application/json; charset=utf-8');
The important part is to specify the charset with every JS response - else IE will fall back to user's system default encoding, which is wrong most of the time.
Contanis occur if using the method of the present letter, and store the corresponding number using the IndexOf method, see example below.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim myString As String = "abcdef"
Dim numberString As String = String.Empty
If myString.Contains("d") Then
numberString = myString.IndexOf("d")
End If
End Sub
Another sample with TextBox
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim myString As String = "abcdef"
Dim numberString As String = String.Empty
If myString.Contains(me.TextBox1.Text) Then
numberString = myString.IndexOf(Me.TextBox1.Text)
End If
End Sub
Regards
for bootstrap 4 this work with me good
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').find(".form-control:first").addClass('is-invalid');
},
unhighlight: function(element) {
$(element).closest('.form-group').find(".form-control:first").removeClass('is-invalid');
$(element).closest('.form-group').find(".form-control:first").addClass('is-valid');
},
errorElement: 'span',
errorClass: 'invalid-feedback',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
hope it will help !
For a more detailed explanation, check out this post:
http://www.viget.com/inspire/webkit-transform-kill-the-flash/
I would definitely avoid applying it to the entire body. The key is to make sure whatever specific element you plan on transforming in the future starts out rendered in 3d so the browsers doesn't have to switch in and out of rendering modes. Adding
-webkit-transform: translateZ(0)
(or either of the options already mentioned) to the animated element will accomplish this.
You can use array_walk
to apply your preg_match
function to each element of the array.
It's not open source, but you can at least get a free personal use license to Prince, which really does a lovely job.
WHILE EXISTS(
SELECT * FROM sys.all_columns
INNER JOIN sys.tables ST ON all_columns.object_id = ST.object_id
INNER JOIN sys.schemas ON ST.schema_id = schemas.schema_id
INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id
WHERE
schemas.name = 'dbo'
AND ST.name = 'MyTable'
)
BEGIN
DECLARE @SQL NVARCHAR(MAX) = N'';
SET @SQL = ( SELECT TOP 1
'ALTER TABLE ['+ schemas.name + '].[' + ST.name + '] DROP CONSTRAINT ' + default_constraints.name + ';'
FROM
sys.all_columns
INNER JOIN
sys.tables ST
ON all_columns.object_id = ST.object_id
INNER JOIN
sys.schemas
ON ST.schema_id = schemas.schema_id
INNER JOIN
sys.default_constraints
ON all_columns.default_object_id = default_constraints.object_id
WHERE
schemas.name = 'dbo'
AND ST.name = 'MyTable'
)
PRINT @SQL
EXECUTE sp_executesql @SQL
--End if Error
IF @@ERROR <> 0
BREAK
END
To get the fragment instance in a class that extends FragmentActivity:
MyclassFragment instanceFragment=
(MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);
To get the fragment instance in a class that extends Fragment:
MyclassFragment instanceFragment =
(MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);
JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>();
foreach (JToken attribute in attributes)
{
JProperty jProperty = attribute.ToObject<JProperty>();
string propertyName = jProperty.Name;
}
For spring boot framework version 2.0.4.RELEASE+
. Add this line to application.properties
server.servlet.context-path=/api
It looks like you have accidentally declared DataType
as an array rather than as a string.
Change line 3 to:
Dim DataType As String = myTableData.Rows(i).Item(1)
That should work.
this is for prefix with
$("div[class^='apple-']")
this is for starts with so you dont need to have the '-' char in there
$("div[class|='apple']")
you can find a bunch of other cool variations of the jQuery selector here https://api.jquery.com/category/selectors/
brainsandwich and underscore_d gave very good ideas. Since to fill is to change content, for_each(), the simplest among the STL algorithms, should also fill the bill:
std::vector<int> v(10);
std::for_each(v.begin(), v.end(), [i=0] (int& x) mutable {x = i++;});
The generalized capture [i=o]
imparts the lambda expression with an invariant and initializes it to a known state (in this case 0). the keyword mutable
allows this state to be updated each time lambda is called.
It takes only a slight modification to get a sequence of squares:
std::vector<int> v(10);
std::for_each(v.begin(), v.end(), [i=0] (int& x) mutable {x = i*i; i++;});
To generate R-like seq is no more difficult, but note that in R, the numeric mode is actually double, so there really isn't a need to parametrize the type. Just use double.
Arrays Vs Linked List:
Here, since onSaveInstanceState
in fragment does not call when you add fragment into backstack. The fragment lifecycle in backstack when restored start onCreateView
and end onDestroyView
while onSaveInstanceState
is called between onDestroyView
and onDestroy
. My solution is create instance variable and init in onCreate
. Sample code:
private boolean isDataLoading = true;
private ArrayList<String> listData;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
isDataLoading = false;
// init list at once when create fragment
listData = new ArrayList();
}
And check it in onActivityCreated
:
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(isDataLoading){
fetchData();
}else{
//get saved instance variable listData()
}
}
private void fetchData(){
// do fetch data into listData
}
This solution checks all the possible formats before throwing an exception. This solution is more convenient if you are trying to test for multiple date formats.
Date extractTimestampInput(String strDate){
final List<String> dateFormats = Arrays.asList("yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd");
for(String format: dateFormats){
SimpleDateFormat sdf = new SimpleDateFormat(format);
try{
return sdf.parse(strDate);
} catch (ParseException e) {
//intentionally empty
}
}
throw new IllegalArgumentException("Invalid input for date. Given '"+strDate+"', expecting format yyyy-MM-dd HH:mm:ss.SSS or yyyy-MM-dd.");
}
Good answers from gdw2 and d5e5. To make it a little simpler here are the recommendations pulled together in a single series of commands:
sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout
I tried all of the solutions above trying to figure out why one of my unit tests were failing to pick up the configuration from an app.config file that is perfect.
I had 2 references to the same assembly like so:
Removing the (duplicate) reference in yellow fixed it for me.
I hope this works for someone else, it drove me nuts for a while.
Here you can find some public REST services for encryption and security related things: http://security.jelastic.servint.net
This should do what you are looking for.. It assumes your list will always be just numbers. If that is not the case, just change the references to DBMS_SQL.NUMBER_TABLE to a table type that works for all of your data:
CREATE OR REPLACE PROCEDURE insert_from_lists(
list1_in IN VARCHAR2,
list2_in IN VARCHAR2,
delimiter_in IN VARCHAR2 := ','
)
IS
v_tbl1 DBMS_SQL.NUMBER_TABLE;
v_tbl2 DBMS_SQL.NUMBER_TABLE;
FUNCTION list_to_tbl
(
list_in IN VARCHAR2
)
RETURN DBMS_SQL.NUMBER_TABLE
IS
v_retval DBMS_SQL.NUMBER_TABLE;
BEGIN
IF list_in is not null
THEN
/*
|| Use lengths loop through the list the correct amount of times,
|| and substr to get only the correct item for that row
*/
FOR i in 1 .. length(list_in)-length(replace(list_in,delimiter_in,''))+1
LOOP
/*
|| Set the row = next item in the list
*/
v_retval(i) :=
substr (
delimiter_in||list_in||delimiter_in,
instr(delimiter_in||list_in||delimiter_in, delimiter_in, 1, i ) + 1,
instr (delimiter_in||list_in||delimiter_in, delimiter_in, 1, i+1) - instr (delimiter_in||list_in||delimiter_in, delimiter_in, 1, i) -1
);
END LOOP;
END IF;
RETURN v_retval;
END list_to_tbl;
BEGIN
-- Put lists into collections
v_tbl1 := list_to_tbl(list1_in);
v_tbl2 := list_to_tbl(list2_in);
IF v_tbl1.COUNT <> v_tbl2.COUNT
THEN
raise_application_error(num => -20001, msg => 'Length of lists do not match');
END IF;
-- Bulk insert from collections
FORALL i IN INDICES OF v_tbl1
insert into tmp (a, b)
values (v_tbl1(i), v_tbl2(i));
END insert_from_lists;
This is the solution implemented as a function:
Class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = this.getInitialState();
}
getInitialState = () => ({
/* state props */
})
resetState = () => {
this.setState(this.getInitialState());
}
}
DNS answer above is actually incorrect. The SO is asking about milliseconds but the answer is for microseconds. Unfortunately, Python`s doesn't have a directive for milliseconds, just microseconds (see doc), but you can workaround it by appending three zeros at the end of the string and parsing the string as microseconds, something like:
datetime.strptime(time_str + '000', '%d/%m/%y %H:%M:%S.%f')
where time_str
is formatted like 30/03/09 16:31:32.123
.
Hope this helps.
ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.
But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:
sudo apt-get install libstdc++.i686
For my Raspberry Pi 3B model it was
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet manual
allow-hotplug wlan0
iface wlan0 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
allow-hotplug wlan1
iface wlan1 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
With ES6 you can now do it like this
Example Codepen URl to load
const iframe = '<iframe height="265" style="width: 100%;" scrolling="no" title="fx." src="//codepen.io/ycw/embed/JqwbQw/?height=265&theme-id=0&default-tab=js,result" frameborder="no" allowtransparency="true" allowfullscreen="true">See the Pen <a href="https://codepen.io/ycw/pen/JqwbQw/">fx.</a> by ycw(<a href="https://codepen.io/ycw">@ycw</a>) on <a href="https://codepen.io">CodePen</a>.</iframe>';
A function component to load Iframe
function Iframe(props) {
return (<div dangerouslySetInnerHTML={ {__html: props.iframe?props.iframe:""}} />);
}
Usage:
import React from "react";
import ReactDOM from "react-dom";
function App() {
return (
<div className="App">
<h1>Iframe Demo</h1>
<Iframe iframe={iframe} />,
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Edit on CodeSandbox:
I've used includes
from Lodash
which is really similar to the native.
Added a new answer to display the code formatted:
The thing is that you were checking for document.referer, because you were in ff it was returning always true, then it was navigating to http://mysite.com. Try the following:
function backAway(){
if (document.referrer) {
//firefox, chrome, etc..
i = 0;
} else {
// under ie
i = 1;
}
if (history.length>i)
{
// there are items in history property
history.back();
} else {
window.location = 'http://www.mysite.com/';
}
return false;
}
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
//Delete all records of table
db.execSQL("DELETE FROM " + TABLE_NAME);
//Reset the auto_increment primary key if you needed
db.execSQL("UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME=" + TABLE_NAME);
//For go back free space by shrinking sqlite file
db.execSQL("VACUUM");
If what you need is non-editable text that by default starts at the top left corner you can simply use a Text View instead of a label and then set its state to non-editable, like this:
textview.isEditable = false
Way easier than messing with the labels...
Cheers!
I used JSONObject as shown below in Servlet.
JSONObject jsonReturn = new JSONObject();
NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName);
map = new HashMap<String, String>();
map.put("Status", "Success");
map.put("FailureReason", "None");
map.put("DataElements", "2");
jsonReturn = new JSONObject();
jsonReturn.accumulate("Header", map);
List<String> list = new ArrayList<String>();
list.add(NhAdminTree);
list.add(userName);
jsonReturn.accumulate("Elements", list);
The Servlet returns this JSON object as shown below:
response.setContentType("application/json");
response.getWriter().write(jsonReturn.toString());
This Servlet is called from Browser using AngularJs as below
$scope.GetNeighborhoodTreeUsingPost = function(){
alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName );
$http({
method: 'POST',
url : 'http://localhost:8080/EPortal/xlEPortalService',
headers: {
'Content-Type': 'application/json'
},
data : {
'action': 64,
'userName' : $scope.userName
}
}).success(function(data, status, headers, config){
alert("DATA.header.status : " + data.Header.Status);
alert("DATA.header.FailureReason : " + data.Header.FailureReason);
alert("DATA.header.DataElements : " + data.Header.DataElements);
alert("DATA.elements : " + data.Elements);
}).error(function(data, status, headers, config) {
alert(data + " : " + status + " : " + headers + " : " + config);
});
};
This code worked and it is showing correct data in alert dialog box:
Data.header.status : Success
Data.header.FailureReason : None
Data.header.DetailElements : 2
Data.Elements : Coma seperated string values i.e. NhAdminTree, userName
You can format the jquery date with this line:
moment($(elem).datepicker('getDate')).format("YYYY-MM-DD");
Stored procedure can be called recursively but stored function can not
Use Windows Job Objects. Jobs are like process groups and can limit memory usage and process priority.
Given that this is a schedule of jobs, I suspect that at some point you are going to sort them into a proposed order of execution.
If that's the case, then a topological sort implementation may in any case detect cycles. UNIX tsort
certainly does. I think it is likely that it is therefore more efficient to detect cycles at the same time as tsorting, rather than in a separate step.
So the question might become, "how do I most efficiently tsort", rather than "how do I most efficiently detect loops". To which the answer is probably "use a library", but failing that the following Wikipedia article:
has the pseudo-code for one algorithm, and a brief description of another from Tarjan. Both have O(|V| + |E|)
time complexity.
Here is my solution with reduce and Optional:
private Optional<SimpleImmutableEntry<String, String>> splitKeyValue(String text) {
String[] v = text.split("=");
if (v.length == 1 || v.length == 2) {
String key = URLDecoder.decode(v[0], StandardCharsets.UTF_8);
String value = v.length == 2 ? URLDecoder.decode(v[1], StandardCharsets.UTF_8) : null;
return Optional.of(new SimpleImmutableEntry<String, String>(key, value));
} else
return Optional.empty();
}
private HashMap<String, String> parseQuery(URI uri) {
HashMap<String, String> params = Arrays.stream(uri.getQuery()
.split("&"))
.map(this::splitKeyValue)
.filter(Optional::isPresent)
.map(Optional::get)
.reduce(
// initial value
new HashMap<String, String>(),
// accumulator
(map, kv) -> {
map.put(kv.getKey(), kv.getValue());
return map;
},
// combiner
(a, b) -> {
a.putAll(b);
return a;
});
return params;
}
Optional<SimpleImmutableEntry<String, String>>
to ignore garbage laterIn case you ask, reduce requires this weird combiner in the last parameter, which is only used in parallel streams. Its goal is to merge two intermediate results (here HashMap).
Try instead of db.parse(xml)
:
Document doc = db.parse(new InputSource(new StringReader(**xml**)));
$(jQuery.browser.webkit ? "body": "html").animate({ scrollTop: $('#title1').offset().top }, 1000);
Another good option for handling this kind of option is the pprint
module, which (among other things) pretty prints long lists with one element per line:
>>> import sys
>>> import pprint
>>> pprint.pprint(sys.path)
['',
'/usr/lib/python27.zip',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/lib/python2.7/site-packages',
'/usr/lib/python2.7/site-packages/PIL',
'/usr/lib/python2.7/site-packages/gst-0.10',
'/usr/lib/python2.7/site-packages/gtk-2.0',
'/usr/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info',
'/usr/lib/python2.7/site-packages/webkit-1.0']
>>>
1.if your phone system is over 4.2.2 , there will be
2.disconnect the USB and try again or restart your phone
3.After after all try , it didn't work. It may be a shortage power supply so try other usb interface on your computer.
I solved the problem doing the first step . anyway have try.
As a learning exercise for myself, I created a class to be able to create several stopwatch timer instances that you might find useful (I'm sure there are better/simpler versions around in the time modules or similar)
import time as tm
class Watch:
count = 0
description = "Stopwatch class object (default description)"
author = "Author not yet set"
name = "not defined"
instances = []
def __init__(self,name="not defined"):
self.name = name
self.elapsed = 0.
self.mode = 'init'
self.starttime = 0.
self.created = tm.strftime("%Y-%m-%d %H:%M:%S", tm.gmtime())
Watch.count += 1
def __call__(self):
if self.mode == 'running':
return tm.time() - self.starttime
elif self.mode == 'stopped':
return self.elapsed
else:
return 0.
def display(self):
if self.mode == 'running':
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.elapsed = 0.
elif self.mode == 'stopped':
pass
else:
pass
print "Name: ", self.name
print "Address: ", self
print "Created: ", self.created
print "Start-time: ", self.starttime
print "Mode: ", self.mode
print "Elapsed: ", self.elapsed
print "Description:", self.description
print "Author: ", self.author
def start(self):
if self.mode == 'running':
self.starttime = tm.time()
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.starttime = tm.time()
self.mode = 'running'
self.elapsed = 0.
elif self.mode == 'stopped':
self.mode = 'running'
#self.elapsed = self.elapsed + tm.time() - self.starttime
self.starttime = tm.time() - self.elapsed
else:
pass
return
def stop(self):
if self.mode == 'running':
self.mode = 'stopped'
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.mode = 'stopped'
self.elapsed = 0.
elif self.mode == 'stopped':
pass
else:
pass
return self.elapsed
def lap(self):
if self.mode == 'running':
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.elapsed = 0.
elif self.mode == 'stopped':
pass
else:
pass
return self.elapsed
def reset(self):
self.starttime=0.
self.elapsed=0.
self.mode='init'
return self.elapsed
def WatchList():
return [i for i,j in zip(globals().keys(),globals().values()) if '__main__.Watch instance' in str(j)]
Q1) Here are couple things to read or google more :
Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest
It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.
Q2) Here are couple of good tutorials for soap (I had them bookmarked) :
http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/
http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html
Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.
SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.
Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).
Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.
If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development
.
It's fantastic, not hard to read and not too big either (win win).
Please check if the setting Generate Debug Info is Yes which under Project Propeties > Configuration Properties > Linker > Debugging tab. If not, try to change it to Yes.
Those perticular pdb's ( for ntdll.dll, mscoree.dll, kernel32.dll, etc ) are for the windows API and shouldn't be needed for simple apps. However, if you cannot find pdb's for your own compiled projects, I suggest making sure the Project Properties > Configuration Properties > Debugging > Working Directory uses the value from Project Properties > Configuration Properties > General > Output Directory .
You need to run Visual c++ in "Run as Administrator" mode.Right click on the executable and click "Run as Administrator"
window.onload = function() {
var el = document.documentElement,
rfs = el.requestFullScreen
|| el.webkitRequestFullScreen
|| el.mozRequestFullScreen;
rfs.call(el);
};
import java.util.*;
public class Friday {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("code", 10);
map.put("to", 11);
map.put("joy", 12);
if (! map.isEmpty()) {
Map.Entry<String, Integer> entry = map.entrySet().iterator().next();
System.out.println(entry);
}
}
}
This approach doesn't work because you used HashMap. I assume using LinkedHashMap will be right solution in this case.
On Windows:-
Go to File -> Settings.
And open the 'Build,Execution,Deployment'
. Then open the
Build Tools -> Gradle
Then uncheck -> Offline work on the right.
Click the OK button.
Then Rebuild the Project.
On Mac OS:-
go to Android Studio -> Preferences, and the rest is the same. OR follow steps given in the image
[
I was with the same problem and now discovered a working solution. After successful installation of node and angular CLI do the following steps.
Open C:\usr\local
and copy the path or the path where angular CLI located on your machine.
Now open environment variable in your Windows, and add copied path in the following location:
Advanced > Environment Variable > User Variables and System Variables
as below image:
That's all, now open cmd and try with any 'ng' command:
For Xamarin Android align to the left of an object
int dp24 = (int)TypedValue.ApplyDimension( ComplexUnitType.Dip, 24, Resources.System.DisplayMetrics );
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( dp24, dp24 );
lp.AddRule( LayoutRules.CenterInParent, 1 );
lp.AddRule( LayoutRules.LeftOf, //Id of the field Eg m_Button.Id );
m_Button.LayoutParameters = lp;
This worked for me on mac os High sierra 10.13.6, java 8 64-bit, jmeter 4.0
$ jmeter -n --testfile /path/to/Test_Plan.jmx
Sample output:
Creating summariser <summary>
Created the tree successfully using ./src/test/jmeter/Test_Plan.jmx
Starting the test @ Fri Aug 24 17:18:18 PDT 2018 (1535156298333)
Waiting for possible Shutdown/StopTestNow/Heapdump message on port 4445
summary = 10 in 00:00:09 = 1.1/s Avg: 6666 Min: 1000 Max: 8950 Err:
0 (0.00%)
Tidying up ... @ Fri Aug 24 17:18:28 PDT 2018 (1535156308049)
... end of run
I have to wait until a UIWebView is loaded before running my method, I was able to get this working by performing UIWebView ready checks on main thread using GCD in combination with semaphore methods mentioned in this thread. Final code looks like this:
-(void)myMethod {
if (![self isWebViewLoaded]) {
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block BOOL isWebViewLoaded = NO;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
while (!isWebViewLoaded) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((0.0) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
isWebViewLoaded = [self isWebViewLoaded];
});
[NSThread sleepForTimeInterval:0.1];//check again if it's loaded every 0.1s
}
dispatch_sync(dispatch_get_main_queue(), ^{
dispatch_semaphore_signal(semaphore);
});
});
while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0]];
}
}
}
//Run rest of method here after web view is loaded
}
note you can only do this with Numbers and Strings
you could do...
var a, b, c; a = b = c = 0; //but why?
c++;
// c = 1, b = 0, a = 0;
In my case, my dataframe has the following characteristics
<class 'pandas.core.frame.DataFrame'>
Index: 3040 entries, 15/12/2008 to
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Close 3038 non-null float64
dtypes: float64(1)
memory usage: 47.5+ KB
The first option data.index = pd.to_datetime(data.index)
returned
ParserError: String does not contain a date: ParserError: String does not contain a date:
The second option: data.index.to_datetime()
returned
AttributeError: 'Index' object has no attribute 'to_datetime'
It returned
Another option I have tested is. data.index = pd.to_datetime(data.index)
It returned: ParserError: String does not contain a date:
What could be my problem? Thanks
Simple javascript solution for all browser:
setTimeout(function() {
$(".parent input").each(function(){
parent = $(this).parents(".parent");
$(this).clone().appendTo(parent);
$(this).attr("id","").attr("name","").hide();
});
}, 300 );
Clone input, reset attribute and hide original input. Timeout is needed for iPad
Add a reference to the Microsoft Forms 2.0 Object Library and try this code. It only works with text, not with other data types.
Dim DataObj As New MSForms.DataObject
'Put a string in the clipboard
DataObj.SetText "Hello!"
DataObj.PutInClipboard
'Get a string from the clipboard
DataObj.GetFromClipboard
Debug.Print DataObj.GetText
Here you can find more details about how to use the clipboard with VBA.
There is an implementation in my TypeScript utilities based on JavaScript GUID generators.
Here is the code:
class Guid {_x000D_
static newGuid() {_x000D_
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
var r = Math.random() * 16 | 0,_x000D_
v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
return v.toString(16);_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
var id = Guid.newGuid();_x000D_
console.log(id);_x000D_
}
_x000D_
Please note the following:
C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.
JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).
For cloning a specific branch you can do :
git clone --branch yourBranchName [email protected]
length
and dbms_lob.getlength
return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength
will return the number of bytes, which may differ from the number of characters in a multi-byte character set.
As the documentation doesn't specify what happens when you apply length
on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength
.
For setting value in hidden field do in the following way:
@Html.HiddenFor(model => model.title,
new { id= "natureOfVisitField", Value = @Model.title})
It will work
Oh I figured this out, please ignore unless you have the same problem i did in which case:
$prevmonth = date("M Y",mktime(0,0,0,date("m")-1,1,date("Y")));
I wouldn't use the debian packages, have a look at RVM or Rbenv.
Though this isn't 'powershell' specific... you can easily list the drives and partitions using diskpart, list volume
PS C:\Dev> diskpart
Microsoft DiskPart version 6.1.7601
Copyright (C) 1999-2008 Microsoft Corporation.
On computer: Box
DISKPART> list volume
Volume ### Ltr Label Fs Type Size Status Info
---------- --- ----------- ----- ---------- ------- --------- --------
Volume 0 D DVD-ROM 0 B No Media
Volume 1 C = System NTFS Partition 100 MB Healthy System
Volume 2 G C = Box NTFS Partition 244 GB Healthy Boot
Volume 3 H D = Data NTFS Partition 687 GB Healthy
Volume 4 E System Rese NTFS Partition 100 MB Healthy
html:
<h4 data-toggle-selector="#me">toggle</h4>
<div id="me">content here</div>
js:
$(function () {
$('[data-toggle-selector]').on('click',function () {
$($(this).data('toggle-selector')).toggle(300);
})
})
an simple solution!
setInterval(()=>console.clear(),1500);
I use this to open a workbook and then copy that workbook's data to the template.
Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
.Filters.Clear
.Title = "Your Title"
If Not .Show Then
MsgBox "No file selected.": Exit Sub
End If
Workbooks.OpenText .SelectedItems(1)
'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1
Set myfile = ActiveWorkbook
ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
myfile.Close
Template.Activate
ActiveSheet.Cells.Select
Selection.Copy
Sheets("Sheet1").Select
Cells.Select
ActiveSheet.Paste
End With
Trying to depict with venn diagrams for better understanding..
Left Semi join : A semi join returns values from the left side of the relation that has a match with the right. It is also referred to as a left semi join.
Note : There is another thing called left anti join : An anti join returns values from the left relation that has no match with the right. It is also referred to as a left anti join.
Inner join : It selects rows that have matching values in both relations.
Try this simple code.
1. Components side code: to get both body and header property. Here there's a token in body and Authorization
in the header.
loginUser() {
this.userService.loginTest(this.loginCred).
subscribe(res => {
let output1 = res;
console.log(output1.body.token);
console.log(output1.headers.get('Authorization'));
})
}
2. Service side code: sending login data in the body and observe the response in Observable
any which be subscribed in the component side.
loginTest(loginCred: LoginParams): Observable<any> {
const header1= {'Content-Type':'application/json',};
const body = JSON.stringify(loginCred);
return this.http.post<any>(this.baseURL+'signin',body,{
headers: header1,
observe: 'response',
responseType: 'json'
});
}
On Linux (and probably most Unix), there is no OS-level DNS caching unless nscd is installed and running. Even then, the DNS caching feature of nscd is disabled by default at least in Debian because it's broken. The practical upshot is that your linux system very very probably does not do any OS-level DNS caching.
You could implement your own cache in your application (like they did for Squid, according to diegows's comment), but I would recommend against it. It's a lot of work, it's easy to get it wrong (nscd got it wrong!!!), it likely won't be as easily tunable as a dedicated DNS cache, and it duplicates functionality that already exists outside your application.
If an end user using your software needs to have DNS caching because the DNS query load is large enough to be a problem or the RTT to the external DNS server is long enough to be a problem, they can install a caching DNS server such as Unbound on the same machine as your application, configured to cache responses and forward misses to the regular DNS resolvers.
Microsoft has a tool called JLCA: Java Language Conversion Assistant. I can't tell if it is better though, as I have never compared the two.
Your datatype is wrong, change datatype for dataType.
After the update you have done,
Earlier you were only returning JSON to browser without rendering any HTML. Now it has a HTML view rendered where it can get your JSON Data.
You can't directly render JSON its plain data not HTML.
To force LF line endings for all text files, you can create .gitattributes
file in top-level of your repository with the following lines (change as desired):
# Ensure all C and PHP files use LF.
*.c eol=lf
*.php eol=lf
which ensures that all files that Git considers to be text files have normalized (LF
) line endings in the repository (normally core.eol
configuration controls which one do you have by default).
Based on the new attribute settings, any text files containing CRLFs should be normalized by Git. If this won't happen automatically, you can refresh a repository manually after changing line endings, so you can re-scan and commit the working directory by the following steps (given clean working directory):
$ echo "* text=auto" >> .gitattributes
$ rm .git/index # Remove the index to force Git to
$ git reset # re-scan the working directory
$ git status # Show files that will be normalized
$ git add -u
$ git add .gitattributes
$ git commit -m "Introduce end-of-line normalization"
or as per GitHub docs:
git add . -u
git commit -m "Saving files before refreshing line endings"
git rm --cached -r . # Remove every file from Git's index.
git reset --hard # Rewrite the Git index to pick up all the new line endings.
git add . # Add all your changed files back, and prepare them for a commit.
git commit -m "Normalize all the line endings" # Commit the changes to your repository.
See also: @Charles Bailey post.
In addition, if you would like to exclude any files to not being treated as a text, unset their text attribute, e.g.
manual.pdf -text
Or mark it explicitly as binary:
# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary
To see some more advanced git normalization file, check .gitattributes
at Drupal core:
# Drupal git normalization
# @see https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
# @see https://www.drupal.org/node/1542048
# Normally these settings would be done with macro attributes for improved
# readability and easier maintenance. However macros can only be defined at the
# repository root directory. Drupal avoids making any assumptions about where it
# is installed.
# Define text file attributes.
# - Treat them as text.
# - Ensure no CRLF line-endings, neither on checkout nor on checkin.
# - Detect whitespace errors.
# - Exposed by default in `git diff --color` on the CLI.
# - Validate with `git diff --check`.
# - Deny applying with `git apply --whitespace=error-all`.
# - Fix automatically with `git apply --whitespace=fix`.
*.config text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.css text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.dist text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.engine text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.html text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=html
*.inc text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.install text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.js text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.json text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.lock text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.map text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.md text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.module text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.php text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.po text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.profile text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.script text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.sh text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.sql text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.svg text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.theme text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.twig text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.txt text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.xml text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.yml text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
# Define binary file attributes.
# - Do not treat them as text.
# - Include binary diff in patches instead of "binary files differ."
*.eot -text diff
*.exe -text diff
*.gif -text diff
*.gz -text diff
*.ico -text diff
*.jpeg -text diff
*.jpg -text diff
*.otf -text diff
*.phar -text diff
*.png -text diff
*.svgz -text diff
*.ttf -text diff
*.woff -text diff
*.woff2 -text diff
See also:
DateTime does not know its timezone offset. There is no built-in method to return the offset or the timezone name (e.g. EAT, CEST, EST etc).
Like suggested by others, you can convert your date to UTC:
DateTime localtime = new DateTime.Now;
var utctime = localtime.ToUniversalTime();
and then only calculate the difference:
TimeSpan difference = localtime - utctime;
Also you may convert one time to another by using the DateTimeOffset:
DateTimeOffset targetTime = DateTimeOffset.Now.ToOffset(new TimeSpan(5, 30, 0));
But this is sort of lossy compression - the offset alone cannot tell you which time zone it is as two different countries may be in different time zones and have the same time only for part of the year (eg. South Africa and Europe). Also, be aware that summer daylight saving time may be introduced at different dates (EST vs CET - a 3-week difference).
You can get the name of your local system time zone using TimeZoneInfo class:
TimeZoneInfo localZone = TimeZoneInfo.Local;
localZone.IsDaylightSavingTime(localtime) ? localZone.DaylightName : localZone.StandardName
I agree with Gerrie Schenck, please read the article he suggested.
You can do that by specifying the ref
EDIT: In react v16.8.0 with function component, you can define a ref with useRef. Note that when you specify a ref on a function component, you need to use React.forwardRef on it to forward the ref to the DOM element of use useImperativeHandle
to to expose certain functions from within the function component
Ex:
const Child1 = React.forwardRef((props, ref) => {
return <div ref={ref}>Child1</div>
});
const Child2 = React.forwardRef((props, ref) => {
const handleClick= () =>{};
useImperativeHandle(ref,() => ({
handleClick
}))
return <div>Child2</div>
});
const App = () => {
const child1 = useRef(null);
const child2 = useRef(null);
return (
<>
<Child1 ref={child1} />
<Child1 ref={child1} />
</>
)
}
EDIT:
In React 16.3+, use React.createRef()
to create your ref:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
In order to access the element, use:
const node = this.myRef.current;
DOC for using React.createRef()
EDIT
However facebook advises against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases.
From the docs:
Legacy API: String Refs
If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.
A recommended way for React 16.2 and earlier is to use the callback pattern:
<Progressbar completed={25} id="Progress1" ref={(input) => {this.Progress[0] = input }}/>
<h2 class="center"></h2>
<Progressbar completed={50} id="Progress2" ref={(input) => {this.Progress[1] = input }}/>
<h2 class="center"></h2>
<Progressbar completed={75} id="Progress3" ref={(input) => {this.Progress[2] = input }}/>
Even older versions of react defined refs using string like below
<Progressbar completed={25} id="Progress1" ref="Progress1"/>
<h2 class="center"></h2>
<Progressbar completed={50} id="Progress2" ref="Progress2"/>
<h2 class="center"></h2>
<Progressbar completed={75} id="Progress3" ref="Progress3"/>
In order to get the element just do
var object = this.refs.Progress1;
Remember to use this
inside an arrow function block like:
print = () => {
var object = this.refs.Progress1;
}
and so on...
The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.
Please check the class you inherited. Whether it is simply Controller or APIController.
By mistake we might create a controller from MVC 5 controller. It should be from Web API Controller.
If you want to use a js variable in a php script you MUST pass it within a HTTP request.
There are basically two ways:
A basic example can be:
var profile_viewer_uid = 1;
$.ajax({
url: "serverScript.php",
method: "POST",
data: { "profile_viewer_uid": profile_viewer_uid }
})
And in the serverScript.php
file, you can do:
$profile_viewer_uid = $_POST['profile_viewer_uid'];
echo($profile_viewer_uid);
// prints 1
Note: in this example I used jQuery AJAX, which is quicker to implement. You can do it in pure js as well.
I am looking for a way to create a select without repeating the conditional query.
I'm assuming that you don't want to repeat Foo-stuff+bar
. You could put your calculation into a derived table:
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END
FROM (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable) AS a
A common table expression would work just as well:
WITH a AS (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable)
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END
FROM a
Also, each part of your switch should return the same datatype, so you may have to cast one or more cases.
You do not have to install something.
parseInt(req.params.year, 10);
should work properly.
console.log(typeof parseInt(req.params.year)); // returns 'number'
What is your output, if you use parseInt? is it still a string?
I used Time.parse("02/07/1988")
, like some of the other posters.
An interesting gotcha was that Time
was loaded by default when I opened up IRB, but Time.parse
was not defined. I had to require 'time'
to get it to work.
That's with Ruby 2.2.
All of that above can work but for a quick and easy fix you can use the time_formatter package.
Using this package you can convert the epoch to human-readable time.
String convertTimeStamp(timeStamp){
//Pass the epoch server time and the it will format it for you
String formatted = formatTime(timeStamp).toString();
return formatted;
}
//Then you can display it
Text(convertTimeStamp['createdTimeStamp'])//< 1 second : "Just now" up to < 730 days : "1 year"
Here you can check the format of the output that is going to be displayed: Formats
Try:
git remote prune origin
From the Git remote documentation:
prune
Deletes all stale remote-tracking branches under <name>. These stale branches have already been removed from the remote repository referenced by <name>, but are still locally available in "remotes/<name>".
With --dry-run option, report what branches will be pruned, but do not actually prune them.
I think the error is caused by the redundant ,
flutter:
uses-material-design: true, # <<< redundant , at the end of the line
assets:
- images/lake.jpg
I'd also suggest to create an assets
folder in the directory that contains the pubspec.yaml
file and move images
there and use
flutter:
uses-material-design: true
assets:
- assets/images/lake.jpg
The assets
directory will get some additional IDE support that you won't have if you put assets somewhere else.
Simply call window.frameElement
from your framed page.
If the page is not in a frame then frameElement
will be null
.
The other way (getting the window element inside a frame is less trivial) but for sake of completeness:
/**
* @param f, iframe or frame element
* @return Window object inside the given frame
* @effect will append f to document.body if f not yet part of the DOM
* @see Window.frameElement
* @usage myFrame.document = getFramedWindow(myFrame).document;
*/
function getFramedWindow(f)
{
if(f.parentNode == null)
f = document.body.appendChild(f);
var w = (f.contentWindow || f.contentDocument);
if(w && w.nodeType && w.nodeType==9)
w = (w.defaultView || w.parentWindow);
return w;
}
NULL
isn't a keyword; it's a macro substitution for 0, and comes in stddef.h
or cstddef
, I believe. You haven't #included
an appropriate header file, so g++ sees NULL
as a regular variable name, and you haven't declared it.
You can use DataSourceBuilder
if you are using jdbc
starter. Also, in order to override the default autoconfiguration bean you need to mark your bean as a @Primary
In my case I have properties starting with datasource.postgres
prefix.
E.g
@ConfigurationProperties(prefix = "datasource.postgres")
@Bean
@Primary
public DataSource dataSource() {
return DataSourceBuilder
.create()
.build();
}
If it is not feasible for you, then you can use
@Bean
@Primary
public DataSource dataSource() {
return DataSourceBuilder
.create()
.username("")
.password("")
.url("")
.driverClassName("")
.build();
}
Use;
^(19|[2-9][0-9])\d{2}$
for years 1900 - 9999.
No need to worry for 9999 and onwards - A.I. will be doing all programming by then !!! Hehehehe
You can test your regex at https://regex101.com/
Also more info about non-capturing groups ( mentioned in one the comments above ) here http://www.manifold.net/doc/radian/why_do_non-capture_groups_exist_.htm
In case of multi monitor and If you prefer to center on correct monitor/screen then you might like to try these lines:
// Save values for future(for example, to center a form on next launch)
int screen_x = Screen.FromControl(Form).WorkingArea.X;
int screen_y = Screen.FromControl(Form).WorkingArea.Y;
// Move it and center using correct screen/monitor
Form.Left = screen_x;
Form.Top = screen_y;
Form.Left += (Screen.FromControl(Form).WorkingArea.Width - Form.Width) / 2;
Form.Top += (Screen.FromControl(Form).WorkingArea.Height - Form.Height) / 2;
You could always use the sort method, if you don't know where the record is at present:
playlist.sort(function (a, b) {
return a.artist == "Lalo Schifrin"
? 1 // Move it down the list
: 0; // Keep it the same
});
Looks like you typed brackets instead of parenthesis by mistake.
Create a div, which contains both divs (full and someid) and set the height of that div to the following:
height: 100vh;
The height of the containing divs (full and someid) should be set to "auto". That's all.
Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").
POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--
Note that every line (including the last one) is terminated by a \r\n sequence.
To be short, use:
write-output "your text" | out-file -append -encoding utf8 "filename"
double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);
The double value is 420.5 and the application prints out the integer value of 420
If you call it like this: $ python myfile.py var1 var2 var3
import sys
var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]
Similar to arrays you also have sys.argv[0]
which is always the current working directory.
Convert your JSON object to JSON String using
JSON.stringify({"name":"testName"})
or manually. @RequestBody expecting json string instead of json object.
Note:stringify function having issue with some IE version, firefox it will work
verify the syntax of your ajax request for POST request. processData:false property is required in ajax request
$.ajax({
url:urlName,
type:"POST",
contentType: "application/json; charset=utf-8",
data: jsonString, //Stringified Json Object
async: false, //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
cache: false, //This will force requested pages not to be cached by the browser
processData:false, //To avoid making query String instead of JSON
success: function(resposeJsonObject){
// Success Action
}
});
Controller
@RequestMapping(value = urlPattern , method = RequestMethod.POST)
public @ResponseBody Test addNewWorker(@RequestBody Test jsonString) {
//do business logic
return test;
}
@RequestBody
-Covert Json object to java
@ResponseBody
- convert Java object to json
If you're open to using jQuery:
<script type="text/javascript">
function fncsave()
{
$('#<%= savebtn.ClientID %>').click();
}
</script>
Also, if you are using .NET 4 or better you can make the ClientIDMode == static
and simplify the code:
<script type="text/javascript">
function fncsave()
{
$("#savebtn").click();
}
</script>
Reference: MSDN Article for Control.ClientIDMode
I know this question has been answered and I am not trying to give better answer here. I'll just share my experience in this topic.
Once I lost my code and I had the apk
file only. I decompiled it using the tool below and it made my day.
These tools MUST be used in such situation, otherwise, it is unethical and even sometimes it is illegal, (stealing somebody else's effort). So please use it wisely.
Those are my favorite tools for doing that:
and to get the apk from google play you can google it or check out those sites:
On the date of posting this answer I tested all the links and it worked perfect for me.
NOTE: Apk Decompiling is not effective in case of proguarded code. Because Proguard shrink and obfuscates the code and rename classes to nonsense names which make it fairly hard to understand the code.
Bonus:
Use margins instead of line-height and then apply float to the buttons. By default they are displaying as inline-block
, so when one is pushed down the hole line is pushed down with him. Float fixes this:
#header button {
float:left;
}
Here's a working jsfidle.
If you copy something from disk A to disk B in explorer, Windows employs DMA. That means for most of the copy process, the CPU will basically do nothing other than telling the disk controller where to put, and get data from, eliminating a whole step in the chain, and one that is not at all optimized for moving large amounts of data - and I mean hardware.
What you do involves the CPU a lot. I want to point you to the "Some calculations to fill a[]" part. Which I think is essential. You generate a[], then you copy from a[] to an output buffer (thats what fstream::write does), then you generate again, etc.
What to do? Multithreading! (I hope you have a multi-core processor)
For private static variables, I found this way:
function Class()
{
}
Class.prototype = new function()
{
_privateStatic = 1;
this.get = function() { return _privateStatic; }
this.inc = function() { _privateStatic++; }
};
var o1 = new Class();
var o2 = new Class();
o1.inc();
console.log(o1.get());
console.log(o2.get()); // 2
Use the constructor Date(year,month,date)
in Java 8 it is deprecated:
Date date = new Date(1990, 10, 26, 0, 0);
The best way is to use SimpleDateFormat
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = format.parse("26/10/1985");
you need to import import java.text.SimpleDateFormat;
So, simplejson.loads takes a json string and returns a data structure, which is why you are getting that type error there.
simplejson.dumps(data) comes back with
'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'
Which is a json array, which is what you want, since you gave this a python array.
If you want to get an "object" type syntax you would instead do
>>> data2 = {'apple':'cat', 'banana':'dog', 'pear':'fish'}
>>> simplejson.dumps(data2)
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
which is javascript will come out as an object.
This can be done in a single line, as long as the worksheet is active:
ActiveSheet.Visible = xlSheetHidden
However, you may not want to do this, especially if you use any "select" operations or you use any more ActiveSheet operations.
Load data into a table in MySQL and specify columns:
LOAD DATA LOCAL INFILE 'file.csv' INTO TABLE t1
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'
(@col1,@col2,@col3,@col4) set name=@col4,id=@col2 ;
@col1,2,3,4 are variables to hold the csv file columns (assume 4 ) name,id are table columns.
There's, however, slight difference among all these options which
I found out that
If you do
string URL = Server.MapPath("~");
or
string URL = Server.MapPath("/");
or
string URL = HttpRuntime.AppDomainAppPath;
your URL will display resources in your link like this:
"file:///d:/InetPUB/HOME/Index/bin/Resources/HandlerDoc.htm"
But if you want your URL to show only virtual path not the resources location, you should do
string URL = HttpRuntime.AppDomainAppVirtualPath;
then, your URL is displaying a virtual path to your resources as below
"http://HOME/Index/bin/Resources/HandlerDoc.htm"
The way to output >
character is to prepend it with ^
escape character:
echo ^>
will print simply
>
I understand the question as this: you want to completely replace the contents of one file (or a selection) from upstream. You don't want to affect the index directly (so you would go through add + commit as usual).
Simply do
git checkout remote/branch -- a/file b/another/file
If you want to do this for extensive subtrees and instead wish to affect the index directly use
git read-tree remote/branch:subdir/
You can then (optionally) update your working copy by doing
git checkout-index -u --force
If you want to use a PathVariable, you can use an example method below (all methods are and do the same):
//You can consume the path .../users/added-since1/2019-04-25
@GetMapping("/users/added-since1/{since}")
public String userAddedSince1(@PathVariable("since") @DateTimeFormat(pattern = "yyyy-MM-dd") Date since) {
return "Date: " + since.toString(); //The output is "Date: Thu Apr 25 00:00:00 COT 2019"
}
//You can consume the path .../users/added-since2/2019-04-25
@RequestMapping("/users/added-since2/{since}")
public String userAddedSince2(@PathVariable("since") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date since) {
return "Date: " + since.toString(); //The output is "Date: Wed Apr 24 19:00:00 COT 2019"
}
//You can consume the path .../users/added-since3/2019-04-25
@RequestMapping("/users/added-since3/{since}")
public String userAddedSince3(@PathVariable("since") @DateTimeFormat(pattern = "yyyy-MM-dd") Date since) {
return "Date: " + since.toString(); //The output is "Date: Thu Apr 25 00:00:00 COT 2019"
}
Just came across the same problem trying to make a bad USB...
I tried to run this command in admin cmd
java -jar c:\fw\ducky\duckencode.jar -I c:\fw\ducky\HelloWorld.txt -o c:\fw\ducky\inject.bin
But got this error:
Error: unable to access jarfile c:\fw\ducky\duckencode.jar
Solution
1st step
Right click the jarfile in question. Click properties. Click the unblock tab in bottom right corner. The file was blocked, because it was downloaded and not created on my PC.
2nd step
In the cmd I changed the directory to where the jar file is located.
cd C:\fw\ducky\
Then I typed dir
and saw the file was named duckencode.jar.jar
So in cmd I changed the original command to reference the file with .jar.jar
java -jar c:\fw\ducky\duckencode.jar.jar -I c:\fw\ducky\HelloWorld.txt -o c:\fw\ducky\inject.bin
That command executed without error messages and the inject.bin I was trying to create was now located in the directory.
Hope this helps.
$('input[name=myradiobutton]:radio:checked')
will get you the selected radio button
$('input[name=myradiobutton]:radio:not(:checked)')
will get you the unselected radio buttons
Using this you can do this
$('input[name=myradiobutton]:radio:not(:checked)').val("0");
Update: After reading your Update I think I understand You will want to do something like this
var myRadioValue;
function radioValue(jqRadioButton){
if (jqRadioButton.length) {
myRadioValue = jqRadioButton.val();
}
else {
myRadioValue = 0;
}
}
$(document).ready(function () {
$('input[name=myradiobutton]:radio').click(function () { //Hook the click event for selected elements
radioValue($('input[name=myradiobutton]:radio:checked'));
});
radioValue($('input[name=myradiobutton]:radio:checked')); //check for value on page load
});
I had this issue for a day until I found the real resolution. Instead of trying to force unmount an smb share that is hung, mount the share with the "soft" option. If a process attempts to connect to the share that is not available it will stop trying after a certain amount of time.
soft Make the mount soft. Fail file system calls after a number of seconds.
mount -t smbfs -o soft //username@server/share /users/username/smb/share
stat /users/username/smb/share/file
stat: /users/username/smb/share/file: stat: Operation timed out
May not be a real answer to your question but it is a solution to the problem
You can take videos and screenshots of Simulator using the
xcrun simctl
, a command-line utility to control the Simulator
Run your app on the simulator
Open a terminal
Run the command
To take a screenshot
xcrun simctl io booted screenshot <filename>.<file extension>
For example:
xcrun simctl io booted screenshot myScreenshot.png
To take a video
xcrun simctl io booted recordVideo <filename>.<file extension>
For example:
xcrun simctl io booted recordVideo appVideo.mov
Press ctrl + C to stop recording the video.
The default location for the created file is the current directory.
From Xcode 11.2 Beta Release Notes
simctl video recording now produces smaller video files, supports HEIC compression, and takes advantage of hardware encoding support where available. In addition, the ability to record video on iOS 13, tvOS 13, and watchOS 6 devices has been restored.
You could use additional flags:
xcrun simctl io --help
Set up a device IO operation.
Usage: simctl io <device> <operation> <arguments>
...
recordVideo [--codec=<codec>] [--display=<display>] [--mask=<policy>] [--force] <file or url>
Records the display to a QuickTime movie at the specified file or url.
--codec Specifies the codec type: "h264" or "hevc". Default is "hevc".
--display iOS: supports "internal" or "external". Default is "internal".
tvOS: supports only "external"
watchOS: supports only "internal"
--mask For non-rectangular displays, handle the mask by policy:
ignored: The mask is ignored and the unmasked framebuffer is saved.
alpha: Not supported, but retained for compatibility; the mask is rendered black.
black: The mask is rendered black.
--force Force the output file to be written to, even if the file already exists.
screenshot [--type=<type>] [--display=<display>] [--mask=<policy>] <file or url>
Saves a screenshot as a PNG to the specified file or url(use "-" for stdout).
--type Can be "png", "tiff", "bmp", "gif", "jpeg". Default is png.
--display iOS: supports "internal" or "external". Default is "internal".
tvOS: supports only "external"
watchOS: supports only "internal"
You may also specify a port by UUID
--mask For non-rectangular displays, handle the mask by policy:
ignored: The mask is ignored and the unmasked framebuffer is saved.
alpha: The mask is used as premultiplied alpha.
black: The mask is rendered black.
Now you can take a screenshot in jpeg
, with mask (for non-rectangular displays) and some other flags:
xcrun simctl io booted screenshot --type=jpeg --mask=black screenshot.jpeg
To use quotes just for completeness.
"/Users/my/work/a project with space"/**
If not recursive, remove the /**
You want reorder()
. Here is an example with dummy data
set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
require("ggplot2")
p1 <- ggplot(df, aes(x = Category, y = Count)) +
geom_bar(stat = "identity")
p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
geom_bar(stat = "identity")
require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))
Giving:
Use reorder(Category, Count)
to have Category
ordered from low-high.
Code is here (Win form app):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace RunAtStartup
{
public partial class frmStartup : Form
{
// The path to the key where Windows looks for startup applications
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
public frmStartup()
{
InitializeComponent();
// Check to see the current state (running at startup or not)
if (rkApp.GetValue("MyApp") == null)
{
// The value doesn't exist, the application is not set to run at startup
chkRun.Checked = false;
}
else
{
// The value exists, the application is set to run at startup
chkRun.Checked = true;
}
}
private void btnOk_Click(object sender, EventArgs e)
{
if (chkRun.Checked)
{
// Add the value in the registry so that the application runs at startup
rkApp.SetValue("MyApp", Application.ExecutablePath);
}
else
{
// Remove the value from the registry so that the application doesn't start
rkApp.DeleteValue("MyApp", false);
}
}
}
}
Run the script as source= to run in debug mode as well.
source= ./myscript.sh
You could use:
echo date('F Y', strtotime('20130814'));
which should do the trick.
Edit: You have a date which is in a string format. To be able to format it nicelt, you first need to change it into a date itself - which is where strtotime comes in. It is a fantastic feature that converts almost any plausible expression of a date into a date itself. Then we can actually use the date() function to format the output into what you want.
To only modify the title's font (and not the font of the axis) I used this:
import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})
The fontdict accepts all kwargs from matplotlib.text.Text.
INSERT INTO wp_bp_activity
(
user_id,
component,
`type`,
`action`,
content,
primary_link,
item_id,
secondary_item_id,
date_recorded,
hide_sitewide,
mptt_left,
mptt_right
)
VALUES(
1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
)
The best way I can think of to accomplish this is via sp_addlinkedserver. You need to make sure that whatever account you use to add the link (via sp_addlinkedsrvlogin) has permissions to the table you're joining, but then once the link is established, you can call the server by name, i.e.:
SELECT *
FROM server1table
INNER JOIN server2.database.dbo.server2table ON .....
i faced same problem but i solve using this code
html2canvas(body,{
onrendered:function(canvas){
var pdf=new jsPDF("p", "mm", "a4");
var width = pdf.internal.pageSize.getWidth();
var height = pdf.internal.pageSize.getHeight();
pdf.addImage(canvas, 'JPEG', 0, 0,width,height);
pdf.save('test11.pdf');
}
})
You didn't want an Excel-based solution but since I had the same problem today and wanted to test using other Office Applications functions I wrote the function below.
Limitations:
Tested calling Excel 2010 from Visio 2010
Option Base 1
Private Function sort_array_2D_excel(array_2D, array_sortkeys, Optional array_sortorders, Optional tag_header As String = "Guess", Optional tag_matchcase As String = "False")
' Dependencies: Excel; Tools > References > Microsoft Excel [Version] Object Library
Dim excel_application As Excel.Application
Dim excel_workbook As Excel.Workbook
Dim excel_worksheet As Excel.Worksheet
Set excel_application = CreateObject("Excel.Application")
excel_application.Visible = True
excel_application.ScreenUpdating = False
excel_application.WindowState = xlNormal
Set excel_workbook = excel_application.Workbooks.Add
excel_workbook.Activate
Set excel_worksheet = excel_workbook.Worksheets.Add
excel_worksheet.Activate
excel_worksheet.Visible = xlSheetVisible
Dim excel_range As Excel.Range
Set excel_range = excel_worksheet.Range("A1").Resize(UBound(array_2D, 1) - LBound(array_2D, 1) + 1, UBound(array_2D, 2) - LBound(array_2D, 2) + 1)
excel_range = array_2D
For i_sortkey = LBound(array_sortkeys) To UBound(array_sortkeys)
If IsNumeric(array_sortkeys(i_sortkey)) Then
sortkey_range = Chr(array_sortkeys(i_sortkey) + 65 - 1) & "1"
Set array_sortkeys(i_sortkey) = excel_worksheet.Range(sortkey_range)
Else
MsgBox "Error in sortkey parameter:" & vbLf & "array_sortkeys(" & i_sortkey & ") = " & array_sortkeys(i_sortkey) & vbLf & "Terminating..."
End
End If
Next i_sortkey
For i_sortorder = LBound(array_sortorders) To UBound(array_sortorders)
Select Case LCase(array_sortorders(i_sortorder))
Case "asc"
array_sortorders(i_sortorder) = XlSortOrder.xlAscending
Case "desc"
array_sortorders(i_sortorder) = XlSortOrder.xlDescending
Case Else
array_sortorders(i_sortorder) = XlSortOrder.xlAscending
End Select
Next i_sortorder
Select Case LCase(tag_header)
Case "yes"
tag_header = Excel.xlYes
Case "no"
tag_header = Excel.xlNo
Case "guess"
tag_header = Excel.xlGuess
Case Else
tag_header = Excel.xlGuess
End Select
Select Case LCase(tag_matchcase)
Case "true"
tag_matchcase = True
Case "false"
tag_matchcase = False
Case Else
tag_matchcase = False
End Select
Select Case (UBound(array_sortkeys) - LBound(array_sortkeys) + 1)
Case 1
Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Header:=tag_header, MatchCase:=tag_matchcase)
Case 2
Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Key2:=array_sortkeys(2), Order2:=array_sortorders(2), Header:=tag_header, MatchCase:=tag_matchcase)
Case 3
Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Key2:=array_sortkeys(2), Order2:=array_sortorders(2), Key3:=array_sortkeys(3), Order3:=array_sortorders(3), Header:=tag_header, MatchCase:=tag_matchcase)
Case Else
MsgBox "Error in sortkey parameter:" & vbLf & "Maximum number of sort columns is 3!" & vbLf & "Currently passed: " & (UBound(array_sortkeys) - LBound(array_sortkeys) + 1)
End
End Select
For i_row = 1 To excel_range.Rows.Count
For i_column = 1 To excel_range.Columns.Count
array_2D(i_row, i_column) = excel_range(i_row, i_column)
Next i_column
Next i_row
excel_workbook.Close False
excel_application.Quit
Set excel_worksheet = Nothing
Set excel_workbook = Nothing
Set excel_application = Nothing
sort_array_2D_excel = array_2D
End Function
Private Sub test_sort()
array_unsorted = dim_sort_array()
Call msgbox_array(array_unsorted)
array_sorted = sort_array_2D_excel(array_unsorted, Array(2, 1, 3), Array("desc", "", "asdas"), "yes", "False")
Call msgbox_array(array_sorted)
End Sub
Private Function dim_sort_array()
Dim array_unsorted(1 To 5, 1 To 3) As String
i_row = 0
i_row = i_row + 1
array_unsorted(i_row, 1) = "Column1": array_unsorted(i_row, 2) = "Column2": array_unsorted(i_row, 3) = "Column3"
i_row = i_row + 1
array_unsorted(i_row, 1) = "OR": array_unsorted(i_row, 2) = "A": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2)
i_row = i_row + 1
array_unsorted(i_row, 1) = "XOR": array_unsorted(i_row, 2) = "A": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2)
i_row = i_row + 1
array_unsorted(i_row, 1) = "NOT": array_unsorted(i_row, 2) = "B": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2)
i_row = i_row + 1
array_unsorted(i_row, 1) = "AND": array_unsorted(i_row, 2) = "A": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & "_" & array_unsorted(i_row, 2)
dim_sort_array = array_unsorted
End Function
Sub msgbox_array(array_2D, Optional string_info As String = "2D array content:")
msgbox_string = string_info & vbLf
For i_row = LBound(array_2D, 1) To UBound(array_2D, 1)
msgbox_string = msgbox_string & vbLf & i_row & vbTab
For i_column = LBound(array_2D, 2) To UBound(array_2D, 2)
msgbox_string = msgbox_string & array_2D(i_row, i_column) & vbTab
Next i_column
Next i_row
MsgBox msgbox_string
End Sub
If anybody tests this using other versions of office please post here if there are any problems.
I'm assuming that you're trying to deal with Ajax navigation and not trying to prevent your users from using the back button, which violates just about every tenet of UI development ever.
Here's some possible solutions: JQuery History Salajax A Better Ajax Back Button
Try this, but you can adjust frame size with bounds and edit title.
package co.form.Try;
import javax.swing.JFrame;
public class Form {
public static void main(String[] args) {
JFrame obj =new JFrame();
obj.setBounds(10,10,700,600);
obj.setTitle("Application Form");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I did something else. I wanted to replace a word, in lists off lists, that contained phrases. I wanted to replace that sttring / word with a new word that will be a join between string and number, and that number / digit will indicate the position of the phrase / sublist / lists of lists.
That is, I replaced a string with a string and an incremental number that follow it.
myoldlist_1=[[' myoldword'],[''],['tttt myoldword'],['jjjj ddmyoldwordd']]
No_ofposition=[]
mynewlist_2=[]
for i in xrange(0,4,1):
mynewlist_2.append([x.replace('myoldword', "%s" % i+"_mynewword") for x in myoldlist_1[i]])
if len(mynewlist_2[i])>0:
No_ofposition.append(i)
mynewlist_2
No_ofposition
David's answer works fine if you're only using it for outputting to a file or displaying on the screen, but if a function or library requires a char* for parsing, then this method works best:
// copy QString to char*
QString filename = "C:\dev\file.xml";
char* cstr;
string fname = filename.toStdString();
cstr = new char [fname.size()+1];
strcpy( cstr, fname.c_str() );
// function that requires a char* parameter
parseXML(cstr);
Extension methods:
public static string Repeat(this string s, int n)
{
return new String(Enumerable.Range(0, n).SelectMany(x => s).ToArray());
}
public static string Repeat(this char c, int n)
{
return new String(c, n);
}
Another alternative, if you already have an instance of the object created and you want to add it as an @autowired dependency to initialize all the internal @autowired variables, could be the following:
@Autowired
private AutowireCapableBeanFactory autowireCapableBeanFactory;
public void doStuff() {
YourObject obj = new YourObject("Value X", "etc");
autowireCapableBeanFactory.autowireBean(obj);
}
You can use 2 methods:
<div [ngStyle]="{'background-image': 'url("' + photo + '")'}"></div>
<div [style.background-image]="'url("' + photo + '")'"></div>
Note: it is important to surround the URL with " char.
Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")
' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close
' Write file
outFile.write (strRetVal)
outFile.Close
When you cast an object reference you are just casting the type of the reference, not the type of the object. casting won't change the actual type of the object.
Java doesn't have implicit rules for converting Object types. (Unlike primitives)
Instead you need to provide how to convert one type to another and call it manually.
public class TestA {}
public class TestB extends TestA{
TestB(TestA testA) {
// build a TestB from a TestA
}
}
List<TestA> result = ....
List<TestB> data = new List<TestB>();
for(TestA testA : result) {
data.add(new TestB(testA));
}
This is more verbose than in a language with direct support, but it works and you shouldn't need to do this very often.
The only time you would use |
or &
instead of ||
or &&
is when you have very simple boolean expressions and the cost of short cutting (i.e. a branch) is greater than the time you save by not evaluating the later expressions.
However, this is a micro-optimisation which rarely matters except in the most low level code.
For readonly/disabled and other attributes with true/false values
$(':submit').attr('disabled', function(_, attr){ return !attr});
It is technically approved that MD5 is faster than SHA256 so in just verifying file integrity it will be sufficient and better for performance.
You are able to checkout the following resources:
If the behavior of for(... in ...) is acceptable/necessary for your purposes, you can tell tslint to allow it.
in tslint.json, add this to the "rules" section.
"forin": false
Otherwise, @Maxxx has the right idea with
for (const field of Object.keys(this.formErrors)) {
Small update.... Make sure you use EditedFormattedValue
instead of value
as I tried value
but it never give right status that is checked/unchecked most of the site still use value
but as used in latest c# 2010 express below is one way to access..
grdJobDetails.Rows[e.RowIndex].Cells[0].EditedFormattedValue
Also _CellValueChanged
event suggested or used by few must be usable for some cases but if you are looking for every check/uncheck of cell make sure you use _CellContentClick
else per my notice I see not every time _CellValueChanged
is fired.. that is if the same checkbox is clicked over & over again it does not fire _CellValueChanged
but if you click alternately for example you have two chekbox & click one after other _CellValueChanged
event will be fired but usually if looking for event to fire everytime the any cell is check/uncheck _CellValueChanged
is not fired.
Maybe it is easier to convert the Date into the actual integer 20110506105524
and then convert this into a string:
function printDate() {
var temp = new Date();
var dateInt =
((((temp.getFullYear() * 100 +
temp.getMonth() + 1) * 100 +
temp.getDate()) * 100 +
temp.getHours()) * 100 +
temp.getMinutes()) * 100 +
temp.getSeconds();
debug ( '' + dateInt ); // convert to String
}
When temp.getFullYear() < 1000
the result will be one (or more) digits shorter.
Caution: this wont work with millisecond precision (i.e. 17 digits) since Number.MAX_SAFE_INTEGER is 9007199254740991
which is only 16 digits.
**Different way to Find Element:**
IEDriver.findElement(By.id("id"));
IEDriver.findElement(By.linkText("linkText"));
IEDriver.findElement(By.xpath("xpath"));
IEDriver.findElement(By.xpath(".//*[@id='id']"));
IEDriver.findElement(By.xpath("//button[contains(.,'button name')]"));
IEDriver.findElement(By.xpath("//a[contains(.,'text name')]"));
IEDriver.findElement(By.xpath("//label[contains(.,'label name')]"));
IEDriver.findElement(By.xpath("//*[contains(text(), 'your text')]");
Check Case Sensitive:
IEDriver.findElement(By.xpath("//*[contains(lower-case(text()),'your text')]");
For exact match:
IEDriver.findElement(By.xpath("//button[text()='your text']");
**Find NG-Element:**
Xpath == //td[contains(@ng-show,'childsegment.AddLocation')]
CssSelector == .sprite.icon-cancel
You must have the definition of class B
before you use the class. How else would the compiler otherwise know that there exists such a function as B::add
?
Either define class B
before class A
, or move the body of A::doSomething
to after class B
have been defined, like
class B;
class A
{
B* b;
void doSomething();
};
class B
{
A* a;
void add() {}
};
void A::doSomething()
{
b->add();
}
The following worked for me:
Registry Editor
(press windows key, type regedit
and hit Enter
) .HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
and clear the values.HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
.Here's a technique that allows you to center ANY content both vertically and horizontally!
Basically, you just need a two containers and make sure your elements meet the following criteria.
display: table;
display: table-cell;
vertical-align: middle;
text-align: center;
display: inline-block;
If you use this technique, just add your image (along with any other content you want to go with it) to the content box.
body {_x000D_
margin : 0;_x000D_
}_x000D_
_x000D_
.outer-container {_x000D_
position : absolute;_x000D_
display: table;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background: #ccc;_x000D_
}_x000D_
_x000D_
.inner-container {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.centered-content {_x000D_
display: inline-block;_x000D_
background: #fff;_x000D_
padding : 12px;_x000D_
border : 1px solid #000;_x000D_
}_x000D_
_x000D_
img {_x000D_
max-width : 120px;_x000D_
}
_x000D_
<div class="outer-container">_x000D_
<div class="inner-container">_x000D_
<div class="centered-content">_x000D_
<img src="https://i.stack.imgur.com/mRsBv.png" />_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
See also this Fiddle!
I agree with thomaux that the initialization type checking error is a TypeScript bug. However, I still wanted to find a way to declare and initialize a Dictionary in a single statement with correct type checking. This implementation is longer, however it adds additional functionality such as a containsKey(key: string)
and remove(key: string)
method. I suspect that this could be simplified once generics are available in the 0.9 release.
First we declare the base Dictionary class and Interface. The interface is required for the indexer because classes cannot implement them.
interface IDictionary {
add(key: string, value: any): void;
remove(key: string): void;
containsKey(key: string): bool;
keys(): string[];
values(): any[];
}
class Dictionary {
_keys: string[] = new string[];
_values: any[] = new any[];
constructor(init: { key: string; value: any; }[]) {
for (var x = 0; x < init.length; x++) {
this[init[x].key] = init[x].value;
this._keys.push(init[x].key);
this._values.push(init[x].value);
}
}
add(key: string, value: any) {
this[key] = value;
this._keys.push(key);
this._values.push(value);
}
remove(key: string) {
var index = this._keys.indexOf(key, 0);
this._keys.splice(index, 1);
this._values.splice(index, 1);
delete this[key];
}
keys(): string[] {
return this._keys;
}
values(): any[] {
return this._values;
}
containsKey(key: string) {
if (typeof this[key] === "undefined") {
return false;
}
return true;
}
toLookup(): IDictionary {
return this;
}
}
Now we declare the Person specific type and Dictionary/Dictionary interface. In the PersonDictionary note how we override values()
and toLookup()
to return the correct types.
interface IPerson {
firstName: string;
lastName: string;
}
interface IPersonDictionary extends IDictionary {
[index: string]: IPerson;
values(): IPerson[];
}
class PersonDictionary extends Dictionary {
constructor(init: { key: string; value: IPerson; }[]) {
super(init);
}
values(): IPerson[]{
return this._values;
}
toLookup(): IPersonDictionary {
return this;
}
}
And here is a simple initialization and usage example:
var persons = new PersonDictionary([
{ key: "p1", value: { firstName: "F1", lastName: "L2" } },
{ key: "p2", value: { firstName: "F2", lastName: "L2" } },
{ key: "p3", value: { firstName: "F3", lastName: "L3" } }
]).toLookup();
alert(persons["p1"].firstName + " " + persons["p1"].lastName);
// alert: F1 L2
persons.remove("p2");
if (!persons.containsKey("p2")) {
alert("Key no longer exists");
// alert: Key no longer exists
}
alert(persons.keys().join(", "));
// alert: p1, p3
If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-
[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb
Mysql would then open this file for each user account read the credentials and open the selected database.
Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.
The -i
option streams the edited content into a new file and then renames it behind the scenes, anyway.
Example:
sed -i 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename
and
sed -i '' 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename
on macOS.
You should put the include angular line first, before including any other js file
My understanding is that this isn't easy at all to do cross-browser. Instead of trying to manipulate the checkbox control, you could always build your own implementation using images, javascript, and hidden input fields. I'm assuming this is similar to what niceforms is (from Staicu lonut's answer above), but wouldn't be particularly difficult to implement. I believe jQuery has a plugin to allow for this custom behavior as well (will look for the link and post here if I can find it).
mysqli_select_db()
should have 2 parameters, the connection link and the database name -
mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));
Using mysqli_error
in the die statement will tell you exactly what is wrong as opposed to a generic error message.
This is what I do when I need to add months or years and don't want to import more libraries. Just create a datetime.date() object, call add_month(date) to add a month and add_year(date) to add a year.
import datetime
__author__ = 'Daniel Margarido'
# Check if the int given year is a leap year
# return true if leap year or false otherwise
def is_leap_year(year):
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return True
else:
return False
else:
return True
else:
return False
THIRTY_DAYS_MONTHS = [4, 6, 9, 11]
THIRTYONE_DAYS_MONTHS = [1, 3, 5, 7, 8, 10, 12]
# Inputs -> month, year Booth integers
# Return the number of days of the given month
def get_month_days(month, year):
if month in THIRTY_DAYS_MONTHS: # April, June, September, November
return 30
elif month in THIRTYONE_DAYS_MONTHS: # January, March, May, July, August, October, December
return 31
else: # February
if is_leap_year(year):
return 29
else:
return 28
# Checks the month of the given date
# Selects the number of days it needs to add one month
# return the date with one month added
def add_month(date):
current_month_days = get_month_days(date.month, date.year)
next_month_days = get_month_days(date.month + 1, date.year)
delta = datetime.timedelta(days=current_month_days)
if date.day > next_month_days:
delta = delta - datetime.timedelta(days=(date.day - next_month_days) - 1)
return date + delta
def add_year(date):
if is_leap_year(date.year):
delta = datetime.timedelta(days=366)
else:
delta = datetime.timedelta(days=365)
return date + delta
# Validates if the expected_value is equal to the given value
def test_equal(expected_value, value):
if expected_value == value:
print "Test Passed"
return True
print "Test Failed : " + str(expected_value) + " is not equal to " str(value)
return False
# Test leap year
print "---------- Test leap year ----------"
test_equal(True, is_leap_year(2012))
test_equal(True, is_leap_year(2000))
test_equal(False, is_leap_year(1900))
test_equal(False, is_leap_year(2002))
test_equal(False, is_leap_year(2100))
test_equal(True, is_leap_year(2400))
test_equal(True, is_leap_year(2016))
# Test add month
print "---------- Test add month ----------"
test_equal(datetime.date(2016, 2, 1), add_month(datetime.date(2016, 1, 1)))
test_equal(datetime.date(2016, 6, 16), add_month(datetime.date(2016, 5, 16)))
test_equal(datetime.date(2016, 3, 15), add_month(datetime.date(2016, 2, 15)))
test_equal(datetime.date(2017, 1, 12), add_month(datetime.date(2016, 12, 12)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 31)))
test_equal(datetime.date(2015, 3, 1), add_month(datetime.date(2015, 1, 31)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 30)))
test_equal(datetime.date(2016, 4, 30), add_month(datetime.date(2016, 3, 30)))
test_equal(datetime.date(2016, 5, 1), add_month(datetime.date(2016, 3, 31)))
# Test add year
print "---------- Test add year ----------"
test_equal(datetime.date(2016, 2, 2), add_year(datetime.date(2015, 2, 2)))
test_equal(datetime.date(2001, 2, 2), add_year(datetime.date(2000, 2, 2)))
test_equal(datetime.date(2100, 2, 2), add_year(datetime.date(2099, 2, 2)))
test_equal(datetime.date(2101, 2, 2), add_year(datetime.date(2100, 2, 2)))
test_equal(datetime.date(2401, 2, 2), add_year(datetime.date(2400, 2, 2)))
Probably the fastest way is:
myString.All(c => char.IsDigit(c))
Note: it will return True in case your string is empty which is incorrect (if you not considering empty as valid number/digit )
In Pyspark, using parenthesis around each condition is the key to using multiple column names in the join condition.
joined_df = df1.join(df2,
(df1['name'] == df2['name']) &
(df1['phone'] == df2['phone'])
)
You can try to check if your web properties for the project didn't switch to IIS Express and change it back to IIS Local
Wiper is cool, good thing about it is I don't have to type '()' around it. Here is slight variation to it
# wiper.py
import os
class Cls(object):
def __repr__(self):
os.system('cls')
return ''
The usage is quite simple:
>>> cls = Cls()
>>> cls # this will clear console.
I had the same error. I deleted the android repository from android sdk manager and reinstalled it. It worked.
There are multiple ways you can do it:
Solution 1:
class MainActivity extends AppCompactActivity {
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
Solution 2:
In activity_main.xml file, simply add:
<android:KeepScreenOn="true"/>
My advice: please don't use WakeLock. If you use it, you have to define extra permission, and mostly this thing is useful in CPU's development environment.
Also, make sure to turn off the screen while closing the activity. You can do it in this way:
public void onDestry() {
getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
As far as I know, there is no such a thing as iOS emulator on windows or linux, there are only some gameengines that enable you to compile same code for both iOS and windows or linux and there is a toolchain to compile iOS application using linux. none of them are realy emulator/simulator things. and to use that toolchain you need a jailbreaked iOS device to test binary file created using toolchain. I mean linux itself can't run the binary created itself. and by the way even in mac simulator is just an intermediate program which runs mac-compiled binary, since if you change compiling for iOS from simulator or the other way, all the files are rebuild. and also there are some real differences, like iOS is a case-sensitive operation while simulator is not.
so the best solution is to buy an iOS device yourself.
When you said, "our code base does not lend itself to easy testing" is the first sign of a code smell. Writing Unit Tests means you typically write code differently in order to make the code more testable. This is a good thing in my opinion as what I've seen over the years in writing code that I had to write tests for, it forced me to put forth a better design.
var str = 'Hello World',
i = 3,
result = str.substr(0, i-1)+str.substring(i);
alert(result);
Value of i
should not be less then 1
.
It appears that the functionality previously present in the react-cookie
npm package has been moved to universal-cookie
. The relevant example from the universal-cookie repository now is:
import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('myCat', 'Pacman', { path: '/' });
console.log(cookies.get('myCat')); // Pacman
The biggest advantage is enum Singletons are easy to write and thread-safe :
public enum EasySingleton{
INSTANCE;
}
and
/**
* Singleton pattern example with Double checked Locking
*/
public class DoubleCheckedLockingSingleton{
private volatile DoubleCheckedLockingSingleton INSTANCE;
private DoubleCheckedLockingSingleton(){}
public DoubleCheckedLockingSingleton getInstance(){
if(INSTANCE == null){
synchronized(DoubleCheckedLockingSingleton.class){
//double checking Singleton instance
if(INSTANCE == null){
INSTANCE = new DoubleCheckedLockingSingleton();
}
}
}
return INSTANCE;
}
}
both are similar and it handled Serialization by themselves by implementing
//readResolve to prevent another instance of Singleton
private Object readResolve(){
return INSTANCE;
}
spring.jackson.serialization-inclusion=non_null
used to work for us
But when we upgraded spring boot version to 1.4.2.RELEASE or higher, it stopped working.
Now, another property spring.jackson.default-property-inclusion=non_null
is doing the magic.
in fact, serialization-inclusion
is deprecated. This is what my intellij throws at me.
Deprecated: ObjectMapper.setSerializationInclusion was deprecated in Jackson 2.7
So, start using spring.jackson.default-property-inclusion=non_null
instead
Sometimes I have been getting some errors when you want to pass httpBody serialized to Data
from Dictionary
, which on most cases is due to the wrong encoding or malformed data due to non NSCoding conforming objects in the Dictionary
.
Depending on your requirements one easy solution would be to create a String
instead of Dictionary
and convert it to Data
. You have the code samples below written on Objective-C
and Swift 3.0
.
// Create the URLSession on the default configuration
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
// Setup the request with URL
NSURL *url = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = @"api_key=APIKEY&[email protected]&password=password";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];
// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:postData];
// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Handle your response here
}];
// Fire the request
[dataTask resume];
// Create the URLSession on the default configuration
let defaultSessionConfiguration = URLSessionConfiguration.default
let defaultSession = URLSession(configuration: defaultSessionConfiguration)
// Setup the request with URL
let url = URL(string: "yourURL")
var urlRequest = URLRequest(url: url!) // Note: This is a demo, that's why I use implicitly unwrapped optional
// Convert POST string parameters to data using UTF8 Encoding
let postParams = "api_key=APIKEY&[email protected]&password=password"
let postData = postParams.data(using: .utf8)
// Set the httpMethod and assign httpBody
urlRequest.httpMethod = "POST"
urlRequest.httpBody = postData
// Create dataTask
let dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in
// Handle your response here
}
// Fire the request
dataTask.resume()
Unfortunately, it's not that easy. There are more complicated things behind the scenes in JBoss (most of them ClassLoader related) that will prevent you from HOT-DEPLOYING your application.
For example, you are not going to be able to HOT-DEPLOY if some of your classes signatures change.
So far, using MyEclipse IDE (a paid distribution of Eclipse) is the only thing I found that does hot deploying quite successfully. Not 100% accuracy though. But certainly better than JBoss Tools, Netbeans or any other Eclipse based solution.
I've been looking for free tools to accomplish what you've just described by asking people in StackOverflow if you want to take a look.
Ensure that you have following JARS in place: 1) jackson-core-asl-1.9.13 2) jackson-jaxrs-1.9.13 3) jackson-mapper-asl-1.9.13 4) jackson-xc-1.9.13
I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.
In C++, consider the State pattern.
Use document.execCommand('copy')
. Supported in the latest versions of Chrome
, Firefox
, Edge
, and Safari
.
function copyText(text){_x000D_
function selectElementText(element) {_x000D_
if (document.selection) {_x000D_
var range = document.body.createTextRange();_x000D_
range.moveToElementText(element);_x000D_
range.select();_x000D_
} else if (window.getSelection) {_x000D_
var range = document.createRange();_x000D_
range.selectNode(element);_x000D_
window.getSelection().removeAllRanges();_x000D_
window.getSelection().addRange(range);_x000D_
}_x000D_
}_x000D_
var element = document.createElement('DIV');_x000D_
element.textContent = text;_x000D_
document.body.appendChild(element);_x000D_
selectElementText(element);_x000D_
document.execCommand('copy');_x000D_
element.remove();_x000D_
}_x000D_
_x000D_
_x000D_
var txt = document.getElementById('txt');_x000D_
var btn = document.getElementById('btn');_x000D_
btn.addEventListener('click', function(){_x000D_
copyText(txt.value);_x000D_
})
_x000D_
<input id="txt" value="Hello World!" />_x000D_
<button id="btn">Copy To Clipboard</button>
_x000D_
$(function () {
$('input[type=checkbox]').click(function () {
var chks = document.getElementById('<%= chkRoleInTransaction.ClientID %>').getElementsByTagName('INPUT');
for (i = 0; i < chks.length; i++) {
chks[i].checked = false;
}
if (chks.length > 1)
$(this)[0].checked = true;
});
});
I would also like to add a solution that uses slots:
class Point:
__slots__ = ["x", "y"]
def __init__(self, x, y):
self.x = x
self.y = y
Definitely check the documentation for slots but a quick explanation of slots is that it is python's way of saying: "If you can lock these attributes and only these attributes into the class such that you commit that you will not add any new attributes once the class is instantiated (yes you can add new attributes to a class instance, see example below) then I will do away with the large memory allocation that allows for adding new attributes to a class instance and use just what I need for these slotted attributes".
Example of adding attributes to class instance (thus not using slots):
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p1 = Point(3,5)
p1.z = 8
print(p1.z)
Output: 8
Example of trying to add attributes to class instance where slots was used:
class Point:
__slots__ = ["x", "y"]
def __init__(self, x, y):
self.x = x
self.y = y
p1 = Point(3,5)
p1.z = 8
Output: AttributeError: 'Point' object has no attribute 'z'
This can effectively works as a struct and uses less memory than a class (like a struct would, although I have not researched exactly how much). It is recommended to use slots if you will be creating a large amount of instances of the object and do not need to add attributes. A point object is a good example of this as it is likely that one may instantiate many points to describe a dataset.
Consider the Switch Function as an alternative to multiple IIf()
expressions. It will return the value from the first expression/value pair where the expression evaluates as True, and ignore any remaining pairs. The concept is similar to the SELECT ... CASE
approach you referenced but which is not available in Access SQL.
If you want to display a calculated field as commission
:
SELECT
Switch(
OpeningBalance < 5001, 20,
OpeningBalance < 10001, 30,
OpeningBalance < 20001, 40,
OpeningBalance >= 20001, 50
) AS commission
FROM YourTable;
If you want to store that calculated value to a field named commission
:
UPDATE YourTable
SET commission =
Switch(
OpeningBalance < 5001, 20,
OpeningBalance < 10001, 30,
OpeningBalance < 20001, 40,
OpeningBalance >= 20001, 50
);
Either way, see whether you find Switch()
easier to understand and manage. Multiple IIf()s
can become mind-boggling as the number of conditions grows.
self.materials
is a dict
and by default you are iterating over just the keys (which are strings).
Since self.materials
has more than two keys*, they can't be unpacked into the tuple
"k, m
", hence the ValueError
exception is raised.
In Python 2.x, to iterate over the keys and the values (the tuple
"k, m
"), we use self.materials.iteritems()
.
However, since you're throwing the key away anyway, you may as well simply iterate over the dictionary's values:
for m in self.materials.itervalues():
In Python 3.x, prefer dict.values()
(which returns a dictionary view object):
for m in self.materials.values():
I was trying to get clang to work (which also requires 6.0.15), and while poking around I found it was installed at /usr/local/lib/libstdc++.so.6.0.15
. It installed there when I installed graphite (an experimental gcc version).
If you need access to libraries at that location, then you’ll need to define LD_LIBRARY_PATH
as:
export LD_LIBRARY_PATH=/usr/local/lib:/usr/lib:/usr/local/lib64:/usr/lib64
I was able to get clang to work after doing this. Hope that is helpful to someone.
To make it work, I installed latex, typical latex extra, and pandoc.
With ubuntu:
sudo apt-get install texlive texlive-latex-extra pandoc
it takes some times: several 100 Mb to download. I read somewhere that you can use --no-install-recommends
for texlive and extra to reduce to the dl.
You can set up a express proxy server using http-proxy-middleware to bypass CORS:
const express = require('express');
const proxy = require('http-proxy-middleware');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(express.static(__dirname));
app.use('/proxy', proxy({
pathRewrite: {
'^/proxy/': '/'
},
target: 'https://server.com',
secure: false
}));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(port);
console.log('Server started');
From your react app all requests should be sent to /proxy endpoint and they will be redirected to the intended server.
const URL = `/proxy/${PATH}`;
return axios.get(URL);
sum(d.values()) - "d" -> Your dictionary Variable
double value = 2.8032739273;
String formattedValue = value.toStringAsFixed(3);
PHP 7.4 style:
$ids = array_map(fn(string $x): int => (int) $x, explode(',', $string));
Something is clearly corrupt in your Laravel setup and it is very hard to track without more info about your environment. Usually these 2 commands help you resolve such issues
php artisan clear-compiled
composer dump-autoload
If nothing else helps then I recommend you to install fresh Laravel 5 app and copy your application logic over, it should take around 15 min or so.
For compatibility when ajax is not available, set .val('') or it will resend the last ajax-uploaded file that is still present in the input. The following should properly clear the input whilst retaining .on() events:
var input = $("input[type='file']");
input.html(input.html()).val('');
Try this code
<input type="TextBox" ID="yearBox" border="0" disabled>
$('#yearSelected li').on('click', function(){
$('#yearBox').val($(this).text());
});
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fas fa-calendar-alt"></i> <span>Academic Years</span> <i class="fas fa-chevron-down"></i> </a>
<ul class="dropdown-menu">
<li>
<ul class="menu" id="yearSelected">
<li><a href="#">2014-2015</a></li>
<li><a href="#">2015-2016</a></li>
<li><a href="#">2016-2017</a></li>
<li><a href="#">2017-2018</a></li>
</ul>
</li>
</ul>
its work for me
It seems like the visibility problem - the parent controller doesn't see the Component you are trying to wire.
Try to add
@ComponentScan("path to respective Component")
to the parent controller.
To add rows to existing DataTable in Dataset:
DataRow drPartMtl = DSPartMtl.Tables[0].NewRow();
drPartMtl["Group"] = "Group";
drPartMtl["BOMPart"] = "BOMPart";
DSPartMtl.Tables[0].Rows.Add(drPartMtl);
// logout
if(isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header('location:login.php');
}
?>
In case someone needs a more involved example on how to do cross-database queries, here's an example that cleans up the databasechangeloglock
table on every database that has it:
CREATE EXTENSION IF NOT EXISTS dblink;
DO
$$
DECLARE database_name TEXT;
DECLARE conn_template TEXT;
DECLARE conn_string TEXT;
DECLARE table_exists Boolean;
BEGIN
conn_template = 'user=myuser password=mypass dbname=';
FOR database_name IN
SELECT datname FROM pg_database
WHERE datistemplate = false
LOOP
conn_string = conn_template || database_name;
table_exists = (select table_exists_ from dblink(conn_string, '(select Count(*) > 0 from information_schema.tables where table_name = ''databasechangeloglock'')') as (table_exists_ Boolean));
IF table_exists THEN
perform dblink_exec(conn_string, 'delete from databasechangeloglock');
END IF;
END LOOP;
END
$$
In my case ESLint was disabled in my workspace. I had to enable it in vscode extensions settings.
There's a duplicate question with a simpler answer using cut:
svn status | grep '\!' | cut -d\ -f2-
-d
specifies the delimeter (space), -f
specifies the list of columns (all starting with the 2nd)
VBA can use the dictionary structure of Scripting.Runtime
.
And its implementation is actually a fancy one - just by doing myDict(x) = y
, it checks whether there is a key x
in the dictionary and if there is not such, it even creates it. If it is there, it uses it.
And it does not "yell" or "complain" about this extra step, performed "under the hood". Of course, you may check explicitly, whether a key exists with Dictionary.Exists(key)
. Thus, these 5 lines:
If myDict.exists("B") Then
myDict("B") = myDict("B") + i * 3
Else
myDict.Add "B", i * 3
End If
are the same as this 1 liner - myDict("B") = myDict("B") + i * 3
. Check it out:
Sub TestMe()
Dim myDict As Object, i As Long, myKey As Variant
Set myDict = CreateObject("Scripting.Dictionary")
For i = 1 To 3
Debug.Print myDict.Exists("A")
myDict("A") = myDict("A") + i
myDict("B") = myDict("B") + 5
Next i
For Each myKey In myDict.keys
Debug.Print myKey; myDict(myKey)
Next myKey
End Sub
You could try using FontAwesome. It contains a sort-icon (http://fontawesome.io/icon/sort/).
To do so, you would
need to include fontawesome:
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
and then simply use the fontawesome-icon instead of the default-bootstrap-icons in your th
's:
<th><b>#</b> <i class="fa fa-fw fa-sort"></i></th>
Hope that helps.
As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:
<?php
$world = _("World");
$str = <<<EOF
<p>Hello</p>
<p>$world</p>
EOF;
echo $str;
?>
a workaround idea that comes to mind is building a class with a magic getter method.
You would declare a class like this:
class Translator
{
public function __get($name) {
return _($name); // Does the gettext lookup
}
}
Initialize an object of the class at some point:
$translate = new Translator();
You can then use the following syntax to do a gettext lookup inside a HEREDOC block:
$str = <<<EOF
<p>Hello</p>
<p>{$translate->World}</p>
EOF;
echo $str;
?>
$translate->World
will automatically be translated to the gettext lookup thanks to the magic getter method.
To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!
, you will have to use the following notation:
$translate->{"Hello World!!!!!!"}
This is all untested but should work.
Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.
Looking, it turns out on my system there is an envsubst
command which is part of the gettext-base package.
So, this makes it easy:
envsubst < "source.txt" > "destination.txt"
Note if you want to use the same file for both, you'll have to use something like moreutil's sponge
, as suggested by Johnny Utahh: envsubst < "source.txt" | sponge "source.txt"
. (Because the shell redirect will otherwise empty the file before its read.)
pip-autoremove
(since it removes dependencies shared among other packages) and pip3 uninstall jupyter
just removed some packages, then do the following:sudo
may be needed as per your need.
python3 -m pip uninstall -y jupyter jupyter_core jupyter-client jupyter-console jupyterlab_pygments notebook qtconsole nbconvert nbformat
The above command will only uninstall jupyter
specific packages. I have not added other packages to uninstall since they might be shared among other packages (eg: Jinja2
is used by Flask
, ipython
is a separate set of packages themselves, tornado
again might be used by others).
In any case, all the dependencies are mentioned below(as of 21 Nov, 2020. jupyter==4.4.0
)
If you are sure you want to remove all the dependencies, then you can use Stan_MD's answer.
attrs
backcall
bleach
decorator
defusedxml
entrypoints
importlib-metadata
ipykernel
ipython
ipython-genutils
ipywidgets
jedi
Jinja2
jsonschema
jupyter
jupyter-client
jupyter-console
jupyter-core
jupyterlab-pygments
MarkupSafe
mistune
more-itertools
nbconvert
nbformat
notebook
pandocfilters
parso
pexpect
pickleshare
prometheus-client
prompt-toolkit
ptyprocess
Pygments
pyrsistent
python-dateutil
pyzmq
qtconsole
Send2Trash
six
terminado
testpath
tornado
traitlets
wcwidth
webencodings
widgetsnbextension
zipp
pip3 uninstall jupyter
pip3 uninstall jupyter_core
pip3 uninstall jupyter-client
pip3 uninstall jupyter-console
pip3 uninstall jupyterlab_pygments
pip3 uninstall notebook
pip3 uninstall qtconsole
pip3 uninstall nbconvert
pip3 uninstall nbformat
Uninstall jupyter
dist-packages:
pip3 uninstall jupyter
Uninstall jupyter_core
dist-packages (It also uninstalls following binaries: jupyter
, jupyter-migrate
,jupyter-troubleshoot
):
pip3 uninstall jupyter_core
Uninstall jupyter-client
:
pip3 uninstall jupyter-client
Uninstall jupyter-console
:
pip3 uninstall jupyter-console
Uninstall jupyter-notebook
(It also uninstalls following binaries: jupyter-bundlerextension
, jupyter-nbextension
, jupyter-notebook
, jupyter-serverextension
):
pip3 uninstall notebook
Uninstall jupyter-qtconsole
:
pip3 uninstall qtconsole
Uninstall jupyter-nbconvert
:
pip3 uninstall nbconvert
Uninstall jupyter-trust
:
pip3 uninstall nbformat
On VS2017 I installed the NuGet package: Microsoft.AspNet.WebPages
That did the trick.
Answer : I found this and wants to share it with you.
Sub Copier4()
Dim x As Integer
For x = 1 To ActiveWorkbook.Sheets.Count
'Loop through each of the sheets in the workbook
'by using x as the sheet index number.
ActiveWorkbook.Sheets(x).Copy _
After:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count)
'Puts all copies after the last existing sheet.
Next
End Sub
But the question, can we use it with following code to rename the sheets, if yes, how can we do so?
Sub CreateSheetsFromAList()
Dim MyCell As Range, MyRange As Range
Set MyRange = Sheets("Summary").Range("A10")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
For Each MyCell In MyRange
Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet
Next MyCell
End Sub