One way to get unbuffered output would be to use sys.stderr
instead of sys.stdout
or to simply call sys.stdout.flush()
to explicitly force a write to occur.
You could easily redirect everything printed by doing:
import sys; sys.stdout = sys.stderr
print "Hello World!"
Or to redirect just for a particular print
statement:
print >>sys.stderr, "Hello World!"
To reset stdout you can just do:
sys.stdout = sys.__stdout__
It can be something so silly as you are transferring the file via FTP to a target machine, you go and run the .JAR file but this was so big that it has not yet been finished transferred :) Yes it happened to me..
Here's a Python 3 version of the functions from @qneill 's answer:
import base64
def encode(key, clear):
enc = []
for i in range(len(clear)):
key_c = key[i % len(key)]
enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
enc.append(enc_c)
return base64.urlsafe_b64encode("".join(enc).encode()).decode()
def decode(key, enc):
dec = []
enc = base64.urlsafe_b64decode(enc).decode()
for i in range(len(enc)):
key_c = key[i % len(key)]
dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
dec.append(dec_c)
return "".join(dec)
The extra encode/decodes are needed because Python 3 has split strings/byte arrays into two different concepts, and updated their APIs to reflect that..
People have recommended MailChimp which is a good vendor for bulk email. If you're looking for a good vendor for transactional email, I might be able to help.
Over the past 6 months, we used four different SMTP vendors with the goal of figuring out which was the best one.
Here's a summary of what we found...
Conclusion
SendGrid was the best with Postmark coming in second place. We never saw any hesitation in send times with either of those two - in some cases we sent several hundred emails at once - and they both have the best ROI, given a solid featureset.
Firstly you need to create AdminClient bean:
@Bean
public AdminClient adminClient(){
Map<String, Object> configs = new HashMap<>();
configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,
StringUtils.arrayToCommaDelimitedString(new Object[]{"your bootstrap server address}));
return AdminClient.create(configs);
}
Then, you can use this script:
while (true) {
Map<String, ConsumerGroupDescription> groupDescriptionMap =
adminClient.describeConsumerGroups(Collections.singletonList(groupId))
.all()
.get(10, TimeUnit.SECONDS);
ConsumerGroupDescription consumerGroupDescription = groupDescriptionMap.get(groupId);
log.debug("Kafka consumer group ({}) state: {}",
groupId,
consumerGroupDescription.state());
if (consumerGroupDescription.state().equals(ConsumerGroupState.STABLE)) {
boolean isReady = true;
for (MemberDescription member : consumerGroupDescription.members()) {
if (member.assignment() == null || member.assignment().topicPartitions().isEmpty()) {
isReady = false;
}
}
if (isReady) {
break;
}
}
log.debug("Kafka consumer group ({}) is not ready. Waiting...", groupId);
TimeUnit.SECONDS.sleep(1);
}
This script will check the state of the consumer group every second till the state will be STABLE. Because all consumers assigned to topic partitions, you can conclude that server is running and ready.
I have tried the solution which redirects 405 to 200, and in production environment(in my case, it's Google Load Balancing with Nginx Docker container), this hack causes some 502 errors(Google Load Balancing error code: backend_early_response_with_non_error_status).
In the end, I have made this work properly by replacing Nginx with OpenResty which is completely compatible with Nginx and have more plugins.
With ngx_coolkit, Now Nginx(OpenResty) could serve static files with POST request properly, here is the config file in my case:
server {
listen 80;
location / {
override_method GET;
proxy_pass http://127.0.0.1:8080;
}
}
server {
listen 8080;
location / {
root /var/www/web-static;
index index.html;
add_header Cache-Control no-cache;
}
}
In the above config, I use override_method
offered by ngx_coolkit to override the HTTP Method to GET
.
Do you mean the conversion 011001100110111101101111
? foo
, for example? You just take the binary stream, split it into separate bytes (01100110
, 01101111
, 01101111
) and look up the ASCII character that corresponds to given number. For example, 01100110
is 102 in decimal and the ASCII character with code 102 is f
:
$ perl -E 'say 0b01100110'
102
$ perl -E 'say chr(102)'
f
(See what the chr
function does.) You can generalize this algorithm and have a different number of bits per character and different encodings, the point remains the same.
upstream
in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add
. Depending on what you select for this name, your git pull
usage will change. For example, if you use:
git remote add upstream git://github.com/somename/original-project.git
then you would use this to pull changes:
git pull upstream master
But, if you choose origin for the name of the remote repo, your commands would be:
To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git
And to pull: git pull origin master
This works...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Load Splash View Controller first
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"Splash"];
self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];
// Load other stuff that requires time
// Now load the main View Controller that you want
}
I was looking for this myself when we changed domain on our Wordpress website. It can't be done without some programming so this is what I did.
<?php
header("Content-Type: text/plain");
$host = "localhost";
$username = "root";
$password = "";
$database = "mydatabase";
$string_to_replace = 'old.example.com';
$new_string = 'new.example.com';
// Connect to database server
mysql_connect($host, $username, $password);
// Select database
mysql_select_db($database);
// List all tables in database
$sql = "SHOW TABLES FROM ".$database;
$tables_result = mysql_query($sql);
if (!$tables_result) {
echo "Database error, could not list tables\nMySQL error: " . mysql_error();
exit;
}
echo "In these fields '$string_to_replace' have been replaced with '$new_string'\n\n";
while ($table = mysql_fetch_row($tables_result)) {
echo "Table: {$table[0]}\n";
$fields_result = mysql_query("SHOW COLUMNS FROM ".$table[0]);
if (!$fields_result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($fields_result) > 0) {
while ($field = mysql_fetch_assoc($fields_result)) {
if (stripos($field['Type'], "VARCHAR") !== false || stripos($field['Type'], "TEXT") !== false) {
echo " ".$field['Field']."\n";
$sql = "UPDATE ".$table[0]." SET ".$field['Field']." = replace(".$field['Field'].", '$string_to_replace', '$new_string')";
mysql_query($sql);
}
}
echo "\n";
}
}
mysql_free_result($tables_result);
?>
Hope it helps anyone who's stumbling into this problem in the future :)
.fadeOut{
background-color: rgba(255, 0, 0, 0.83);
border-radius: 8px;
box-shadow: silver 3px 3px 5px 0px;
border: 2px dashed yellow;
padding: 3px;
}
.fadeOut.end{
transition: all 1s ease-in-out;
background-color: rgba(255, 0, 0, 0.0);
box-shadow: none;
border: 0px dashed yellow;
border-radius: 0px;
}
In events handler you can get id as follows
function show(btn) {_x000D_
console.log('Button id:',btn.id);_x000D_
}
_x000D_
<button id="myButtonId" onclick="show(this)">Click me</button>
_x000D_
This only worked right for me when including strip.white = TRUE
in the read.csv
command.
(I found the solution here.)
If anyone wonders for the Array
version, it goes like this:
int i = Array.FindIndex(yourArray, x => x == itemYouWant);
You could possibly make your own Map.of
(which is only available in Java 9 and higher) method easily in 2 easy ways
Example
public <K,V> Map<K,V> mapOf(K k1, V v1, K k2, V v2 /* perhaps more parameters */) {
return new HashMap<K, V>() {{
put(k1, v1);
put(k2, v2);
// etc...
}};
}
You can also make this using a list, instead of making a lot of methods for a certain set of parameters.
Example
public <K, V> Map<K, V> mapOf(List<K> keys, List<V> values) {
if(keys.size() != values.size()) {
throw new IndexOutOfBoundsException("amount of keys and values is not equal");
}
return new HashMap<K, V>() {{
IntStream.range(0, keys.size()).forEach(index -> put(keys.get(index), values.get(index)));
}};
}
Note It is not recommended to use this for everything as this makes an anonymous class every time you use this.
You can do it using the fs-extra
module very easily:
const fse = require('fs-extra');
let srcDir = 'path/to/file';
let destDir = 'pat/to/destination/directory';
fse.moveSync(srcDir, destDir, function (err) {
// To move a file permanently from a directory
if (err) {
console.error(err);
} else {
console.log("success!");
}
});
Or
fse.copySync(srcDir, destDir, function (err) {
// To copy a file from a directory
if (err) {
console.error(err);
} else {
console.log("success!");
}
});
One thing that I found quite helpful to use to print all images :
_, axs = plt.subplots(n_row, n_col, figsize=(12, 12))
axs = axs.flatten()
for img, ax in zip(imgs, axs):
ax.imshow(img)
plt.show()
Here I'm replacing an old value to a new value:
string actual = "Hello World";
string Result = actual.Replace("World", "Stack Overflow");
----------------------
Output : "Hello Stack Overflow"
If you're not joining two dictionaries, but adding new key-value pairs to a dictionary, then using the subscript notation seems like the best way.
import timeit
timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary.update({"aaa": 123123, "asd": 233})')
>> 0.49582505226135254
timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary["aaa"] = 123123; dictionary["asd"] = 233;')
>> 0.20782899856567383
However, if you'd like to add, for example, thousands of new key-value pairs, you should consider using the update()
method.
Swift 2.2
func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
if self.window?.rootViewController?.presentedViewController is SignatureLandscapeViewController {
let secondController = self.window!.rootViewController!.presentedViewController as! SignatureLandscapeViewController
if secondController.isPresented {
return UIInterfaceOrientationMask.LandscapeLeft;
} else {
return UIInterfaceOrientationMask.Portrait;
}
} else {
return UIInterfaceOrientationMask.Portrait;
}
}
You have 2 options, as described bellow:
Distribution package like Glaslos suggested:
# sudo apt-get install python-mysqldb
In this case you can't use virtualenv no-site-packages (default option) but must use:
# virtualenv --system-site-packages myenv
Use clean virtualenv and build your own python-mysql package.
First create virtualenv:
# virtualenv myvirtualenv
# source myvirtualenv/bin/activate
Then install build dependencies:
# sudo apt-get build-dep python-mysqldb
Now you can install python-mysql
# pip install mysql-python
NOTE Ubuntu package is python-mysql*db* , python pypi package is python-mysql (without db)
Using the usual grouper recipe, you could do:
Python 2:
d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))
Python 3:
d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))
better way is to reuse ANDROID_HOME variable in path variable. if your ANDROID_HOME variable changes you just have to make change at one place.
export ANDROID_HOME=/home/arshid/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
A bit simpler one-liner:
import os
from itertools import product, chain
chain.from_iterable([[os.sep.join(w) for w in product([i[0]], i[2])] for i in os.walk(dir)])
Source from: http://getbootstrap.com/getting-started/#disable-responsive
<meta>
mentioned in the CSS docswidth
on the .container
for each grid tier with a single width, for example width: 970px !important;
Be sure that this comes after the default Bootstrap CSS. You can optionally avoid the !important
with media queries or some selector-fu..col-xs-*
classes in addition to, or in place of, the medium/large ones. Don't worry, the extra-small device grid scales to all resolutions.A service creation example of using backslashes with many double quotes.
C:\Windows\system32>sc.exe create teagent binpath= "\"C:\Program Files\Tripwire\TE\Agent\bin\wrapper.exe\" -s \"C:\Program Files\Tripwire\TE\Agent\bin\agent.conf\"" DisplayName= "Tripwire Enterprise Agent"
[SC] CreateService SUCCESS
You can have it this way:
It is important to mind the commas after each struct item or set of items.
earnings := []LineItemsType{
LineItemsType{
TypeName: "Earnings",
Totals: 0.0,
HasTotal: true,
items: []LineItems{
LineItems{
name: "Basic Pay",
amount: 100.0,
},
LineItems{
name: "Commuter Allowance",
amount: 100.0,
},
},
},
LineItemsType{
TypeName: "Earnings",
Totals: 0.0,
HasTotal: true,
items: []LineItems{
LineItems{
name: "Basic Pay",
amount: 100.0,
},
LineItems{
name: "Commuter Allowance",
amount: 100.0,
},
},
},
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting screen orientation locked so it will be acting as potrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
}
No, the dataType
option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify
and set the processData
option to false
.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON
object, and although jQuery has .parseJSON
, it has no stringifier included; you'll need another polyfill library.
I am using this simple script:
mysql_query("select $column from $table") or mysql_query("alter table $table add $column varchar (20)");
It works if you are already connected to the database.
Add to your gradle:
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
Convert ArrayList
to JsonArray
JsonArray jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList);
1. Without plugin
class IndiSampleState extends State<ProgHudPage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Demo'),
),
body: Center(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async {
showDialog(
context: context,
builder: (BuildContext context) {
return Center(child: CircularProgressIndicator(),);
});
await loginAction();
Navigator.pop(context);
},
),
));
}
Future<bool> loginAction() async {
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
2. With plugin
check this plugin progress_hud
add the dependency in the pubspec.yaml file
dev_dependencies:
progress_hud:
import the package
import 'package:progress_hud/progress_hud.dart';
Sample code is given below to show and hide the indicator
class ProgHudPage extends StatefulWidget {
@override
_ProgHudPageState createState() => _ProgHudPageState();
}
class _ProgHudPageState extends State<ProgHudPage> {
ProgressHUD _progressHUD;
@override
void initState() {
_progressHUD = new ProgressHUD(
backgroundColor: Colors.black12,
color: Colors.white,
containerColor: Colors.blue,
borderRadius: 5.0,
loading: false,
text: 'Loading...',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('ProgressHUD Demo'),
),
body: new Stack(
children: <Widget>[
_progressHUD,
new Positioned(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async{
_progressHUD.state.show();
await loginAction();
_progressHUD.state.dismiss();
},
),
bottom: 30.0,
right: 10.0)
],
));
}
Future<bool> loginAction()async{
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
(Java) Avoiding usage of Map, List data structures:
private String getUniqueStr(String someStr) {
StringBuilder uniqueStr = new StringBuilder();
if(someStr != null) {
for(int i=0; i <someStr.length(); i++) {
if(uniqueStr.indexOf(String.valueOf(someStr.charAt(i))) == -1) {
uniqueStr.append(someStr.charAt(i));
}
}
}
return uniqueStr.toString();
}
Afer looking at the source, for WP7 Hammock doesn't actually use Json.Net for JSON parsing. Instead it uses it's own parser which doesn't cope with custom types very well.
If using Json.Net directly it is possible to deserialize to a strongly typed collection inside a wrapper object.
var response = @"
{
""data"": [
{
""name"": ""A Jones"",
""id"": ""500015763""
},
{
""name"": ""B Smith"",
""id"": ""504986213""
},
{
""name"": ""C Brown"",
""id"": ""509034361""
}
]
}
";
var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass));
return des.data.Count.ToString();
and with:
public class MyClass
{
public List<User> data { get; set; }
}
public class User
{
public string name { get; set; }
public string id { get; set; }
}
Having to create the extra object with the data property is annoying but that's a consequence of the way the JSON formatted object is constructed.
Documentation: Serializing and Deserializing JSON
The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.
From man clock:
The clock() function returns an approximation of processor time used by the program.
So there is no indication you should treat it as milliseconds. Some standards require precise value of CLOCKS_PER_SEC
, so you could rely on it, but I don't think it is advisable.
Second thing is that, as @unwind stated, it is not float/double. Man times suggests that will be an int.
Also note that:
this function will return the same value approximately every 72 minutes
And if you are unlucky you might hit the moment it is just about to start counting from zero, thus getting negative or huge value (depending on whether you store the result as signed or unsigned value).
This:
printf("\n\n%6.3f", stop);
Will most probably print garbage as treating any int as float is really not defined behaviour (and I think this is where most of your problem comes). If you want to make sure you can always do:
printf("\n\n%6.3f", (double) stop);
Though I would rather go for printing it as long long int
at first:
printf("\n\n%lldf", (long long int) stop);
double TotalPrice=90.98989898898;
DecimalFormat format_2Places = new DecimalFormat("0.00");
TotalPrice = Double.valueOf(format_2Places.format(TotalPrice));
It is worth pointing out that if you use json_decode(file_get_contents("php://input"))
(as others have mentioned), this will fail if the string is not valid JSON.
This can be simply resolved by first checking if the JSON is valid. i.e.
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params))
$decoded_params = json_decode($json_params);
Edit: Note that removing strlen($json_params)
above may result in subtle errors, as json_last_error()
does not change when null
or a blank string is passed, as shown here:
http://ideone.com/va3u8U
Update for iOS9.2.1 and Xcode 7.2.1
If you get this error when building to a device in Xcode:
On your device, tap the app icon that would have just been added from your attempt at building the app and you should see this:
Next, on your device, go to Settings --> General --> Device Management, and you will see this page:
Select the profile you are using with Xcode, and you should see this page:
Click Trust "[email protected]" then click Trust on the next popup.
Go back to Xcode and re-run your project and it should build the app to your device.
CHAR
is a fixed-length data type that uses as much space as possible. So a:= a||'one ';
will require more space than is available. Your problem can be reduced to the following example:
declare
v_foo char(50);
begin
v_foo := 'A';
dbms_output.put_line('length of v_foo(A) = ' || length(v_foo));
-- next line will raise:
-- ORA-06502: PL/SQL: numeric or value error: character string buffer too small
v_foo := v_foo || 'B';
dbms_output.put_line('length of v_foo(AB) = ' || length(v_foo));
end;
/
Never use char
. For rationale check the following question (read also the links):
Tensorflow provides an op to automatically apply an exponential decay to a learning rate tensor: tf.train.exponential_decay
. For an example of it in use, see this line in the MNIST convolutional model example. Then use @mrry's suggestion above to supply this variable as the learning_rate parameter to your optimizer of choice.
The key excerpt to look at is:
# Optimizer: set up a variable that's incremented once per batch and
# controls the learning rate decay.
batch = tf.Variable(0)
learning_rate = tf.train.exponential_decay(
0.01, # Base learning rate.
batch * BATCH_SIZE, # Current index into the dataset.
train_size, # Decay step.
0.95, # Decay rate.
staircase=True)
# Use simple momentum for the optimization.
optimizer = tf.train.MomentumOptimizer(learning_rate,
0.9).minimize(loss,
global_step=batch)
Note the global_step=batch
parameter to minimize. That tells the optimizer to helpfully increment the 'batch' parameter for you every time it trains.
As of latest Chrome/FF and on IE11 there's no need for -ms/-moz/-webkit prefix. Here's a shorter code (based on previous answers):
div {
margin: 20px;
width: 100px;
height: 100px;
background: #f00;
/* The animation part: */
animation-name: spin;
animation-duration: 4000ms;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@keyframes spin {
from {transform:rotate(0deg);}
to {transform:rotate(360deg);}
}
Live Demo: http://jsfiddle.net/9Ryvs/3057/
There are a number of different solutions for finding running median from streamed data, I will briefly talk about them at the very end of the answer.
The question is about the details of the a specific solution (max heap/min heap solution), and how heap based solution works is explained below:
For the first two elements add smaller one to the maxHeap on the left, and bigger one to the minHeap on the right. Then process stream data one by one,
Step 1: Add next item to one of the heaps
if next item is smaller than maxHeap root add it to maxHeap,
else add it to minHeap
Step 2: Balance the heaps (after this step heaps will be either balanced or
one of them will contain 1 more item)
if number of elements in one of the heaps is greater than the other by
more than 1, remove the root element from the one containing more elements and
add to the other one
Then at any given time you can calculate median like this:
If the heaps contain equal amount of elements;
median = (root of maxHeap + root of minHeap)/2
Else
median = root of the heap with more elements
Now I will talk about the problem in general as promised in the beginning of the answer. Finding running median from a stream of data is a tough problem, and finding an exact solution with memory constraints efficiently is probably impossible for the general case. On the other hand, if the data has some characteristics we can exploit, we can develop efficient specialized solutions. For example, if we know that the data is an integral type, then we can use counting sort, which can give you a constant memory constant time algorithm. Heap based solution is a more general solution because it can be used for other data types (doubles) as well. And finally, if the exact median is not required and an approximation is enough, you can just try to estimate a probability density function for the data and estimate median using that.
Do a python -VV
in the command line. It should return the version.
After Xcode 6.1 Beta the code below works, slight edit on Tom S code that stopped working with the 6.1 beta (worked with previous beta):
if UIApplication.sharedApplication().respondsToSelector("registerUserNotificationSettings:") {
// It's iOS 8
var types = UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert
var settings = UIUserNotificationSettings(forTypes: types, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
} else {
// It's older
var types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert
UIApplication.sharedApplication().registerForRemoteNotificationTypes(types)
}
Many of the other solutions offered this thread are not doing this correctly.
\r\n\r\n
is not reliable when CURLOPT_FOLLOWLOCATION
is on or when the server responds with a 100 code.\n
for new lines.CURLINFO_HEADER_SIZE
is also not always reliable, especially when proxies are used or in some of the same redirection scenarios.The most correct method is using CURLOPT_HEADERFUNCTION
.
Here is a very clean method of performing this using PHP closures. It also converts all headers to lowercase for consistent handling across servers and HTTP versions.
This version will retain duplicated headers
This complies with RFC822 and RFC2616, please do not suggest edits to make use of the mb_
string functions, it is incorrect!
$ch = curl_init();
$headers = [];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// this function is called by curl for each header received
curl_setopt($ch, CURLOPT_HEADERFUNCTION,
function($curl, $header) use (&$headers)
{
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) // ignore invalid headers
return $len;
$headers[strtolower(trim($header[0]))][] = trim($header[1]);
return $len;
}
);
$data = curl_exec($ch);
print_r($headers);
for me this is working ok tested in chrome v72
function down_file(url,name){
var a = $("<a>")
.attr("href", url)
.attr("download", name)
.appendTo("body");
a[0].click();
a.remove();
}
down_file('https://www.useotools.com/uploads/nulogo[1].png','logo.png')
Use the properties-maven-plugin to write specific pom properties
to a file at compile time, and then read that file at run time.
In your pom.xml:
<properties>
<name>${project.name}</name>
<version>${project.version}</version>
<foo>bar</foo>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>write-project-properties</goal>
</goals>
<configuration>
<outputFile>${project.build.outputDirectory}/my.properties</outputFile>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
And then in .java:
java.io.InputStream is = this.getClass().getResourceAsStream("my.properties");
java.util.Properties p = new Properties();
p.load(is);
String name = p.getProperty("name");
String version = p.getProperty("version");
String foo = p.getProperty("foo");
patrick dw's answer is right on.
For kicks and giggles I thought I would post a simple way to return an array of all the IDs.
var arrayOfIds = $.map($(".myClassName"), function(n, i){
return n.id;
});
alert(arrayOfIds);
Doesn't that really depends on the complexity of the system, and the in-house conventions?
At the moment I am working on a neural network simulator that is incredibly complex, and the accepted style that I am expected to use is:
Class definitions in classname.h
Class code in classnameCode.h
executable code in classname.cpp
This splits up the user-built simulations from the developer-built base classes, and works best in the situation.
However, I'd be surprised to see people do this in, say, a graphics application, or any other application that's purpose is not to provide users with a code base.
If you want to make transformation your app setting from web config file to web.Release.config,you have to do the following steps. Let your web.config app setting file is this-
<appSettings>
<add key ="K1" value="Debendra Dash"/>
</appSettings>
Now here is the web.Release.config for the transformation.
<appSettings>
<add key="K1" value="value dynamicly from Realease"
xdt:Transform="SetAttributes"
xdt:Locator="Match(key)"
/>
</appSettings>
This will transform the value of K1 to the new value in realese Mode.
For non-grouped elements, name and id should be same. In this case you gave name as 'sp' and id as 'sp_100'. Don't do that, do it like this:
HTML:
<input type="hidden" id="msg" name="msg" value="" style="display:none"/>
<input type="checkbox" name="sp" value="100" id="sp">
Javascript:
var Msg="abc";
document.getElementById('msg').value = Msg;
document.getElementById('sp').checked = true;
For more details
please visit : http://www.impressivewebs.com/avoiding-problems-with-javascript-getelementbyid-method-in-internet-explorer-7/
You can first concatenate the strings in the list with the separator ';' using the function join
and then use the split
function in order create the list:
l = ['Facebook;Google+;MySpace', 'Apple;Android']
l1 = ";".join(l)).split(";")
print l1
outputs
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
Simply using an rounded corner image as the background of that view
And don't forget to have your custom image in drawable folder
android:background="@drawable/my_custom_image"
Try to use this CSS:
/* Apply this to your `table` element. */
#page {
border-collapse: collapse;
}
/* And this to your table's `td` elements. */
#page td {
padding: 0;
margin: 0;
}
I thought it has been around a little longer, but according to this,
MySQL 5.7.4 introduces the ability to set server side execution time limits, specified in milliseconds, for top level read-only SELECT statements.
SELECT
/*+ MAX_EXECUTION_TIME(1000) */ --in milliseconds
*
FROM table;
Note that this only works for read-only SELECT statements.
Update: This variable was added in MySQL 5.7.4 and renamed to max_execution_time
in MySQL 5.7.8. (source)
Required arguments (the ones without defaults), must be at the start to allow client code to only supply two. If the optional arguments were at the start, it would be confusing:
fun1("who is who", 3, "jack")
What would that do in your first example? In the last, x is "who is who", y is 3 and a = "jack".
As Pablo said, you need to use find
instead of grep
, but there's no need to pipe find
to grep
. find
has that functionality built in:
find . -regex 'f[[:alnum:]]\.frm'
find
is a very powerful program for searching for files by name and supports searching by file type, depth limiting, combining different search terms with boolean operations, and executing arbitrary commands on found files. See the find man page for more information.
It's now called rounded-circle
as explained here in the BS4 docs
<img src="img/gallery2.JPG" class="rounded-circle">
As an example how this could be done with a readable/maintainable regex.
For a longer regex you should always use RegexOptions.IgnorePatternWhitespace
to allow whitespace and comments in the expression for better readability.
String[] passwords = { "foobar", "Foobar", "Foobar1", "Fooobar12" };
foreach (String s in passwords) {
Match password = Regex.Match(s, @"
^ # Match the start of the string
(?=.*\p{Lu}) # Positive lookahead assertion, is true when there is an uppercase letter
(?=.*\P{L}) # Positive lookahead assertion, is true when there is a non-letter
\S{8,} # At least 8 non whitespace characters
$ # Match the end of the string
", RegexOptions.IgnorePatternWhitespace);
if (password.Success) {
Console.WriteLine(s + ": valid");
}
else {
Console.WriteLine(s + ": invalid");
}
}
Console.ReadLine();
Run from the project folder
msbuild /p:DeployOnBuild=true /p:PublishProfile="release-file.pubxml" /p:AspnetMergePath="C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools" /p:Configuration=Release
This takes care of web.config Transform and AspnetMergePath
I have been running into the same error when I add the following maven dependency in my project:
<artifactId>aws-encryption-sdk-java</artifactId>
The error came up only when I ran the shade jar file produced by maven-shade-plugin. I was able to overcome the error by using the jar produced by maven-assembly-plugin.
It depends
It depends on a lot of things - your goals, your experience, your timeframe, etc.
The majority of game programming isn't language specific. 3D math is 3D math in C# as much as it is in C++. While the APIs may be different, and different 'bookkeeping' may be required, the fundamental logic and math will remain the same.
And it's true that most AAA game engines are C++ with a scripting language on top of them. That is undeniable. However, most AAA engines also have a bunch of in-house tools supporting them, and those may be in anything - Java, C#, C++, etc.
If you want to write a game, and are an experienced developer then C++ and C# have a lot going for them. C# has less housekeeping, while C++ has more available libraries and tools. For anything highly complex, however, you'd be best off trying to use an existing engine as a starting point.
If you want to write a game, and are a new developer then don't write an engine. Use an existing engine, and mod it or use its facilities to write your game. Trust me.
If you want to learn how to write an engine, and are an experienced developer you should probably think about C++. C# is possible as well, but the amount of code and ease of integration of C++ probably puts it over the top.
If you want to learn how to write an engine, and are a new developer I'd probably recommend C#/XNA. You'll get to the game 'stuff' faster, with less headache of learning the ins and outs of C++.
If you want a job in the industry then you need to figure out what kind of job you want. A high-level language can help get a foot in the door dealing with tools and/or web development, which can lead to opportunities on actual game work. Even knowledge of scripting languages can help if you want to go for more of the game designer/scripter position. Chances are that you will not get a job working on core engine stuff immediately, as the skills required to do so are pretty high. Strong C++ development skills are always helpful, especially in real-time or networked scenarios.
AAA game engine development involves some serious brain-twisting code.
If you want to start a professional development house then you probably aren't reading this, but already know that C++ is probably the only viable answer.
If you want to do casual game development then you should probably consider Flash or a similar technology.
The Exception it self says it all java.lang.ClassNotFoundException: org.json.JSONObject
You have not added the necessary jar file which will be having org.json.JSONObject
class to your classpath
.
You can Download it From Here
Add
"rnpm": {
"assets": [
"./assets/fonts/"
]
}
in package.json
then run react-native link
1. In my opinion, the most convenient way is to search for one
occurrence first, and then invoke the following :substitute
command:
:%s///gc
Since the pattern is empty, this :substitute
command will look for
the occurrences of the last-used search pattern, and will then replace
them with the empty string, each time asking for user confirmation,
realizing exactly the desired behavior.
2. If it is a common pattern in one’s editing habits, one can further define a couple of text-object selection mappings to operate specifically on the match of the last search pattern under the cursor. The following two mappings can be used in both Visual and Operator-pending modes to select the text of the preceding match of the last search pattern.
vnoremap <silent> i/ :<c-u>call SelectMatch()<cr>
onoremap <silent> i/ :call SelectMatch()<cr>
function! SelectMatch()
if search(@/, 'bcW')
norm! v
call search(@/, 'ceW')
else
norm! gv
endif
endfunction
Using these mappings one can delete the match under the cursor with
di/
, or apply any other operator or visually select it with vi/
.
Javascript now has a specific built in object called Map, you can call as follows :
var myMap = new Map()
You can update it with .set :
myMap.set("key0","value")
This has the advantage of methods you can use to handle look ups, like the boolean .has
myMap.has("key1"); // evaluates to false
You can use this before calling .get on your Map object to handle looking up non-existent keys
cd /usr/local
git status
git status
til it's cleanbrew update
rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.
There is a performance comparison with YAJL and JsonCPP.
Update:
I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.
What you have above is an object, not an array.
To make an array use [
& ]
to surround your objects.
userTestStatus = [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
Aside from that TypeScript is a superset of JavaScript so whatever is valid JavaScript will be valid TypeScript so no other changes are needed.
Feedback clarification from OP... in need of a definition for the model posted
You can use the types defined here to represent your object model:
type MyType = {
id: number;
name: string;
}
type MyGroupType = {
[key:string]: MyType;
}
var obj: MyGroupType = {
"0": { "id": 0, "name": "Available" },
"1": { "id": 1, "name": "Ready" },
"2": { "id": 2, "name": "Started" }
};
// or if you make it an array
var arr: MyType[] = [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
How about this?
Select DateName( Month, getDate() ) + ' ' + DateName( Year, getDate() )
If you have the option pre-existing in a fixed-with <select>
, and you don't want to change the width programmatically, you could be out of luck unless you get a little creative.
title
attribute to each option. This is non-standard HTML (if you care for this minor infraction here), but IE (and Firefox as well) will display the entire text in a mouse popup on mouse hover.If you are adding a long option later through JavaScript, look here: How to update HTML “select” box dynamically in IE
<style>_x000D_
.hideFullColumn tr > .hidecol_x000D_
{_x000D_
display:none;_x000D_
}_x000D_
</style>
_x000D_
use .hideFullColumn in table and .hidecol in th.You don't need to add class in td individually as it will be problem because index may not be in mind of each td.
I am not sure if you got this resolved. To follow up on "CommonsWare's" comment.
That is not a valid string representation of a Uri. A Uri has a scheme, and "/external/images/media/470939" does not have a scheme.
Change
Uri uri=Uri.parse("/external/images/media/470939");
to
Uri uri=Uri.parse("content://external/images/media/470939");
in my case
Uri uri = Uri.parse("content://media/external/images/media/6562");
Mock
vs Spy
Mock
is a bare double object. This object has the same methods signatures but realisation is empty and return default value - 0 and null
Spy
is a cloned double object. New object is cloned based on a real object but you have a possibility to mock it
class A {
String foo1() {
foo2();
return "RealString_1";
}
String foo2() {
return "RealString_2";
}
void foo3() { foo4(); }
void foo4() { }
}
@Test
public void testMockA() {
//given
A mockA = Mockito.mock(A.class);
Mockito.when(mockA.foo1()).thenReturn("MockedString");
//when
String result1 = mockA.foo1();
String result2 = mockA.foo2();
//then
assertEquals("MockedString", result1);
assertEquals(null, result2);
//Case 2
//when
mockA.foo3();
//then
verify(mockA).foo3();
verify(mockA, never()).foo4();
}
@Test
public void testSpyA() {
//given
A spyA = Mockito.spy(new A());
Mockito.when(spyA.foo1()).thenReturn("MockedString");
//when
String result1 = spyA.foo1();
String result2 = spyA.foo2();
//then
assertEquals("MockedString", result1);
assertEquals("RealString_2", result2);
//Case 2
//when
spyA.foo3();
//then
verify(spyA).foo3();
verify(spyA).foo4();
}
If you are using kotlin,consider these library. It's build for kotlin language.
AndroidHttpServer is a simple demo using ServerSocket to handle http request
https://github.com/weeChanc/AndroidHttpServer
https://github.com/ktorio/ktor
AndroidHttpServer is very small , but the feature is less as well.
Ktor is a very nice library,and the usage is simple too
if you insist on using Bootstrap, use d-inline-block
like below
<div class="row d-inline-block">
<form class="form-inline">
<div class="form-group d-inline-block">
<input type="email" aria-expanded="false" class="form-control mr-2"
placeholder="Enter your email">
<button type="button" class="btn btn-danger">submit</button>
</div>
</form>
</div>
Same issue on macOS and got it fixed by running the same installer again.
Whereas I COULD NOT get it fixed by
Note: Make sure to select 'XAMPP Core Files' component while running the installer as by default it is not selected.
Though re-running the installer is not smart option when one has to do it every now and then. My installer is xampp-osx-7.0.13-1-installer.dmg
Update: I've got my MAMP working with this simple solution here. So, same should work for XAMPP.
Try this
plt.imshow(im.reshape(im.shape[0], im.shape[1]), cmap=plt.cm.Greys)
It would help in some cases.
Why don't you just save/serve the CSS file as UTF-8?
nav a:hover:after {
content: "?";
}
If that's not good enough, and you want to keep it all-ASCII:
nav a:hover:after {
content: "\2193";
}
The general format for a Unicode character inside a string is \000000
to \FFFFFF
– a backslash followed by six hexadecimal digits. You can leave out leading 0
digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.
Relevant part of the CSS2 spec:
Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:
- with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
- by providing exactly 6 hexadecimal digits: "\000026B" ("&B")
In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.
If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).
- Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
The identifier "te\st" is exactly the same identifier as "test".
Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).
sleep infinity
does exactly what it suggests and works without cat abuse.
Section 3 of RFC4122 provides the formal definition of UUID string representations. It's 36 characters (32 hex digits + 4 dashes).
Sounds like you need to figure out where the invalid 60-char IDs are coming from and decide 1) if you want to accept them, and 2) what the max length of those IDs might be based on whatever API is used to generate them.
From: http://www.cplusplus.com/reference/map/map/
"Internally, the elements in a map are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).
map containers are generally slower than unordered_map containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order."
I have solved this problem by using the following code segment:
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
boolean max = jTextField1.getText().length() > 4;
if ( max ){
evt.consume();
}
}
switch (String.valueOf(value)){
case "null":
default:
}
You can add the directories for your build process like:
...
<resources>
<resource>
<directory>src/bootstrap</directory>
</resource>
</resources>
...
The src/main/java is the default path which is not needed to be mentioned in the pom.xml
I had to add [AllowAnonymous] to the ActionResult functions in my login page because the user was not authenticated yet.
https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.md5?view=netframework-4.7.2
using System;
using System.Security.Cryptography;
using System.Text;
static string GetMd5Hash(string input)
{
using (MD5 md5Hash = MD5.Create())
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
}
// Verify a hash against a string.
static bool VerifyMd5Hash(string input, string hash)
{
// Hash the input.
string hashOfInput = GetMd5Hash(input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
return 0 == comparer.Compare(hashOfInput, hash);
}
I really think it's a more robust way to use getLocationOnScreen
than getGlobalVisibleRect
. Because I meet a problem. There is a Listview which contain some Edittext and and set ajustpan
in the activity. I find getGlobalVisibleRect
return a value that looks like including the scrollY in it, but the event.getRawY is always by the screen. The below code works well.
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if ( v instanceof EditText) {
if (!isPointInsideView(event.getRawX(), event.getRawY(), v)) {
Log.i(TAG, "!isPointInsideView");
Log.i(TAG, "dispatchTouchEvent clearFocus");
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent( event );
}
/**
* Determines if given points are inside view
* @param x - x coordinate of point
* @param y - y coordinate of point
* @param view - view object to compare
* @return true if the points are within view bounds, false otherwise
*/
private boolean isPointInsideView(float x, float y, View view) {
int location[] = new int[2];
view.getLocationOnScreen(location);
int viewX = location[0];
int viewY = location[1];
Log.i(TAG, "location x: " + location[0] + ", y: " + location[1]);
Log.i(TAG, "location xWidth: " + (viewX + view.getWidth()) + ", yHeight: " + (viewY + view.getHeight()));
// point is inside view bounds
return ((x > viewX && x < (viewX + view.getWidth())) &&
(y > viewY && y < (viewY + view.getHeight())));
}
Add rows:
<html>_x000D_
<script>_x000D_
function addRow() {_x000D_
var table = document.getElementById('myTable');_x000D_
//var row = document.getElementById("myTable");_x000D_
var x = table.insertRow(0);_x000D_
var e = table.rows.length-1;_x000D_
var l = table.rows[e].cells.length;_x000D_
//x.innerHTML = " ";_x000D_
_x000D_
for (var c=0, m=l; c < m; c++) {_x000D_
table.rows[0].insertCell(c);_x000D_
table.rows[0].cells[c].innerHTML = " ";_x000D_
}_x000D_
}_x000D_
_x000D_
function addColumn() {_x000D_
var table = document.getElementById('myTable');_x000D_
for (var r = 0, n = table.rows.length; r < n; r++) {_x000D_
table.rows[r].insertCell(0);_x000D_
table.rows[r].cells[0].innerHTML = " ";_x000D_
}_x000D_
}_x000D_
_x000D_
function deleteRow() {_x000D_
document.getElementById("myTable").deleteRow(0);_x000D_
}_x000D_
_x000D_
function deleteColumn() {_x000D_
// var row = document.getElementById("myRow");_x000D_
var table = document.getElementById('myTable');_x000D_
for (var r = 0, n = table.rows.length; r < n; r++) {_x000D_
table.rows[r].deleteCell(0); // var table handle_x000D_
}_x000D_
}_x000D_
</script>_x000D_
_x000D_
<body>_x000D_
<input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>_x000D_
<input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>_x000D_
<input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>_x000D_
<input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>_x000D_
_x000D_
<table id='myTable' border=1 cellpadding=0 cellspacing=0>_x000D_
<tr id='myRow'>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
And cells.
OK, so I don't really know what the problem was, but I simply fixed it by navigating to here http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html and installing 8u74 instead of 8u73 which is what I was prompted to do when I would go to "download latest version" in Java. So changing the versions is what did it in the end. Eclipse launched fine, now. Thanks for everyone's help!
edit: Apr 2018- Now is 8u161 and 8u162 (Just need one, I used 8u162 and it worked.)
Always call dispose. It is not worth the risk. Big managed enterprise applications should be treated with respect. No assumptions can be made or else it will come back to bite you.
Don't listen to leppie.
A lot of objects don't actually implement IDisposable, so you don't have to worry about them. If they genuinely go out of scope they will be freed automatically. Also I have never come across the situation where I have had to set something to null.
One thing that can happen is that a lot of objects can be held open. This can greatly increase the memory usage of your application. Sometimes it is hard to work out whether this is actually a memory leak, or whether your application is just doing a lot of stuff.
Memory profile tools can help with things like that, but it can be tricky.
In addition always unsubscribe from events that are not needed. Also be careful with WPF binding and controls. Not a usual situation, but I came across a situation where I had a WPF control that was being bound to an underlying object. The underlying object was large and took up a large amount of memory. The WPF control was being replaced with a new instance, and the old one was still hanging around for some reason. This caused a large memory leak.
In hindsite the code was poorly written, but the point is that you want to make sure that things that are not used go out of scope. That one took a long time to find with a memory profiler as it is hard to know what stuff in memory is valid, and what shouldn't be there.
Here's an example from AndroidManifest.xml. You need to specify the MAIN and LAUNCHER in the intent filter for the activity you want to start on launch
<application android:label="@string/app_name" android:icon="@drawable/icon">
<activity android:name="ExampleActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
WAI-ARIA is a spec defining support for accessible web apps. It defines bunch of markup extensions (mostly as attributes on HTML5 elements), which can be used by the web app developer to provide additional information about the semantics of the various elements to assistive technologies like screen readers. Of course, for ARIA to work, the HTTP user agent that interprets the markup needs to support ARIA, but the spec is created in such a way, as to allow down-level user agents to ignore the ARIA-specific markup safely without affecting the web app's functionality.
Here's an example from the ARIA spec:
<ul role="menubar">
<!-- Rule 2A: "File" label via aria-labelledby -->
<li role="menuitem" aria-haspopup="true" aria-labelledby="fileLabel"><span id="fileLabel">File</span>
<ul role="menu">
<!-- Rule 2C: "New" label via Namefrom:contents -->
<li role="menuitem" aria-haspopup="false">New</li>
<li role="menuitem" aria-haspopup="false">Open…</li>
...
</ul>
</li>
...
</ul>
Note the role
attribute on the outer <ul>
element. This attribute does not affect in any way how the markup is rendered on the screen by the browser; however, browsers that support ARIA will add OS-specific accessibility information to the rendered UI element, so that the screen reader can interpret it as a menu and read it aloud with enough context for the end-user to understand (for example, an explicit "menu" audio hint) and is able to interact with it (for example, voice navigation).
public class SecondHighInIntArray {
public static void main(String[] args) {
int[] intArray=new int[]{2,2,1};
//{2,2,1,12,3,7,9,-1,-5,7};
int secHigh=findSecHigh(intArray);
System.out.println(secHigh);
}
private static int findSecHigh(int[] intArray) {
int highest=Integer.MIN_VALUE;
int sechighest=Integer.MIN_VALUE;
int len=intArray.length;
for(int i=0;i<len;i++)
{
if(intArray[i]>highest)
{
sechighest=highest;
highest=intArray[i];
continue;
}
if(intArray[i]<highest && intArray[i]>sechighest)
{
sechighest=intArray[i];
continue;
}
}
return sechighest;
}
}
I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child
parameters will only make it more complicated. As for the background color I'd just set that to a variable.
Here goes what I came up with before I realized trying to be too clever might be a bad thing.
#romtest {
$bg: #e5e5e5;
.detailed {
th {
&:nth-child(-2n+6) {
background-color: $bg;
}
}
td {
&:nth-child(3n), &:nth-child(2), &:nth-child(7) {
background-color: $bg;
}
&.last {
&:nth-child(-2n+4){
background-color: $bg;
}
}
}
}
}
and here is a quick demo: http://codepen.io/anon/pen/BEImD
----EDIT----
Here's another approach to avoid retyping background-color
:
#romtest {
%highlight {
background-color: #e5e5e5;
}
.detailed {
th {
&:nth-child(-2n+6) {
@extend %highlight;
}
}
td {
&:nth-child(3n), &:nth-child(2), &:nth-child(7) {
@extend %highlight;
}
&.last {
&:nth-child(-2n+4){
@extend %highlight;
}
}
}
}
}
Add a border
to the regular item, the same color
as the background
, so that it cannot be seen. That way the item has a border: 1px
whether it is being hovered or not.
Try This, It's easy way to find java installed path in Mac OS X,
GoTO
1 ) /Library i.e Macintosh HD/Library
2) Click on Library in that we find Java folder.
3) So final path is
/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home
Hope so this is help for someone .
In bootstrap, simply use mx-auto
class along with navbar-brand
.
COPY README.md package.json gulpfile.js __BUILD_NUMBER ./
or
COPY ["__BUILD_NUMBER", "README.md", "gulpfile", "another_file", "./"]
You can also use wildcard characters in the sourcefile specification. See the docs for a little more detail.
Directories are special! If you write
COPY dir1 dir2 ./
that actually works like
COPY dir1/* dir2/* ./
If you want to copy multiple directories (not their contents) under a destination directory in a single command, you'll need to set up the build context so that your source directories are under a common parent and then COPY
that parent.
Agree with Markus' suggestion to roll your own exception, but the text of the exception should clarify that the problem is in the argument list, not the individual argument values. I'd propose:
class BadCallError(ValueError):
pass
Used when keyword arguments are missing that were required for the specific call, or argument values are individually valid but inconsistent with each other. ValueError
would still be right when a specific argument is right type but out of range.
Shouldn't this be a standard exception in Python?
In general, I'd like Python style to be a bit sharper in distinguishing bad inputs to a function (caller's fault) from bad results within the function (my fault). So there might also be a BadArgumentError to distinguish value errors in arguments from value errors in locals.
According to catalina.sh customizations should always go into your own setenv.sh (or setenv.bat respectively) eg:
CATALINA_OPTS='-Xms512m -Xmx1024m'
My guess is that setenv.bat will also be called when starting a service.I might be wrong, though, since I'm not a windows user.
Firstly, JSON.stringify()
function converts a JavaScript value to a JavaScript Object Notation (JSON) string. JSON.parse()
function converts a JavaScript Object Notation (JSON) string into an object. For more information about these two functions, please refer to the following links.
https://msdn.microsoft.com/library/cc836459(v=vs.94).aspx https://msdn.microsoft.com/library/cc836466(v=vs.94).aspx
Secondly, the following sample will be helpful for you to understand these two functions.
<form id="form1" runat="server">
<div>
<div id="result"></div>
</div>
</form>
<script>
$(function () {
//define a json object
var employee = { "name": "John Johnson", "street": "Oslo West 16", "phone": "555 1234567" };
//use JSON.stringify to convert it to json string
var jsonstring = JSON.stringify(employee);
$("#result").append('<p>json string: ' + jsonstring + '</p>');
//convert json string to json object using JSON.parse function
var jsonobject = JSON.parse(jsonstring);
var info = '<ul><li>Name:' + jsonobject.name + '</li><li>Street:' + jsonobject.street + '</li><li>Phone:' + jsonobject.phone + '</li></ul>';
$("#result").append('<p>json object:</p>');
$("#result").append(info);
});
</script>
This should work
<a href="javascript:window.open('document.aspx','mywindowtitle','width=500,height=150')">open window</a>
try below code
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.Transparent"
>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
style.xml
<style name="AppTheme.Transparent" parent="ThemeOverlay.AppCompat.Light">
<item name="colorPrimary">@android:color/transparent</item>
<item name="colorControlActivated">@color/colorWhite</item>
<item name="colorControlNormal">@color/colorWhite</item>
</style>
issue resolved here :
"Windows/Preferences": Java > Installed JREs:
then set/update JRE HOME : C:\Program Files\Java\jdk1.8.0_221\jre
should try this.
For anyone using XCode 7, it's very easy to design for a specific device size (instead of the default square-ish canvas).
In Interface Builder, select your ViewController or Scene from the left menu. Then under Show the Attributes Inspector
, go to the Simulated Metrics
, and pick the desired Size
from the dropdown menu.
public class TestModels
{
public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();
public TestModels()
{
sp.Add(0, new {name="Test One", age=5});
sp.Add(1, new {name="Test Two", age=7});
}
}
Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.
$("legend").each(function() {
var SoftwareItem = $(this).text();
itemCost = GetItemCost(SoftwareItem);
$("input:checked").each(function() {
var Component = $(this).next("label").text();
itemCost += GetItemCost(Component);
});
$(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
});
ssh -t foobar@localhost yourscript.pl
$("#linkid").trigger("click");
startup chrome with --disable-web-security
On Windows:
chrome.exe --disable-web-security
On Mac:
open /Applications/Google\ Chrome.app/ --args --disable-web-security
This will allow for cross-domain requests.
I'm not aware of if this also works for local files, but let us know !
And mention, this does exactly what you expect, it disables the web security, so be careful with it.
It depends on what exactly you want to achieve.
If you just want to have it on the right, then I'd recommend against using position absolute, because it opens a whole can of worms down the line.
The HTML can also be unchanged:
HTML
<div>
<h1> Ok </h1>
<button type='button'>Button</button>
</div>
the CSS then should be something along the lines of:
CSS
div {
background: purple;
overflow: hidden;
}
div h1 {
text-align: center;
display: inline-block;
width: 100%;
margin-right: -50%;
}
div button {
float: right;
}
You can see it in action here: http://jsfiddle.net/azhH5/
If you can change the HTML, then it gets a bit simpler:
HTML
<div>
<button type='button'>Button</button>
<h1> Ok </h1>
</div>
CSS
div {
background: purple;
overflow: hidden;
}
div h1 {
text-align: center;
}
div button {
float: right;
margin-left: -50%;
}
You can see it in action: http://jsfiddle.net/8WA3k/1/
If you want to have the button on the same line as the Text, you can achieve it by doing this:
HTML
<div>
<button type='button'>Button</button>
<h1> Ok </h1>
</div>
CSS
div {
background: purple;
overflow: hidden;
}
div h1 {
text-align: center;
}
div button {
float: right;
margin-left: -50%;
margin-top: 2em;
}
You an see that in action here: http://jsfiddle.net/EtqVh/1/
Cleary in the lest example you'd have to adjust the margin-top for the specified font-size of the <h1>
EDIT:
As you can see, it doesn't get popped out of the <div>
, it's till inside. this is achieved by two things: the negative margin on the <button>
, and the overflow: hidden;
on the <div>
EDIT 2:
I just saw that you also want it to be a bit away from the margin on the right. That's easily achievable with this method. Just add margin-right: 1em;
to the <button>
, like this:
div {
background: purple;
overflow: hidden;
}
div h1 {
text-align: center;
}
div button {
float: right;
margin-left: -50%;
margin-top: 2em;
margin-right: 1em;
}
You can see it in action here: http://jsfiddle.net/QkvGb/
Simply put OAuth is a way for applications to gain credentials to your information without directly getting your user login information to some website. For example if you write an application on your own website and want it to use data from a user's facebook account, you can use OAuth to get a token via a callback url and then use that token to make calls to the facebook API to get their use data until the token expires. Websites rely on it because it allows programmers to access their data without the user having to directly disclose their information and spread their credentials around online but still provide a level of protection to the data. Will it become the de facto method of authorization? Perhaps, it's been gaining a lot of support recently from Twitter, Facebook, and the likes where other programmers want to build applications around user data.
There is clearly some confusion here as to what the preferred syntax for skipping a directory should be.
GNU Opinion
To ignore a directory and the files under it, use -prune
Reasoning
-prune
stops find
from descending into a directory. Just specifying -not -path
will still descend into the skipped directory, but -not -path
will be false whenever find
tests each file.
Issues with -prune
-prune
does what it's intended to, but are still some things you have to take care of when using it.
find
prints the pruned directory.
-prune
only works with -print
and no other actions.
-prune
works with any action except -delete
. Why doesn't it work with delete? For -delete
to work, find needs to traverse the directory in DFS order, since -delete
will first delete the leaves, then the parents of the leaves, etc... But for specifying -prune
to make sense, find
needs to hit a directory and stop descending it, which clearly makes no sense with -depth
or -delete
on.Performance
I set up a simple test of the three top upvoted answers on this question (replaced -print
with -exec bash -c 'echo $0' {} \;
to show another action example). Results are below
----------------------------------------------
# of files/dirs in level one directories
.performance_test/prune_me 702702
.performance_test/other 2
----------------------------------------------
> find ".performance_test" -path ".performance_test/prune_me" -prune -o -exec bash -c 'echo "$0"' {} \;
.performance_test
.performance_test/other
.performance_test/other/foo
[# of files] 3 [Runtime(ns)] 23513814
> find ".performance_test" -not \( -path ".performance_test/prune_me" -prune \) -exec bash -c 'echo "$0"' {} \;
.performance_test
.performance_test/other
.performance_test/other/foo
[# of files] 3 [Runtime(ns)] 10670141
> find ".performance_test" -not -path ".performance_test/prune_me*" -exec bash -c 'echo "$0"' {} \;
.performance_test
.performance_test/other
.performance_test/other/foo
[# of files] 3 [Runtime(ns)] 864843145
Conclusion
Both f10bit's syntax and Daniel C. Sobral's syntax took 10-25ms to run on average. GetFree's syntax, which doesn't use -prune
, took 865ms. So, yes this is a rather extreme example, but if you care about run time and are doing anything remotely intensive you should use -prune
.
Note Daniel C. Sobral's syntax performed the better of the two -prune
syntaxes; but, I strongly suspect this is the result of some caching as switching the order in which the two ran resulted in the opposite result, while the non-prune version was always slowest.
Test Script
#!/bin/bash
dir='.performance_test'
setup() {
mkdir "$dir" || exit 1
mkdir -p "$dir/prune_me/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/w/x/y/z" \
"$dir/other"
find "$dir/prune_me" -depth -type d -exec mkdir '{}'/{A..Z} \;
find "$dir/prune_me" -type d -exec touch '{}'/{1..1000} \;
touch "$dir/other/foo"
}
cleanup() {
rm -rf "$dir"
}
stats() {
for file in "$dir"/*; do
if [[ -d "$file" ]]; then
count=$(find "$file" | wc -l)
printf "%-30s %-10s\n" "$file" "$count"
fi
done
}
name1() {
find "$dir" -path "$dir/prune_me" -prune -o -exec bash -c 'echo "$0"' {} \;
}
name2() {
find "$dir" -not \( -path "$dir/prune_me" -prune \) -exec bash -c 'echo "$0"' {} \;
}
name3() {
find "$dir" -not -path "$dir/prune_me*" -exec bash -c 'echo "$0"' {} \;
}
printf "Setting up test files...\n\n"
setup
echo "----------------------------------------------"
echo "# of files/dirs in level one directories"
stats | sort -k 2 -n -r
echo "----------------------------------------------"
printf "\nRunning performance test...\n\n"
echo \> find \""$dir"\" -path \""$dir/prune_me"\" -prune -o -exec bash -c \'echo \"\$0\"\' {} \\\;
name1
s=$(date +%s%N)
name1_num=$(name1 | wc -l)
e=$(date +%s%N)
name1_perf=$((e-s))
printf " [# of files] $name1_num [Runtime(ns)] $name1_perf\n\n"
echo \> find \""$dir"\" -not \\\( -path \""$dir/prune_me"\" -prune \\\) -exec bash -c \'echo \"\$0\"\' {} \\\;
name2
s=$(date +%s%N)
name2_num=$(name2 | wc -l)
e=$(date +%s%N)
name2_perf=$((e-s))
printf " [# of files] $name2_num [Runtime(ns)] $name2_perf\n\n"
echo \> find \""$dir"\" -not -path \""$dir/prune_me*"\" -exec bash -c \'echo \"\$0\"\' {} \\\;
name3
s=$(date +%s%N)
name3_num=$(name3 | wc -l)
e=$(date +%s%N)
name3_perf=$((e-s))
printf " [# of files] $name3_num [Runtime(ns)] $name3_perf\n\n"
echo "Cleaning up test files..."
cleanup
There is a solution that requires no non-standard modules and is 100% transportable
import thread
def input_thread(a_list):
raw_input()
a_list.append(True)
def do_stuff():
a_list = []
thread.start_new_thread(input_thread, (a_list,))
while not a_list:
stuff()
In the DOM, a tr
element is (implicitly or explicitly) a child of tbody
, thead
, or tfoot
, not a child of table
(hence the 0 you got). So a general answer is:
var count = $('#gvPerformanceResult > * > tr').length;
This includes the rows of the table but excludes rows of any inner table.
$('.tooltip').animate({ opacity: 1, top: "-10px" }, 'slow');
However, this doesn't appear to work on display: none
elements (as fadeIn
does). So, you might need to put this beforehand:
$('.tooltip').css('display', 'block');
$('.tooltip').animate({ opacity: 0 }, 0);
just change them to password('yourpassword')
If you have already defined your view in layout(xml) file and only want to change the weight pro grammatically, then then creating new LayoutParams overwrites other params defined in you xml file.
So first you should use "getLayoutParams" and then setLayoutParams
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mButton.getLayoutParams();
params.weight = 4f;
mButton.setLayoutParams(params);
Either [0-9]
or \d
1 should suffice if you only need a single digit. Append +
if you need more.
1 The semantics are slightly different as \d
potentially matches any decimal digit in any script out there that uses decimal digits.
Regarding Jay Stevens answer: "The fonts available to use in an HTML file have to be present on the user's machine and accessible from the web browser, so unless you want to distribute the fonts to the user's machine via a separate external process, it can't be done." That's true.
But there is another way using javascript / canvas / flash - very good solution gives cufon: http://cufon.shoqolate.com/generate/ library that generates a very easy to use external fonts methods.
import pandas as pd
import numpy as np
x = np.array( [1,1,1,2,2,2,5,25,1,1] )
print(dict(pd.Series(x).value_counts()))
This gives you: {1: 5, 2: 3, 5: 1, 25: 1}
Unfortunately the switch option to mount a volume is only found in the run
command.
docker run --help
-v, --volume list Bind mount a volume (default [])
There is a way you can work around this though so you won't have to reinstall the applications you've already set up on your container.
docker container export -o ./myimage.docker mycontainer
docker import ./myimage.docker myimage
docker run -i -t -v /somedir --name mycontainer myimage /bin/bash
As you've noticed, the WHERE
clause doesn't allow you to use aggregates in it. That's what the HAVING
clause is for.
HAVING t1.field3=MAX(t1.field3)
No need to use git at all, just append "/zipball/master/" to URL (source).
This solution is the closest to "Download ZIP" button on github page. One advantage is lack of .git directory. The other one - it downloads single ZIP file instead of each file one by one, and this can make huge difference. It can be done from command line by wget: wget -O "$(basename $REPO_URL)".zip "$REPO_URL"/zipball/master/
. The only problem is, that some repositories might not have master branch at all. If this is the case, "master" in URL should be replaced by appropriate branch.
Once the ZIP is there, the final unzipped directory name may still be pretty weird and unexpected. To fix this, name can be extracted by this script, and mv
-ed to basename
of the URL. Final script.sh
could look something like (evals for dealing with spaces):
#Script for downloading from github. If no BRANCH_NAME is given, default is "master".
#usage: script.sh URL [BRANCH_NAME]
__repo_name__='basename "$1"'
__repo_name__="$(eval $__repo_name__)"
__branch__="${2:-master}"
#downloading
if [ ! -e ./"$__repo_name__"".zip" ] ; then
wget -O "$__repo_name__"".zip" "$1""/zipball/$__branch__/"
fi
#unpacking and renaming
if [ ! -e ./"$__repo_name__" ] ; then
unzip "$__repo_name__"".zip" &&
__dir_name__="$(unzip -qql $__repo_name__.zip | sed -r '1 {s/([ ]+[^ ]+){3}\s+//;q}')" &&
rm "$__repo_name__"".zip" &&
mv "$__dir_name__" "$__repo_name__"
fi
This approach shoud do the work for "just the files", and it is great for quick single-use access to small repositories.
However. If the source is rather big, and the only possibility to update is to download and rebuild all, then (to the best of my knowledge) there is no possibility to update .git
-less directory, so the full repo has to be downloaded again. Then the best solution is - as VonC has already explained - to stick with shallow copy git clone --depth 1 $REPO_URL
. But what next? To "check for updates" see link, and to update see great wiki-like answer.
Try this, It worked for me
SELECT * FROM (
SELECT
[Code],
[Name],
[CategoryCode],
[CreatedDate],
[ModifiedDate],
[CreatedBy],
[ModifiedBy],
[IsActive],
ROW_NUMBER() OVER(PARTITION BY [Code],[Name],[CategoryCode] ORDER BY ID DESC) rownumber
FROM MasterTable
) a
WHERE rownumber = 1
If you've already installed Android Studio --
Add the following lines to the end of ~/.bashrc
or ~/.zshrc
(if using Oh My ZSH):
export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
Restart Terminal and you're good to go.
You can use aspnet_compiler for this:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler -v /Virtual/Application/Path/Or/Path/In/IIS/Metabase -p C:\Path\To\Your\WebProject -f -errorstack C:\Where\To\Put\Compiled\Site
where "/Virtual/Application/Path/Or/Path/In/IIS/Metabase" is something like this: "/MyApp" or "/lm/w3svc2/1/root/"
Also there is a AspNetCompiler Task on MSDN, showing how to integrate aspnet_compiler with MSBuild:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="PrecompileWeb">
<AspNetCompiler
VirtualPath="/MyWebSite"
PhysicalPath="c:\inetpub\wwwroot\MyWebSite\"
TargetPath="c:\precompiledweb\MyWebSite\"
Force="true"
Debug="true"
/>
</Target>
</Project>
select column1..... from table1
where column1=''
union
select column1..... from table2
where column1= ''
For those like me, who were looking for a pure Python solution without pandas
or numpy
involved, check out the following GitHub project: https://github.com/ThomIves/MatrixInverse.
It generously provides a very good explanation of how the process looks like "behind the scenes". The author has nicely described the step-by-step approach and presented some practical examples, all easy to follow.
This is just a little code snippet from there to illustrate the approach very briefly (AM
is the source matrix, IM
is the identity matrix of the same size):
def invert_matrix(AM, IM):
for fd in range(len(AM)):
fdScaler = 1.0 / AM[fd][fd]
for j in range(len(AM)):
AM[fd][j] *= fdScaler
IM[fd][j] *= fdScaler
for i in list(range(len(AM)))[0:fd] + list(range(len(AM)))[fd+1:]:
crScaler = AM[i][fd]
for j in range(len(AM)):
AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
return IM
But please do follow the entire thing, you'll learn a lot more than just copy-pasting this code! There's a Jupyter notebook as well, btw.
Hope that helps someone, I personally found it extremely useful for my very particular task (Absorbing Markov Chain) where I wasn't able to use any non-standard packages.
If you have your own library/package on GitHub, GitLab, etc., you have to add a tag to commit with a concrete version of the library, for example, v2.0, and then you can install your package:
pip install git+ssh://link/name/[email protected]
This works for me. Other solutions haven't worked for me.
In basic two way communication systems, socket.emit has proved to be more convincing and easy to use (personal experience) and is a part of Socket.IO which is primarily built for such purposes
Another reason may be if you add any html tag before this redirect. Look carefully, you may left DOCTYPE or any html comment before this line.
It is a self-executing anonymous function. The first set of parentheses contain the expressions to be executed, and the second set of parentheses executes those expressions.
It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.
See:
A slight tangent -- if you want to parse and evaluate an entire expression string which contains (nested!) functions, consider NCalc (http://ncalc.codeplex.com/ and nuget)
Ex. slightly modified from the project documentation:
// the expression to evaluate, e.g. from user input (like a calculator program, hint hint college students)
var exprStr = "10 + MyFunction(3, 6)";
Expression e = new Expression(exprString);
// tell it how to handle your custom function
e.EvaluateFunction += delegate(string name, FunctionArgs args) {
if (name == "MyFunction")
args.Result = (int)args.Parameters[0].Evaluate() + (int)args.Parameters[1].Evaluate();
};
// confirm it worked
Debug.Assert(19 == e.Evaluate());
And within the EvaluateFunction
delegate you would call your existing function.
Or you can use the command line below from version 4.4.x.
conda config --set proxy_servers.http http://id:pw@address:port
conda config --set proxy_servers.https https://id:pw@address:port
Try the following:-
ChangeYear:- When set to true, indicates that the cells of the previous or next month indicated in the calendar of the current month can be selected. This option is used with options.showOtherMonths set to true.
YearRange:- Specifies the range of years in the year dropdown. (Default value: “-10:+10")
Example:-
$(document).ready(function() {
$("#date").datepicker({
changeYear:true,
yearRange: "2005:2015"
});
});
v
has 10
element, the index starts from 0
to 9
.
for(int j=10;j>0;--j)
{
cout<<v[j]; // v[10] out of range
}
you should update for
loop to
for(int j=9; j>=0; --j)
// ^^^^^^^^^^
{
cout<<v[j]; // out of range
}
Or use reverse iterator to print element in reverse order
for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
std::cout << *ri << std::endl;
}
In MySQL, this works if there are multiple '=' characters in the string
SUBSTRING(supplier_reference FROM (LOCATE('=',supplier_reference)+1))
It returns the substring after(+1) having found the the first =
Here my approach,it may be useful to others.
public static void compareArrays(int[] array1, int[] array2) {
if (array1.length != array2.length)
{
System.out.println("Not Equal");
}
else
{
int temp = 0;
for (int i = 0; i < array2.length; i++) { //Take any one of the array size
temp^ = array1[i] ^ array2[i]; //with help of xor operator to find two array are equal or not
}
if( temp == 0 )
{
System.out.println("Equal");
}
else{
System.out.println("Not Equal");
}
}
}
A HANDLE in Win32 programming is a token that represents a resource that is managed by the Windows kernel. A handle can be to a window, a file, etc.
Handles are simply a way of identifying a particulate resource that you want to work with using the Win32 APIs.
So for instance, if you want to create a Window, and show it on the screen you could do the following:
// Create the window
HWND hwnd = CreateWindow(...);
if (!hwnd)
return; // hwnd not created
// Show the window.
ShowWindow(hwnd, SW_SHOW);
In the above example HWND means "a handle to a window".
If you are used to an object oriented language you can think of a HANDLE as an instance of a class with no methods who's state is only modifiable by other functions. In this case the ShowWindow function modifies the state of the Window HANDLE.
See Handles and Data Types for more information.
Groupby A:
In [0]: grp = df.groupby('A')
Within each group, sum over B and broadcast the values using transform. Then sort by B:
In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
B
2 -2.829710
5 -2.829710
1 0.253651
4 0.253651
0 0.551377
3 0.551377
Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:
In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]
In [3]: sort1
Out[3]:
A B C
2 baz -0.528172 False
5 baz -2.301539 True
1 bar -0.611756 True
4 bar 0.865408 False
0 foo 1.624345 False
3 foo -1.072969 True
Finally, sort the 'C' values within groups of 'A' using the sort=False
option to preserve the A sort order from step 1:
In [4]: f = lambda x: x.sort('C', ascending=False)
In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)
In [6]: sort2
Out[6]:
A B C
A
baz 5 baz -2.301539 True
2 baz -0.528172 False
bar 1 bar -0.611756 True
4 bar 0.865408 False
foo 3 foo -1.072969 True
0 foo 1.624345 False
Clean up the df index by using reset_index
with drop=True
:
In [7]: sort2.reset_index(0, drop=True)
Out[7]:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
For me, it worked to use Newtonsoft.Json:
using Newtonsoft.Json;
// ...
var output = JsonConvert.SerializeObject(ListOfMyObject);
Move semantics are based on rvalue references.
An rvalue is a temporary object, which is going to be destroyed at the end of the expression. In current C++, rvalues only bind to const
references. C++1x will allow non-const
rvalue references, spelled T&&
, which are references to an rvalue objects.
Since an rvalue is going to die at the end of an expression, you can steal its data. Instead of copying it into another object, you move its data into it.
class X {
public:
X(X&& rhs) // ctor taking an rvalue reference, so-called move-ctor
: data_()
{
// since 'x' is an rvalue object, we can steal its data
this->swap(std::move(rhs));
// this will leave rhs with the empty data
}
void swap(X&& rhs);
// ...
};
// ...
X f();
X x = f(); // f() returns result as rvalue, so this calls move-ctor
In the above code, with old compilers the result of f()
is copied into x
using X
's copy constructor. If your compiler supports move semantics and X
has a move-constructor, then that is called instead. Since its rhs
argument is an rvalue, we know it's not needed any longer and we can steal its value.
So the value is moved from the unnamed temporary returned from f()
to x
(while the data of x
, initialized to an empty X
, is moved into the temporary, which will get destroyed after the assignment).
Gradle looks for gradle.properties
files in these places:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradle
)Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).
Reference: https://gradle.org/docs/current/userguide/build_environment.html
nginx
, like all well-behaved programs, can be configured not to self-daemonize.
Use the daemon off
configuration directive described in http://wiki.nginx.org/CoreModule.
I think this is what you are looking for
<?php include ('Scripts/Php/connection.php');
//The connection.php script is executed inside the current file ?>
The script file can also be in a .txt format, it should still work, it does for me
e.g.
<?php include ('Scripts/Php/connection.txt');
//The connection.txt script is executed inside the current file ?>
create two tabs, one with the formulas and then a second where you paste link the entire table. the second tab should have no problems when sorting!
Here an idea to simplify the syntax:
public class IgnoreCase
{
private readonly string _value;
public IgnoreCase(string s)
{
_value = s;
}
protected bool Equals(IgnoreCase other)
{
return this == other;
}
public override bool Equals(object obj)
{
return obj != null &&
(ReferenceEquals(this, obj) || (obj.GetType() == GetType() && this == (IgnoreCase) obj));
}
public override int GetHashCode()
{
return _value?.GetHashCode() ?? 0;
}
public static bool operator ==(IgnoreCase a, IgnoreCase b)
{
return string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
}
public static bool operator !=(IgnoreCase a, IgnoreCase b)
{
return !(a == b);
}
public static implicit operator string(IgnoreCase s)
{
return s._value;
}
public static implicit operator IgnoreCase(string s)
{
return new IgnoreCase(s);
}
}
Usable like:
Console.WriteLine((IgnoreCase) "a" == "b"); // false
Console.WriteLine((IgnoreCase) "abc" == "abC"); // true
Console.WriteLine((IgnoreCase) "Abc" == "aBc"); // true
Console.WriteLine((IgnoreCase) "ABC" == "ABC"); // true
While looking at your code, the only thing I see wrong, is when you try to load the second database:
$DB2=$this->load->database($config);
When you want to retrieve the database object, you have to pass TRUE in the second argument.
From the Codeigniter User Guide:
By setting the second parameter to TRUE (boolean) the function will return the database object.
So, your code should instead be:
$DB2=$this->load->database($config, TRUE);
That will make it work.
If you want to pursue a "simple" solution, you might find this class I put together useful:
http://www.architectshack.com/TextFileEncodingDetector.ashx
It does the BOM detection automatically first, and then tries to differentiate between Unicode encodings without BOM, vs some other default encoding (generally Windows-1252, incorrectly labelled as Encoding.ASCII in .Net).
As noted above, a "heavier" solution involving NCharDet or MLang may be more appropriate, and as I note on the overview page of this class, the best is to provide some form of interactivity with the user if at all possible, because there simply is no 100% detection rate possible!
Snippet in case the site is offline:
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace KlerksSoft
{
public static class TextFileEncodingDetector
{
/*
* Simple class to handle text file encoding woes (in a primarily English-speaking tech
* world).
*
* - This code is fully managed, no shady calls to MLang (the unmanaged codepage
* detection library originally developed for Internet Explorer).
*
* - This class does NOT try to detect arbitrary codepages/charsets, it really only
* aims to differentiate between some of the most common variants of Unicode
* encoding, and a "default" (western / ascii-based) encoding alternative provided
* by the caller.
*
* - As there is no "Reliable" way to distinguish between UTF-8 (without BOM) and
* Windows-1252 (in .Net, also incorrectly called "ASCII") encodings, we use a
* heuristic - so the more of the file we can sample the better the guess. If you
* are going to read the whole file into memory at some point, then best to pass
* in the whole byte byte array directly. Otherwise, decide how to trade off
* reliability against performance / memory usage.
*
* - The UTF-8 detection heuristic only works for western text, as it relies on
* the presence of UTF-8 encoded accented and other characters found in the upper
* ranges of the Latin-1 and (particularly) Windows-1252 codepages.
*
* - For more general detection routines, see existing projects / resources:
* - MLang - Microsoft library originally for IE6, available in Windows XP and later APIs now (I think?)
* - MLang .Net bindings: http://www.codeproject.com/KB/recipes/DetectEncoding.aspx
* - CharDet - Mozilla browser's detection routines
* - Ported to Java then .Net: http://www.conceptdevelopment.net/Localization/NCharDet/
* - Ported straight to .Net: http://code.google.com/p/chardetsharp/source/browse
*
* Copyright Tao Klerks, 2010-2012, [email protected]
* Licensed under the modified BSD license:
*
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
- The name of the author may not be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*
* CHANGELOG:
* - 2012-02-03:
* - Simpler methods, removing the silly "DefaultEncoding" parameter (with "??" operator, saves no typing)
* - More complete methods
* - Optionally return indication of whether BOM was found in "Detect" methods
* - Provide straight-to-string method for byte arrays (GetStringFromByteArray)
*/
const long _defaultHeuristicSampleSize = 0x10000; //completely arbitrary - inappropriate for high numbers of files / high speed requirements
public static Encoding DetectTextFileEncoding(string InputFilename)
{
using (FileStream textfileStream = File.OpenRead(InputFilename))
{
return DetectTextFileEncoding(textfileStream, _defaultHeuristicSampleSize);
}
}
public static Encoding DetectTextFileEncoding(FileStream InputFileStream, long HeuristicSampleSize)
{
bool uselessBool = false;
return DetectTextFileEncoding(InputFileStream, _defaultHeuristicSampleSize, out uselessBool);
}
public static Encoding DetectTextFileEncoding(FileStream InputFileStream, long HeuristicSampleSize, out bool HasBOM)
{
if (InputFileStream == null)
throw new ArgumentNullException("Must provide a valid Filestream!", "InputFileStream");
if (!InputFileStream.CanRead)
throw new ArgumentException("Provided file stream is not readable!", "InputFileStream");
if (!InputFileStream.CanSeek)
throw new ArgumentException("Provided file stream cannot seek!", "InputFileStream");
Encoding encodingFound = null;
long originalPos = InputFileStream.Position;
InputFileStream.Position = 0;
//First read only what we need for BOM detection
byte[] bomBytes = new byte[InputFileStream.Length > 4 ? 4 : InputFileStream.Length];
InputFileStream.Read(bomBytes, 0, bomBytes.Length);
encodingFound = DetectBOMBytes(bomBytes);
if (encodingFound != null)
{
InputFileStream.Position = originalPos;
HasBOM = true;
return encodingFound;
}
//BOM Detection failed, going for heuristics now.
// create sample byte array and populate it
byte[] sampleBytes = new byte[HeuristicSampleSize > InputFileStream.Length ? InputFileStream.Length : HeuristicSampleSize];
Array.Copy(bomBytes, sampleBytes, bomBytes.Length);
if (InputFileStream.Length > bomBytes.Length)
InputFileStream.Read(sampleBytes, bomBytes.Length, sampleBytes.Length - bomBytes.Length);
InputFileStream.Position = originalPos;
//test byte array content
encodingFound = DetectUnicodeInByteSampleByHeuristics(sampleBytes);
HasBOM = false;
return encodingFound;
}
public static Encoding DetectTextByteArrayEncoding(byte[] TextData)
{
bool uselessBool = false;
return DetectTextByteArrayEncoding(TextData, out uselessBool);
}
public static Encoding DetectTextByteArrayEncoding(byte[] TextData, out bool HasBOM)
{
if (TextData == null)
throw new ArgumentNullException("Must provide a valid text data byte array!", "TextData");
Encoding encodingFound = null;
encodingFound = DetectBOMBytes(TextData);
if (encodingFound != null)
{
HasBOM = true;
return encodingFound;
}
else
{
//test byte array content
encodingFound = DetectUnicodeInByteSampleByHeuristics(TextData);
HasBOM = false;
return encodingFound;
}
}
public static string GetStringFromByteArray(byte[] TextData, Encoding DefaultEncoding)
{
return GetStringFromByteArray(TextData, DefaultEncoding, _defaultHeuristicSampleSize);
}
public static string GetStringFromByteArray(byte[] TextData, Encoding DefaultEncoding, long MaxHeuristicSampleSize)
{
if (TextData == null)
throw new ArgumentNullException("Must provide a valid text data byte array!", "TextData");
Encoding encodingFound = null;
encodingFound = DetectBOMBytes(TextData);
if (encodingFound != null)
{
//For some reason, the default encodings don't detect/swallow their own preambles!!
return encodingFound.GetString(TextData, encodingFound.GetPreamble().Length, TextData.Length - encodingFound.GetPreamble().Length);
}
else
{
byte[] heuristicSample = null;
if (TextData.Length > MaxHeuristicSampleSize)
{
heuristicSample = new byte[MaxHeuristicSampleSize];
Array.Copy(TextData, heuristicSample, MaxHeuristicSampleSize);
}
else
{
heuristicSample = TextData;
}
encodingFound = DetectUnicodeInByteSampleByHeuristics(TextData) ?? DefaultEncoding;
return encodingFound.GetString(TextData);
}
}
public static Encoding DetectBOMBytes(byte[] BOMBytes)
{
if (BOMBytes == null)
throw new ArgumentNullException("Must provide a valid BOM byte array!", "BOMBytes");
if (BOMBytes.Length < 2)
return null;
if (BOMBytes[0] == 0xff
&& BOMBytes[1] == 0xfe
&& (BOMBytes.Length < 4
|| BOMBytes[2] != 0
|| BOMBytes[3] != 0
)
)
return Encoding.Unicode;
if (BOMBytes[0] == 0xfe
&& BOMBytes[1] == 0xff
)
return Encoding.BigEndianUnicode;
if (BOMBytes.Length < 3)
return null;
if (BOMBytes[0] == 0xef && BOMBytes[1] == 0xbb && BOMBytes[2] == 0xbf)
return Encoding.UTF8;
if (BOMBytes[0] == 0x2b && BOMBytes[1] == 0x2f && BOMBytes[2] == 0x76)
return Encoding.UTF7;
if (BOMBytes.Length < 4)
return null;
if (BOMBytes[0] == 0xff && BOMBytes[1] == 0xfe && BOMBytes[2] == 0 && BOMBytes[3] == 0)
return Encoding.UTF32;
if (BOMBytes[0] == 0 && BOMBytes[1] == 0 && BOMBytes[2] == 0xfe && BOMBytes[3] == 0xff)
return Encoding.GetEncoding(12001);
return null;
}
public static Encoding DetectUnicodeInByteSampleByHeuristics(byte[] SampleBytes)
{
long oddBinaryNullsInSample = 0;
long evenBinaryNullsInSample = 0;
long suspiciousUTF8SequenceCount = 0;
long suspiciousUTF8BytesTotal = 0;
long likelyUSASCIIBytesInSample = 0;
//Cycle through, keeping count of binary null positions, possible UTF-8
// sequences from upper ranges of Windows-1252, and probable US-ASCII
// character counts.
long currentPos = 0;
int skipUTF8Bytes = 0;
while (currentPos < SampleBytes.Length)
{
//binary null distribution
if (SampleBytes[currentPos] == 0)
{
if (currentPos % 2 == 0)
evenBinaryNullsInSample++;
else
oddBinaryNullsInSample++;
}
//likely US-ASCII characters
if (IsCommonUSASCIIByte(SampleBytes[currentPos]))
likelyUSASCIIBytesInSample++;
//suspicious sequences (look like UTF-8)
if (skipUTF8Bytes == 0)
{
int lengthFound = DetectSuspiciousUTF8SequenceLength(SampleBytes, currentPos);
if (lengthFound > 0)
{
suspiciousUTF8SequenceCount++;
suspiciousUTF8BytesTotal += lengthFound;
skipUTF8Bytes = lengthFound - 1;
}
}
else
{
skipUTF8Bytes--;
}
currentPos++;
}
//1: UTF-16 LE - in english / european environments, this is usually characterized by a
// high proportion of odd binary nulls (starting at 0), with (as this is text) a low
// proportion of even binary nulls.
// The thresholds here used (less than 20% nulls where you expect non-nulls, and more than
// 60% nulls where you do expect nulls) are completely arbitrary.
if (((evenBinaryNullsInSample * 2.0) / SampleBytes.Length) < 0.2
&& ((oddBinaryNullsInSample * 2.0) / SampleBytes.Length) > 0.6
)
return Encoding.Unicode;
//2: UTF-16 BE - in english / european environments, this is usually characterized by a
// high proportion of even binary nulls (starting at 0), with (as this is text) a low
// proportion of odd binary nulls.
// The thresholds here used (less than 20% nulls where you expect non-nulls, and more than
// 60% nulls where you do expect nulls) are completely arbitrary.
if (((oddBinaryNullsInSample * 2.0) / SampleBytes.Length) < 0.2
&& ((evenBinaryNullsInSample * 2.0) / SampleBytes.Length) > 0.6
)
return Encoding.BigEndianUnicode;
//3: UTF-8 - Martin Dürst outlines a method for detecting whether something CAN be UTF-8 content
// using regexp, in his w3c.org unicode FAQ entry:
// http://www.w3.org/International/questions/qa-forms-utf-8
// adapted here for C#.
string potentiallyMangledString = Encoding.ASCII.GetString(SampleBytes);
Regex UTF8Validator = new Regex(@"\A("
+ @"[\x09\x0A\x0D\x20-\x7E]"
+ @"|[\xC2-\xDF][\x80-\xBF]"
+ @"|\xE0[\xA0-\xBF][\x80-\xBF]"
+ @"|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}"
+ @"|\xED[\x80-\x9F][\x80-\xBF]"
+ @"|\xF0[\x90-\xBF][\x80-\xBF]{2}"
+ @"|[\xF1-\xF3][\x80-\xBF]{3}"
+ @"|\xF4[\x80-\x8F][\x80-\xBF]{2}"
+ @")*\z");
if (UTF8Validator.IsMatch(potentiallyMangledString))
{
//Unfortunately, just the fact that it CAN be UTF-8 doesn't tell you much about probabilities.
//If all the characters are in the 0-127 range, no harm done, most western charsets are same as UTF-8 in these ranges.
//If some of the characters were in the upper range (western accented characters), however, they would likely be mangled to 2-byte by the UTF-8 encoding process.
// So, we need to play stats.
// The "Random" likelihood of any pair of randomly generated characters being one
// of these "suspicious" character sequences is:
// 128 / (256 * 256) = 0.2%.
//
// In western text data, that is SIGNIFICANTLY reduced - most text data stays in the <127
// character range, so we assume that more than 1 in 500,000 of these character
// sequences indicates UTF-8. The number 500,000 is completely arbitrary - so sue me.
//
// We can only assume these character sequences will be rare if we ALSO assume that this
// IS in fact western text - in which case the bulk of the UTF-8 encoded data (that is
// not already suspicious sequences) should be plain US-ASCII bytes. This, I
// arbitrarily decided, should be 80% (a random distribution, eg binary data, would yield
// approx 40%, so the chances of hitting this threshold by accident in random data are
// VERY low).
if ((suspiciousUTF8SequenceCount * 500000.0 / SampleBytes.Length >= 1) //suspicious sequences
&& (
//all suspicious, so cannot evaluate proportion of US-Ascii
SampleBytes.Length - suspiciousUTF8BytesTotal == 0
||
likelyUSASCIIBytesInSample * 1.0 / (SampleBytes.Length - suspiciousUTF8BytesTotal) >= 0.8
)
)
return Encoding.UTF8;
}
return null;
}
private static bool IsCommonUSASCIIByte(byte testByte)
{
if (testByte == 0x0A //lf
|| testByte == 0x0D //cr
|| testByte == 0x09 //tab
|| (testByte >= 0x20 && testByte <= 0x2F) //common punctuation
|| (testByte >= 0x30 && testByte <= 0x39) //digits
|| (testByte >= 0x3A && testByte <= 0x40) //common punctuation
|| (testByte >= 0x41 && testByte <= 0x5A) //capital letters
|| (testByte >= 0x5B && testByte <= 0x60) //common punctuation
|| (testByte >= 0x61 && testByte <= 0x7A) //lowercase letters
|| (testByte >= 0x7B && testByte <= 0x7E) //common punctuation
)
return true;
else
return false;
}
private static int DetectSuspiciousUTF8SequenceLength(byte[] SampleBytes, long currentPos)
{
int lengthFound = 0;
if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xC2
)
{
if (SampleBytes[currentPos + 1] == 0x81
|| SampleBytes[currentPos + 1] == 0x8D
|| SampleBytes[currentPos + 1] == 0x8F
)
lengthFound = 2;
else if (SampleBytes[currentPos + 1] == 0x90
|| SampleBytes[currentPos + 1] == 0x9D
)
lengthFound = 2;
else if (SampleBytes[currentPos + 1] >= 0xA0
&& SampleBytes[currentPos + 1] <= 0xBF
)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xC3
)
{
if (SampleBytes[currentPos + 1] >= 0x80
&& SampleBytes[currentPos + 1] <= 0xBF
)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xC5
)
{
if (SampleBytes[currentPos + 1] == 0x92
|| SampleBytes[currentPos + 1] == 0x93
)
lengthFound = 2;
else if (SampleBytes[currentPos + 1] == 0xA0
|| SampleBytes[currentPos + 1] == 0xA1
)
lengthFound = 2;
else if (SampleBytes[currentPos + 1] == 0xB8
|| SampleBytes[currentPos + 1] == 0xBD
|| SampleBytes[currentPos + 1] == 0xBE
)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xC6
)
{
if (SampleBytes[currentPos + 1] == 0x92)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xCB
)
{
if (SampleBytes[currentPos + 1] == 0x86
|| SampleBytes[currentPos + 1] == 0x9C
)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 2
&& SampleBytes[currentPos] == 0xE2
)
{
if (SampleBytes[currentPos + 1] == 0x80)
{
if (SampleBytes[currentPos + 2] == 0x93
|| SampleBytes[currentPos + 2] == 0x94
)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0x98
|| SampleBytes[currentPos + 2] == 0x99
|| SampleBytes[currentPos + 2] == 0x9A
)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0x9C
|| SampleBytes[currentPos + 2] == 0x9D
|| SampleBytes[currentPos + 2] == 0x9E
)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0xA0
|| SampleBytes[currentPos + 2] == 0xA1
|| SampleBytes[currentPos + 2] == 0xA2
)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0xA6)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0xB0)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0xB9
|| SampleBytes[currentPos + 2] == 0xBA
)
lengthFound = 3;
}
else if (SampleBytes[currentPos + 1] == 0x82
&& SampleBytes[currentPos + 2] == 0xAC
)
lengthFound = 3;
else if (SampleBytes[currentPos + 1] == 0x84
&& SampleBytes[currentPos + 2] == 0xA2
)
lengthFound = 3;
}
return lengthFound;
}
}
}
Another approach that is really fast is the MSS module. It is different from other solutions in the way that it uses only the ctypes
standard module, so it does not require big dependencies. It is OS independant and its use is made easy:
from mss import mss
with mss() as sct:
sct.shot()
And just find the screenshot.png
file containing the screen shot of the first monitor. There are a lot of possibile customizations, you can play with ScreenShot
objects and OpenCV/Numpy/PIL/etc..
That's the way I'd prefer to see if I was maintaining your code. If you manage to find a faster solution, it's going to be very esoteric, and you should really bury it inside of a method that describes what it does.
(does it still work without the ToArray)?
It ought to be implemented in msysgit, but there are two downsides:
I did a quick search and there is work being actively done on this, see issue 224.
At my previous job we struggled with getting our rich UI app to paint instantly and smoothly. We were using standard .Net controls, custom controls and devexpress controls.
After a lot of googling and reflector usage I came across the WM_SETREDRAW win32 message. This really stops controls drawing whilst you update them and can be applied, IIRC to the parent/containing panel.
This is a very very simple class demonstrating how to use this message:
class DrawingControl
{
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
private const int WM_SETREDRAW = 11;
public static void SuspendDrawing( Control parent )
{
SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
}
public static void ResumeDrawing( Control parent )
{
SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
parent.Refresh();
}
}
There are fuller discussions on this - google for C# and WM_SETREDRAW, e.g.
And to whom it may concern, this is similar example in VB:
Public Module Extensions
<DllImport("user32.dll")>
Private Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Boolean, ByVal lParam As IntPtr) As Integer
End Function
Private Const WM_SETREDRAW As Integer = 11
' Extension methods for Control
<Extension()>
Public Sub ResumeDrawing(ByVal Target As Control, ByVal Redraw As Boolean)
SendMessage(Target.Handle, WM_SETREDRAW, True, 0)
If Redraw Then
Target.Refresh()
End If
End Sub
<Extension()>
Public Sub SuspendDrawing(ByVal Target As Control)
SendMessage(Target.Handle, WM_SETREDRAW, False, 0)
End Sub
<Extension()>
Public Sub ResumeDrawing(ByVal Target As Control)
ResumeDrawing(Target, True)
End Sub
End Module
I'd just like to point out that Apache has the worst inheritance rules when using multiple .htaccess files across directory depths. Two key pitfalls:
RewriteOptions InheritDownBefore
directive (or similar) to change this. (see question)This means the suggested global solution on the Apache Wiki does not work if you use any other .htaccess files in subdirectories. I wrote a modified version that does:
RewriteEngine On
# This will enable the Rewrite capabilities
RewriteOptions InheritDownBefore
# This prevents the rule from being overrided by .htaccess files in subdirectories.
RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [QSA,R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e. http://www.example.com/foo/ to https://www.example.com/foo/
Windows Firewall was creating this error for me. SMTP was trying to post to GMAIL at port 587. Adding port 587 to the Outbound rule [Outbound HTTP/SMTP/RDP] resolved the issue.
Make use of *(B)
instead of *B[0]
.
Here, *(B+i)
implies B[i]
and *(B)
implies B[0
], that is *(B+0)=*(B)=B[0]
.
#include <stdio.h>
int func(int *B){
*B = 5;
// if you want to modify ith index element in the array just do *(B+i)=<value>
}
int main(void){
int B[10] = {};
printf("b[0] = %d\n\n", B[0]);
func(B);
printf("b[0] = %d\n\n", B[0]);
return 0;
}
Your connection failed because by default psql
connects over UNIX sockets using peer
authentication, that requires the current UNIX user to have the same user name as psql
. So you will have to create the UNIX user dev
and then login as dev
or use sudo -u dev psql test_development
for accessing the database (and psql
should not ask for a password).
If you cannot or do not want to create the UNIX user, like if you just want to connect to your database for ad hoc queries, forcing a socket connection using psql --host=localhost --dbname=test_development --username=dev
(as pointed out by @meyerson answer) will solve your immediate problem.
But if you intend to force password authentication over Unix sockets instead of the peer method, try changing the following pg_hba.conf
* line:
from
# TYPE DATABASE USER ADDRESS METHOD
local all all peer
to
# TYPE DATABASE USER ADDRESS METHOD
local all all md5
peer
means it will trust the identity (authenticity) of UNIX user. So not asking for a password.
md5
means it will always ask for a password, and validate it after hashing with MD5
.
You can, of course, also create more specific rules for a specific database or user, with some users having peer
and others requiring passwords.
After changing pg_hba.conf
if PostgreSQL is running you'll need to make it re-read the configuration by reloading (pg_ctl reload
) or restarting (sudo service postgresql restart
).
* The file pg_hba.conf
will most likely be at /etc/postgresql/9.x/main/pg_hba.conf
Edited: Remarks from @Chloe, @JavierEH, @Jonas Eicher, @fccoelho, @Joanis, @Uphill_What comments incorporated into answer.
Basically the same solution as provided by Rutger Kassies, but using a more pythonic syntax:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
data = np.arange(250, 260)
for ax, d in zip(axs.ravel(), data):
ax.contourf(np.random.rand(10,10), 5, cmap=plt.cm.Oranges)
ax.set_title(str(d))
I met the same problem before, also read the answers here, but doesn't found any satisfy solution can balance the compatibility, performance and well format output, the Jython can't work with extend C packages and slower than CPython. So finally I decided to invent the wheel myself, it took my 5 nights, I hope it can help you too: jpserve(https://github.com/johnhuang-cn/jpserve).
JPserve provides a simple way to call Python and exchange the result by well format JSON, few performance loss. The following is the sample code.
At first, start jpserve on Python side
>>> from jpserve.jpserve import JPServe
>>> serve = JPServe(("localhost", 8888))
>>> serve.start()
INFO:JPServe:JPServe starting...
INFO:JPServe:JPServe listening in localhost 8888
Then call Python from JAVA side:
PyServeContext.init("localhost", 8888);
PyExecutor executor = PyServeContext.getExecutor();
script = "a = 2\n"
+ "b = 3\n"
+ "_result_ = a * b";
PyResult rs = executor.exec(script);
System.out.println("Result: " + rs.getResult());
---
Result: 6
You can use substring to get portio of String which is equal to 1 mb:
public static void main(String[] args) {
// Get length of String in bytes
String string = "long string";
long sizeInBytes = string.getBytes().length;
int oneMb=1024*1024;
if (sizeInBytes>oneMb) {
String string1Mb=string.substring(0, oneMb);
}
}
you can use grep incase you are not keen in the sequence of the pattern.
grep -l "pattern1" filepattern*.* | xargs grep "pattern2"
example
grep -l "vector" *.cpp | xargs grep "map"
grep -l
will find all the files which matches the first pattern, and xargs will grep for the second pattern. Hope this helps.
To get timestamp from NSDate Swift 3
func getCurrentTimeStampWOMiliseconds(dateToConvert: NSDate) -> String {
let objDateformat: DateFormatter = DateFormatter()
objDateformat.dateFormat = "yyyy-MM-dd HH:mm:ss"
let strTime: String = objDateformat.string(from: dateToConvert as Date)
let objUTCDate: NSDate = objDateformat.date(from: strTime)! as NSDate
let milliseconds: Int64 = Int64(objUTCDate.timeIntervalSince1970)
let strTimeStamp: String = "\(milliseconds)"
return strTimeStamp
}
To use
let now = NSDate()
let nowTimeStamp = self.getCurrentTimeStampWOMiliseconds(dateToConvert: now)
You can do something similar:
var tuple = Object.freeze({ name:'Bob', age:14 })
and then refer to name and age as attributes
tuple.name
tuple.age
You can do this type of checking with Flash or Silverlight but not Javascript. The javascript sandbox does not allow access to the file system. The size check would need to be done server side after it has been uploaded.
If you want to go the Silverlight/Flash route, you could check that if they are not installed to default to a regular file upload handler that uses the normal controls. This way, if the do have Silverlight/Flash installed their experience will be a bit more rich.
woocommerce_get_product_terms()
is now deprecated.
Use wc_get_product_terms()
instead.
Example:
global $product;
$koostis = array_shift( wc_get_product_terms( $product->id, 'pa_koostis', array( 'fields' => 'names' ) ) );
Use which:
set.seed(1)
x <- sample(10, 50, replace = TRUE)
length(which(x > 3 & x < 5))
# [1] 6
The problem with the above approaches, is that you have to repeat the several case
s every time you call the function which has the switch
. A more robust solution is to have a map or a dictionary.
Here is an example:
// The Map, divided by concepts
var dictionary = {
timePeriod: {
'month': [1, 'monthly', 'mensal', 'mês'],
'twoMonths': [2, 'two months', '2 months', 'bimestral', 'bimestre'],
'trimester': [3, 'trimesterly', 'quarterly', 'trimestral'],
'semester': [4, 'semesterly', 'semestral', 'halfyearly'],
'year': [5, 'yearly', 'annual', 'ano']
},
distance: {
'km': [1, 'kms', 'kilometre', 'kilometers', 'kilometres'],
'mile': [2, 'mi', 'miles'],
'nordicMile': [3, 'Nordic mile', 'mil (10 km)', 'Scandinavian mile']
},
fuelAmount: {
'ltr': [1, 'l', 'litre', 'Litre', 'liter', 'Liter'],
'gal (imp)': [2, 'imp gallon', 'imperial gal', 'gal (UK)'],
'gal (US)': [3, 'US gallon', 'US gal'],
'kWh': [4, 'KWH']
}
};
// This function maps every input to a certain defined value
function mapUnit (concept, value) {
for (var key in dictionary[concept]) {
if (key === value ||
dictionary[concept][key].indexOf(value) !== -1) {
return key
}
}
throw Error('Uknown "'+value+'" for "'+concept+'"')
}
// You would use it simply like this
mapUnit("fuelAmount", "ltr") // => ltr
mapUnit("fuelAmount", "US gal") // => gal (US)
mapUnit("fuelAmount", 3) // => gal (US)
mapUnit("distance", "kilometre") // => km
// Now you can use the switch statement safely without the need
// to repeat the combinations every time you call the switch
var foo = 'monthly'
switch (mapUnit ('timePeriod', foo)) {
case 'month':
console.log('month')
break
case 'twoMonths':
console.log('twoMonths')
break
case 'trimester':
console.log('trimester')
break
case 'semester':
console.log('semester')
break
case 'year':
console.log('year')
break
default:
throw Error('error')
}
_x000D_
This doesn't exactly apply to your situation, but I had the same thing -- tests that would pass in Eclipse failed when the test goal from Maven was run.
It turned out to be a test earlier in my suite, in a different package. This took me a week to solve!
An earlier test was testing some Logback classes, and created a Logback context from a config file.
The later test was testing a subclass of Spring's SimpleRestTemplate, and somehow, the earlier Logback context was held, with DEBUG on. This caused extra calls to be made in RestTemplate to log HttpStatus, etc.
It's another thing to check if one ever gets into this situation. I fixed my problem by injecting some Mocks into my Logback test class, so that no real Logback contexts were created.
you can get the json string as a param of your ActionResult
and afterwards serialize it using JSON.Net
HERE an example is being shown
in order to receive it in the serialized form as a param of the controller action you must either write a custom model binder or a Action filter (OnActionExecuting) so that the json string is serialized into the model of your liking and is available inside the controller body for use.
HERE is an implementation using the dynamic object
The DLL has to be in the bin folder.
In Visual Studio, I add the dll to my project (NOT in References, but "Add existing file"). Then set the "Copy to Output Directory" Property for the dll to "Copy if newer".
This is how I solved this problem:
First you have to get the SHA-1 value. For that there are two ways.
OR
keytool -list -v -keystore keystore_file_name.jks -alias key0
Copy the SHA-1 value to your clipboard like this:
CD:A1:EA:A3:5C:5C:68:FB:FA:0A:6B:E5:5A:72:64:DD:26:8D:44:84
And open Hexadecimal -> Base64 string decoder to convert your SHA-1 value to Base64.
This is what Facebook requires.
Get the generated hash " ********************= " and copy the key hash to the Facebook app.
You could also just change the @RequestParam default required status to false so that HTTP response status code 400 is not generated. This will allow you to place the Annotations in any order you feel like.
@RequestParam(required = false)String name
Have your person class implement Comparable<Person>
and then implement the compareTo method, for instance:
public int compareTo(Person o) {
int result = name.compareToIgnoreCase(o.name);
if(result==0) {
return Integer.valueOf(age).compareTo(o.age);
}
else {
return result;
}
}
That will sort first by name (case insensitively) and then by age. You can then run Arrays.sort()
or Collections.sort()
on the collection or array of Person objects.
You can use this apk
1.first install the app from the Google play store
2.install the above apk
3.launch the apk and input the package name of your app
4.then you will get the hash code you want
This is an intuitive solution using the viewport command that just sets the minimum height to the viewport height minus the footer height.
html,body{
height: 100%
}
#nonFooter{
min-height: calc(100vh - 30px)
}
#footer {
height:30px;
margin: 0;
clear: both;
width:100%;
}
Terminates this process and gives the underlying operating system the specified exit code.
https://msdn.microsoft.com/en-us/library/system.environment.exit%28v=vs.110%29.aspx
[Environment]::Exit(1)
This will allow you to exit with a specific exit code, that can be picked up from the caller.
Closing Visual Studio and re-opening worked for me. Must be a weird bug.
Arduino (c++) version based on Valentinos answer
unsigned long timeNow = 0;
unsigned long mSecInHour = 3600000;
unsigned long TimeNow =0;
int millisecs =0;
int seconds = 0;
byte minutes = 0;
byte hours = 0;
void setup() {
Serial.begin(9600);
Serial.println (""); // because arduino monitor gets confused with line 1
Serial.println ("hours:minutes:seconds.milliseconds:");
}
void loop() {
TimeNow = millis();
hours = TimeNow/mSecInHour;
minutes = (TimeNow-(hours*mSecInHour))/(mSecInHour/60);
seconds = (TimeNow-(hours*mSecInHour)-(minutes*(mSecInHour/60)))/1000;
millisecs = TimeNow-(hours*mSecInHour)-(minutes*(mSecInHour/60))- (seconds*1000);
Serial.print(hours);
Serial.print(":");
Serial.print(minutes);
Serial.print(":");
Serial.print(seconds);
Serial.print(".");
Serial.println(millisecs);
}
You should avoid using pool.getConnection()
if you can. If you call pool.getConnection()
, you must call connection.release()
when you are done using the connection. Otherwise, your application will get stuck waiting forever for connections to be returned to the pool once you hit the connection limit.
For simple queries, you can use pool.query()
. This shorthand will automatically call connection.release()
for you—even in error conditions.
function doSomething(cb) {
pool.query('SELECT 2*2 "value"', (ex, rows) => {
if (ex) {
cb(ex);
} else {
cb(null, rows[0].value);
}
});
}
However, in some cases you must use pool.getConnection()
. These cases include:
If you must use pool.getConnection()
, ensure you call connection.release()
using a pattern similar to below:
function doSomething(cb) {
pool.getConnection((ex, connection) => {
if (ex) {
cb(ex);
} else {
// Ensure that any call to cb releases the connection
// by wrapping it.
cb = (cb => {
return function () {
connection.release();
cb.apply(this, arguments);
};
})(cb);
connection.beginTransaction(ex => {
if (ex) {
cb(ex);
} else {
connection.query('INSERT INTO table1 ("value") VALUES (\'my value\');', ex => {
if (ex) {
cb(ex);
} else {
connection.query('INSERT INTO table2 ("value") VALUES (\'my other value\')', ex => {
if (ex) {
cb(ex);
} else {
connection.commit(ex => {
cb(ex);
});
}
});
}
});
}
});
}
});
}
I personally prefer to use Promise
s and the useAsync()
pattern. This pattern combined with async
/await
makes it a lot harder to accidentally forget to release()
the connection because it turns your lexical scoping into an automatic call to .release()
:
async function usePooledConnectionAsync(actionAsync) {
const connection = await new Promise((resolve, reject) => {
pool.getConnection((ex, connection) => {
if (ex) {
reject(ex);
} else {
resolve(connection);
}
});
});
try {
return await actionAsync(connection);
} finally {
connection.release();
}
}
async function doSomethingElse() {
// Usage example:
const result = await usePooledConnectionAsync(async connection => {
const rows = await new Promise((resolve, reject) => {
connection.query('SELECT 2*4 "value"', (ex, rows) => {
if (ex) {
reject(ex);
} else {
resolve(rows);
}
});
});
return rows[0].value;
});
console.log(`result=${result}`);
}
There's an extension that shows line endings. You can configure the color used, the characters that represent CRLF and LF and a boolean that turns it on and off.
Name: Line endings
Id: jhartell.vscode-line-endings
Description: Display line ending characters in vscode
Version: 0.1.0
Publisher: Johnny Härtell
Yet another answer ...
In my case I had a Visual Studio 2017 project targeting both .Net Standard 1.3 and .Net Framework 2.0. This was specified in the .csproj file like this:
<TargetFrameworks>netstandard1.3;net20</TargetFrameworks>
I also had a post-build event command line like this:
copy "E:\Yacks\YacksCore\YacksCore\bin\net20\Merlinia.YacksCore.dll" "E:\Merlinia\Trunk-Debug\Shared Bin\"
In other words I was trying to copy the .Net Framework .dll produced by the build to an alternative location.
This was failing with this error when I did a Rebuild:
MSB3073 The command "copy "E:\Yacks\YacksCore\YacksCore\bin\net20\Merlinia.YacksCore.dll" "E:\Merlinia\Trunk-Debug\Shared Bin\"" exited with code 1.
After much frustration I finally determined that what was happening was that Rebuild deleted all of the output files, then did the build for .Net Standard 1.3, then tried to run the post-build event command line, which failed because the file to be copied wasn't built yet.
So the solution was to change the order of building, i.e., build for .Net Framework 2.0 first, then for .Net Standard 1.3.
<TargetFrameworks>net20;netstandard1.3</TargetFrameworks>
This now works, with the minor glitch that the post-build event command line is being run twice, so the file is copied twice.
If you want something more C++-like, this is what I use. Although it depends on Boost, that's just for exceptions. You can easily remove those leaving it to depend only on the STL and the WideCharToMultiByte()
Win32 API call.
#include <string>
#include <vector>
#include <cassert>
#include <exception>
#include <boost/system/system_error.hpp>
#include <boost/integer_traits.hpp>
/**
* Convert a Windows wide string to a UTF-8 (multi-byte) string.
*/
std::string WideStringToUtf8String(const std::wstring& wide)
{
if (wide.size() > boost::integer_traits<int>::const_max)
throw std::length_error(
"Wide string cannot be more than INT_MAX characters long.");
if (wide.size() == 0)
return "";
// Calculate necessary buffer size
int len = ::WideCharToMultiByte(
CP_UTF8, 0, wide.c_str(), static_cast<int>(wide.size()),
NULL, 0, NULL, NULL);
// Perform actual conversion
if (len > 0)
{
std::vector<char> buffer(len);
len = ::WideCharToMultiByte(
CP_UTF8, 0, wide.c_str(), static_cast<int>(wide.size()),
&buffer[0], static_cast<int>(buffer.size()), NULL, NULL);
if (len > 0)
{
assert(len == static_cast<int>(buffer.size()));
return std::string(&buffer[0], buffer.size());
}
}
throw boost::system::system_error(
::GetLastError(), boost::system::system_category);
}
(untested) something like this may do the job
WITH
base AS
(
select * -- get the table
from sometable
order by name -- in the desired order
),
twenty AS
(
select * -- get the first 30 rows
from base
where rownum < 30
order by name -- in the desired order
)
select * -- then get rows 21 .. 30
from twenty
where rownum > 20
order by name -- in the desired order
There is also the analytic function rank, that you can use to order by.
To automatically fix all android to androidx issues for React Native (prerequisite npx)
Add the following two flags to true
in your gradle.properties
file at ProjectFolder/android/gradle.properties
android.useAndroidX=true
android.enableJetifier=true
Execute
npm install --save-dev jetifier
npx jetify
npx react-native run-android
In your package.json add the following to scripts
"postinstall" : "npx jetify"
More info at https://github.com/mikehardy/jetifier
Update: This is now in-built in react-native 0.60. If you migrate to react-native 0.60 you won't need this step. - https://facebook.github.io/react-native/blog/2019/07/03/version-60#androidx-support
Try this
<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />
if you want 0 or 1 "description" elements, Or
<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />
if you want 0 to infinity number of "description" elements.
You just need to have your class inherit from Comparable.
then implement the compareTo method the way you like.
You can also use Uploadify, which is a great jQuery upload plugin, it let's you upload multiple files, and also style the file fields easily. http://www.uploadify.com
This is not "auto-completion", this is automation. One common tool for these things is called Expect.
You might also get away with just piping input from yes
.
You would use data validation for this. Click in the cell you want to have a multiple drop down > DATA > Validation > Criteria (List from a Range) - here you select form a list of items you want in the drop down. And .. you are good. I have included an example to reference.
Just in case Milen A. Radev doesn't get around to posting his solution, this is it:
CREATE TABLE foo (
key int PRIMARY KEY,
foo text NOT NULL DEFAULT TO_CHAR(CURRENT_TIMESTAMP,'YYYYMM')
);
You accidentally created the column name with a trailing space and presumably phpPGadmin created the column name with double quotes around it:
create table your_table (
"foo " -- ...
)
That would give you a column that looked like it was called foo
everywhere but you'd have to double quote it and include the space whenever you use it:
select ... from your_table where "foo " is not null
The best practice is to use lower case unquoted column names with PostgreSQL. There should be a setting in phpPGadmin somewhere that will tell it to not quote identifiers (such as table and column names) but alas, I don't use phpPGadmin so I don't where that setting is (or even if it exists).
One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .
<input inputmode='none'>
The
inputmode
global attribute is an enumerated attribute that hints at the type of data that might be entered by the user while editing the element or its contents. It can have the following values:
none
- No virtual keyboard. For when the page implements its own keyboard input control.
I am using this successfully (Tested on Chrome/Android)
CSS-Tricks: Everything You Ever Wanted to Know About inputmode