How can I run code on a background thread on Android?
class Background implements Runnable {
private CountDownLatch latch = new CountDownLatch(1);
private Handler handler;
Background() {
Thread thread = new Thread(this);
thread.start();
try {
latch.await();
} catch (InterruptedException e) {
/// e.printStackTrace();
}
}
@Override
public void run() {
Looper.prepare();
handler = new Handler();
latch.countDown();
Looper.loop();
}
public Handler getHandler() {
return handler;
}
}
How to insert double and float values to sqlite?
SQL Supports following types of affinities:
- TEXT
- NUMERIC
- INTEGER
- REAL
- BLOB
If the declared type for a column contains any of these "REAL", "FLOAT", or "DOUBLE" then the column has 'REAL' affinity.
return query based on date
If you want to get all new things in the past 5 minutes you would have to do some calculations, but its not hard...
First create an index on the property you want to match on (include sort direction -1 for descending and 1 for ascending)
db.things.createIndex({ createdAt: -1 }) // descending order on .createdAt
Then query for documents created in the last 5 minutes (60 seconds * 5 minutes)....because javascript's .getTime()
returns milliseconds you need to mulitply by 1000 before you use it as input to the new Date()
constructor.
db.things.find({
createdAt: {
$gte: new Date(new Date().getTime()-60*5*1000).toISOString()
}
})
.count()
Explanation for new Date(new Date().getTime()-60*5*1000).toISOString()
is as follows:
First we calculate "5 minutes ago":
new Date().getTime()
gives us current time in milliseconds
- We want to subtract 5 minutes (in ms) from that:
5*60*1000
-- I just multiply by 60
seconds so its easy to change. I can just change 5
to 120
if I want 2 hours (120 minutes).
new Date().getTime()-60*5*1000
gives us 1484383878676
(5 minutes ago in ms)
Now we need to feed that into a new Date()
constructor to get the ISO string format required by MongoDB timestamps.
{ $gte: new Date(resultFromAbove).toISOString() }
(mongodb .find() query)
- Since we can't have variables we do it all in one shot:
new Date(new Date().getTime()-60*5*1000)
- ...then convert to ISO string:
.toISOString()
new Date(new Date().getTime()-60*5*1000).toISOString()
gives us 2017-01-14T08:53:17.586Z
Of course this is a little easier with variables if you're using the node-mongodb-native driver, but this works in the mongo shell which is what I usually use to check things.
How to convert string date to Timestamp in java?
You can convert String to Timestamp:
String inDate = "01-01-1990"
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
Timestamp ts = new Timestamp(((java.util.Date)df.parse(inDate)).getTime());
How to declare std::unique_ptr and what is the use of it?
From cppreference, one of the std::unique_ptr
constructors is
explicit unique_ptr( pointer p ) noexcept;
So to create a new std::unique_ptr
is to pass a pointer to its constructor.
unique_ptr<int> uptr (new int(3));
Or it is the same as
int *int_ptr = new int(3);
std::unique_ptr<int> uptr (int_ptr);
The different is you don't have to clean up after using it. If you don't use std::unique_ptr
(smart pointer), you will have to delete it like this
delete int_ptr;
when you no longer need it or it will cause a memory leak.
How to use boost bind with a member function
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
What is the difference between Cygwin and MinGW?
Don't overlook AT&T's U/Win software, which is designed to help you compile Unix applications on windows (last version - 2012-08-06; uses Eclipse Public License, Version 1.0).
Like Cygwin they have to run against a library; in their case POSIX.DLL
. The AT&T guys are terrific engineers (same group that brought you ksh and dot) and their stuff is worth checking out.
bootstrap initially collapsed element
another solution is to add toggle=false to the collapse target, this will stop it randomly opening and closing which happens if you just remove the "in"
eg
<div class="accordion-heading">
<a class="accordion-toggle"
data-toggle="collapse"
data-parent="#accordion2"
href="#collapseOne">Open!</a>
</div>
<div
id="collapseOne"
class="accordion-body collapse"
data-toggle="false"
>
<div class="span6">
<div class="well well-small">
<div class="accordion-toggle">
...some text...
</div>
</div>
</div>
<div class="span2"></div>
</div>
How do I get the difference between two Dates in JavaScript?
this code fills the duration of study years when you input the start date and end date(qualify accured date) of study and check if the duration less than a year if yes the alert a message
take in mind there are three input elements the first txtFromQualifDate
and second txtQualifDate
and third txtStudyYears
it will show result of number of years with fraction
function getStudyYears()
{
if(document.getElementById('txtFromQualifDate').value != '' && document.getElementById('txtQualifDate').value != '')
{
var d1 = document.getElementById('txtFromQualifDate').value;
var d2 = document.getElementById('txtQualifDate').value;
var one_day=1000*60*60*24;
var x = d1.split("/");
var y = d2.split("/");
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0])
var dDays = (date2.getTime()-date1.getTime())/one_day;
if(dDays < 365)
{
alert("the date between start study and graduate must not be less than a year !");
document.getElementById('txtQualifDate').value = "";
document.getElementById('txtStudyYears').value = "";
return ;
}
var dMonths = Math.ceil(dDays / 30);
var dYears = Math.floor(dMonths /12) + "." + dMonths % 12;
document.getElementById('txtStudyYears').value = dYears;
}
}
What is the difference between a strongly typed language and a statically typed language?
Data Coercion does not necessarily mean weakly typed because sometimes its syntacical sugar:
The example above of Java being weakly typed because of
String s = "abc" + 123;
Is not weakly typed example because its really doing:
String s = "abc" + new Integer(123).toString()
Data coercion is also not weakly typed if you are constructing a new object.
Java is a very bad example of weakly typed (and any language that has good reflection will most likely not be weakly typed). Because the runtime of the language always knows what the type is (the exception might be native types).
This is unlike C. C is the one of the best examples of weakly typed. The runtime has no idea if 4 bytes is an integer, a struct, a pointer or a 4 characters.
The runtime of the language really defines whether or not its weakly typed otherwise its really just opinion.
EDIT:
After further thought this is not necessarily true as the runtime does not have to have all the types reified in the runtime system to be a Strongly Typed system.
Haskell and ML have such complete static analysis that they can potential ommit type information from the runtime.
Difference between <input type='submit' /> and <button type='submit'>text</button>
Not sure where you get your legends from but:
Submit button with <button>
As with:
<button type="submit">(html content)</button>
IE6 will submit all text for this button between the tags, other browsers will only submit the value. Using <button>
gives you more layout freedom over the design of the button. In all its intents and purposes, it seemed excellent at first, but various browser quirks make it hard to use at times.
In your example, IE6 will send text
to the server, while most other browsers will send nothing. To make it cross-browser compatible, use <button type="submit" value="text">text</button>
. Better yet: don't use the value, because if you add HTML it becomes rather tricky what is received on server side. Instead, if you must send an extra value, use a hidden field.
Button with <input>
As with:
<input type="button" />
By default, this does next to nothing. It will not even submit your form. You can only place text on the button and give it a size and a border by means of CSS. Its original (and current) intent was to execute a script without the need to submit the form to the server.
Normal submit button with <input>
As with:
<input type="submit" />
Like the former, but actually submits the surrounding form.
Image submit button with <input>
As with:
<input type="image" />
Like the former (submit), it will also submit a form, but you can use any image. This used to be the preferred way to use images as buttons when a form needed submitting. For more control, <button>
is now used. This can also be used for server side image maps but that's a rarity these days. When you use the usemap
-attribute and (with or without that attribute), the browser will send the mouse-pointer X/Y coordinates to the server (more precisely, the mouse-pointer location inside the button of the moment you click it). If you just ignore these extras, it is nothing more than a submit button disguised as an image.
There are some subtle differences between browsers, but all will submit the value-attribute, except for the <button>
tag as explained above.
CSS3 transition doesn't work with display property
Made some changes, but I think I got the effect you want using visibility
. http://jsfiddle.net/9dsGP/49/
I also made these changes:
position: absolute; /* so it doesn't expand the button background */
top: calc(1em + 8px); /* so it's under the "button" */
left:8px; /* so it's shifted by padding-left */
width: 182px; /* so it fits nicely under the button, width - padding-left - padding-right - border-left-width - border-right-width, 200 - 8 - 8 - 1 - 1 = 182 */
Alternatively, you could put .content as a sibling of .button, but I didn't make an example for this.
How can I get System variable value in Java?
Actually the variable can be set or not, so, In Java 8 or superior its nullable value should be wrapped into an Optional
object, which allows really good features. In the following example we gonna try to obtain the variable ENV_VAR1
, if it doesnt exist we may throw some custom Exception to alert about it:
String ENV_VAR1 = Optional.ofNullable(System.getenv("ENV_VAR1")).orElseThrow(
() -> new CustomException("ENV_VAR1 is not set in the environment"));
How to escape indicator characters (i.e. : or - ) in YAML
I came here trying to get my Azure DevOps Command Line task working. The thing that worked for me was using the pipe (|
) character. Using >
did not work.
Example:
steps:
- task: CmdLine@2
inputs:
script: |
echo "Selecting Mono version..."
/bin/bash -c "sudo $AGENT_HOMEDIRECTORY/scripts/select-xamarin-sdk.sh 5_18_1"
echo "Selecting Xcode version..."
/bin/bash -c "echo '##vso[task.setvariable variable=MD_APPLE_SDK_ROOT;]'/Applications/Xcode_10.2.1.app;sudo xcode-select --switch /Applications/Xcode_10.2.1.app/Contents/Developer"
Removing html5 required attribute with jQuery
If you want to set required to true
$(document).ready(function(){
$('#edit-submitted-first-name').prop('required',true);
});
if you want to set required to false
$(document).ready(function(){
$('#edit-submitted-first-name').prop('required',false);
});
NSDate get year/month/day
If you are targeting iOS 8+ you can use the new NSCalendar
convenience methods to achieve this in a more terse format.
First create an NSCalendar
and use whatever NSDate
is required.
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [NSDate date];
You could extract components individually via component:fromDate:
NSInteger year = [calendar component:NSCalendarUnitYear fromDate:date];
NSInteger month = [calendar component:NSCalendarUnitMonth fromDate:date];
NSInteger day = [calendar component:NSCalendarUnitDay fromDate:date];
Or, even more succinctly, use NSInteger
pointers via getEra:year:month:day:fromDate:
NSInteger year, month, day;
[calendar getEra:nil year:&year month:&month day:&day fromDate:date];
For more information and examples check out NSDate Manipulation Made Easy in iOS 8. Disclaimer, I wrote the post.
how to convert integer to string?
If you really want to use String:
NSString *number = [[NSString alloc] initWithFormat:@"%d", 123];
But I would recommend using NSNumber:
NSNumber *number = [[NSNumber alloc] initWithInt:123];
Then just add it to the array.
[array addObject:number];
Don't forget to release it after that, since you created it above.
[number release];
Save and load weights in keras
Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model
There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.
First, the reason you're receiving the error is because you're calling load_model
incorrectly.
To save and load the weights of the model, you would first use
model.save_weights('my_model_weights.h5')
to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights
on the model, as in
model.load_weights('my_model_weights.h5')
Another saving technique is model.save(filepath)
. This save
function saves:
- The architecture of the model, allowing to re-create the model.
- The weights of the model.
- The training configuration (loss, optimizer).
- The state of the optimizer, allowing to resume training exactly where you left off.
To load this saved model, you would use the following:
from keras.models import load_model
new_model = load_model(filepath)'
Lastly, model.to_json()
, saves only the architecture of the model. To load the architecture, you would use
from keras.models import model_from_json
model = model_from_json(json_string)
Turning off auto indent when pasting text into vim
Native paste / bracketed paste is the best and simplest way since vim 8
(released in 2016). It even works over ssh! (Bracketed paste works on Linux and Mac, but not Windows Git Bash)
Make sure you have vim 8+ (you don't need the +clipboard
or +xterm_clipboard
options).
vim --version | head -1
Simply use the OS native paste command (e.g. ctrl+shift+V
or cmd+V
) in Normal Mode. Do not press i
for Insert Mode.
Test
Copy (ctrl+shift+C
or cmd+C
) the output of this (2 lines with a tab indent) to the system clipboard:
echo -e '\ta\n\tb'
Launch a clean vim 8+ with autoindent:
vim -u NONE --noplugin -c 'set autoindent'
Paste from the system clipboard (ctrl+shift+V
or cmd+V
) in Normal Mode. Do not press i
for Insert Mode. The a
and b
should be aligned with a single tab indent. You can even do this while ssh-ing to a remote machine (the remote machine will need vim 8+).
Now try the old way, which will autoindent the second line with an extra tab: Press i
for Insert Mode. Then paste using ctrl+shift+V
or cmd+V
. The a
and b
are misaligned now.
Installing Vim 8
Visual Studio 2017 errors on standard headers
I upgraded VS2017 from version 15.2 to 15.8. With version 15.8 here's what happened:
Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0 no longer worked for me! I had to change it to 10.0.17134.0 and then everything built again. After the upgrade and without making this change, I was getting the same header file errors.
I would have submitted this as a comment on one of the other answers but I don't have enough reputation yet.
What is the yield keyword used for in C#?
The yield
keyword actually does quite a lot here.
The function returns an object that implements the IEnumerable<object>
interface. If a calling function starts foreach
ing over this object, the function is called again until it "yields". This is syntactic sugar introduced in C# 2.0. In earlier versions you had to create your own IEnumerable
and IEnumerator
objects to do stuff like this.
The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:
public void Consumer()
{
foreach(int i in Integers())
{
Console.WriteLine(i.ToString());
}
}
public IEnumerable<int> Integers()
{
yield return 1;
yield return 2;
yield return 4;
yield return 8;
yield return 16;
yield return 16777216;
}
When you step through the example, you'll find the first call to Integers()
returns 1
. The second call returns 2
and the line yield return 1
is not executed again.
Here is a real-life example:
public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms)
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(CommandType.Text, sql, connection, parms))
{
command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return make(reader);
}
}
}
}
}
NoClassDefFoundError for code in an Java library on Android
Solutions:
- List item
- Check Exports Order
- Enable Multi Dex
- Check api level of views in layout. I faced same problem with searchView. I have check api level while adding searchview but added implements SearchView.OnQueryTextListener to class file.
How do you clear Apache Maven's cache?
So there are some commands which you can use for cleaning
1. mvn clean cache
2. mvn clean install
3. mvn clean install -Pclean-database
also deleting repository folder from .m2 can help.
How do I merge two dictionaries in a single expression (taking union of dictionaries)?
A hacky one-liner for 2.5+ :
>>> a = dict(x=2, y=3)
>>> b = dict(y=4, z=5)
>>> c = 'No Effect' if a.update(b) else a
>>> c
{'x': 2, 'y': 4, 'z': 5}
Things to keep in mind:
dict.update
modifies the dict
in-place, hence it evaluates to None
- In expression
A if C else B
, C
is evaluated first. See here
So here, a.update(b)
is evaluated first, a
gets updated with b
and operation results in None
, thus the expression will always return the value given in the else
condition, i.e. a
. Since, a
is already modified, it will return the new value of a
, which is the updated dict.
IMPROVEMENT
This can be further improved, and it be made to work for even older versions (probably python 1.0 as well?):
>>> c = a.update(b) or a
Here also, the first part produces None
, hence it always returns the second part, but as the update operation is already done, it always returns the updated dict.
CRITIQUE
- Both the solution modify the value of
a
, so if one wants to keep both the input dictionaries unchanged, this is not a good idea.
IMPROVEMENT
If copy of a
is needed, the second one can be slightly modified:
>>> a = dict(x=2, y=3)
>>> b = dict(y=4, z=5)
>>> a, c = a.copy(), a.update(b) or a
>>> c
{'x': 2, 'y': 4, 'z': 5}
>>> d = dict(m=10, n=11)
>>> a, c = a.copy(), a.update(b) or a.update(d) or a
>>> c
{'x': 2, 'y': 4, 'z': 5, 'm': 10, 'n': 11}
>>> a
{'x': 2, 'y': 4}
CAVEATS
- It (especially the first one) gets ugly and impractical for any number of dicts greater than 2
- Furthermore, this is not explicit, which is un-pythonic.
Even though these solutions are extremely fast, especially the or
method which is probably faster than the new python 3.9 union operator (not entirely sure, further testing required, if anyone wants to add it afterwards, they are welcome), I would not recommend these methods due to the abovementioned reasons.
Added it for the sake of completeness.
How can I order a List<string>?
ListaServizi.Sort();
Will do that for you. It's straightforward enough with a list of strings. You need to be a little cleverer if sorting objects.
How do I add images in laravel view?
normaly is better image store in public folder (because it has write permission already that you can use when I upload images to it)
public
upload_media
photos
image.png
$image = public_path() . '/upload_media/photos/image.png'; // destination path
view PHP
<img src="<?= $image ?>">
View blade
<img src="{{ $image }}">
How to handle floats and decimal separators with html5 input type number
When you call $("#my_input").val();
it returns as string variable. So use parseFloat
and parseInt
for converting.
When you use parseFloat
your desktop or phone ITSELF understands the meaning of variable.
And plus you can convert a float to string by using toFixed
which has an argument the count of digits as below:
var i = 0.011;
var ss = i.toFixed(2); //It returns 0.01
How to map calculated properties with JPA and Hibernate
JPA doesn't offer any support for derived property so you'll have to use a provider specific extension. As you mentioned, @Formula
is perfect for this when using Hibernate. You can use an SQL fragment:
@Formula("PRICE*1.155")
private float finalPrice;
Or even complex queries on other tables:
@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
private Date firstOrderDate;
Where id
is the id
of the current entity.
The following blog post is worth the read: Hibernate Derived Properties - Performance and Portability.
Without more details, I can't give a more precise answer but the above link should be helpful.
See also:
Remove rows not .isin('X')
You can use the DataFrame.select
method:
In [1]: df = pd.DataFrame([[1,2],[3,4]], index=['A','B'])
In [2]: df
Out[2]:
0 1
A 1 2
B 3 4
In [3]: L = ['A']
In [4]: df.select(lambda x: x in L)
Out[4]:
0 1
A 1 2
PHP 5.4 Call-time pass-by-reference - Easy fix available?
You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.
From the documentation:
There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use &
in foo(&$a);
.
For example, instead of using:
// Wrong way!
myFunc(&$arg); # Deprecated pass-by-reference argument
function myFunc($arg) { }
Use:
// Right way!
myFunc($var); # pass-by-value argument
function myFunc(&$arg) { }
How to read a specific line using the specific line number from a file in Java?
Not that I know of, but what you could do is loop through the first 31 lines doing nothing using the readline() function of BufferedReader
FileInputStream fs= new FileInputStream("someFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
for(int i = 0; i < 31; ++i)
br.readLine();
String lineIWant = br.readLine();
Clear text area
I just tried using this code and @psynnott's answer was correct though I needed to know it would work repeatedly, seems to work with jquery 1.7.1 >
I modified the jfiddle to the following
http://jsfiddle.net/Rjj9v/109/
$('#mytext').text('');
This is not a new answer @psynnott is correct I am just providing a more concise example that shows the textarea is still working after the clear because if you use .val("") the text area stops working
Get difference between two lists
You can cycle through the first list and, for every item that isn't in the second list but is in the first list, add it to the third list. E.g:
temp3 = []
for i in temp1:
if i not in temp2:
temp3.append(i)
print(temp3)
Why is AJAX returning HTTP status code 0?
For me, the problem was caused by the hosting company (Godaddy) treating POST operations which had substantial response data (anything more than tens of kilobytes) as some sort of security threat. If more than 6 of these occurred in one minute, the host refused to execute the PHP code that responded to the POST request during the next minute. I'm not entirely sure what the host did instead, but I did see, with tcpdump, a TCP reset packet coming as the response to a POST request from the browser. This caused the http status code returned in a jqXHR object to be 0.
Changing the operations from POST to GET fixed the problem. It's not clear why Godaddy impose this limit, but changing the code was easier than changing the host.
JFrame.dispose() vs System.exit()
JFrame.dispose() affects only to this frame (release all of the native screen resources used by this component, its subcomponents, and all children). System.exit() affects to entire JVM.
If you want to close all JFrame or all Window (since Frames extend Windows) to terminate the application in an ordered mode, you can do some like this:
Arrays.asList(Window.getWindows()).forEach(e -> e.dispose()); // or JFrame.getFrames()
How can I parse a YAML file from a Linux shell script?
Whenever you need a solution for "How to work with YAML/JSON/compatible data from a shell script" which works on just about every OS with Python (*nix, OSX, Windows), consider yamlpath, which provides several command-line tools for reading, writing, searching, and merging YAML, EYAML, JSON, and compatible files. Since just about every OS either comes with Python pre-installed or it is trivial to install, this makes yamlpath highly portable. Even more interesting: this project defines an intuitive path language with very powerful, command-line-friendly syntax that enables accessing one or more nodes.
To your specific question and after installing yamlpath using Python's native package manager or your OS's package manager (yamlpath is available via RPM to some OSes):
#!/bin/bash
# Read values directly from YAML (or EYAML, JSON, etc) for use in this shell script:
myShellVar=$(yaml-get --query=any.path.no[matter%how].complex source-file.yaml)
# Use the value any way you need:
echo "Retrieved ${myShellVar}"
# Perhaps change the value and write it back:
myShellVar="New Value"
yaml-set --change=/any/path/no[matter%how]/complex --value="$myShellVar" source-file.yaml
You didn't specify that the data was a simple Scalar value though, so let's up the ante. What if the result you want is an Array? Even more challenging, what if it's an Array-of-Hashes and you only want one property of each result? Suppose further that your data is actually spread out across multiple YAML files and you need all the results in a single query. That's a much more interesting question to demonstrate with. So, suppose you have these two YAML files:
File: data1.yaml
---
baubles:
- name: Doohickey
sku: 0-000-1
price: 4.75
weight: 2.7g
- name: Doodad
sku: 0-000-2
price: 10.5
weight: 5g
- name: Oddball
sku: 0-000-3
price: 25.99
weight: 25kg
File: data2.yaml
---
baubles:
- name: Fob
sku: 0-000-4
price: 0.99
weight: 18mg
- name: Doohickey
price: 10.5
- name: Oddball
sku: 0-000-3
description: This ball is odd
How would you report only the sku
of every item in inventory after applying the changes from data2.yaml to data1.yaml, all from a shell script? Try this:
#!/bin/bash
baubleSKUs=($(yaml-merge --aoh=deep data1.yaml data2.yaml | yaml-get --query=/baubles/sku -))
for sku in "${baubleSKUs[@]}"; do
echo "Found bauble SKU: ${sku}"
done
You get exactly what you need from only a few lines of code:
Found bauble SKU: 0-000-1
Found bauble SKU: 0-000-2
Found bauble SKU: 0-000-3
Found bauble SKU: 0-000-4
As you can see, yamlpath turns very complex problems into trivial solutions. Note that the entire query was handled as a stream; no YAML files were changed by the query and there were no temp files.
I realize this is "yet another tool to solve the same question" but after reading the other answers here, yamlpath appears more portable and robust than most alternatives. It also fully understands YAML/JSON/compatible files and it does not need to convert YAML to JSON to perform requested operations. As such, comments within the original YAML file are preserved whenever you need to change data in the source YAML file. Like some alternatives, yamlpath is also portable across OSes. More importantly, yamlpath defines a query language that is extremely powerful, enabling very specialized/filtered data queries. It can even operate against results from disparate parts of the file in a single query.
If you want to get or set many values in the data at once -- including complex data like hashes/arrays/maps/lists -- yamlpath can do that. Want a value but don't know precisely where it is in the document? yamlpath can find it and give you the exact path(s). Need to merge multiple data file together, including from STDIN? yamlpath does that, too. Further, yamlpath fully comprehends YAML anchors and their aliases, always giving or changing exactly the data you expect whether it is a concrete or referenced value.
Disclaimer: I wrote and maintain yamlpath, which is based on ruamel.yaml, which is in turn based on PyYAML. As such, yamlpath is fully standards-compliant.
How to generate UML diagrams (especially sequence diagrams) from Java code?
Using IntelliJ IDEA. To generate class diagram select package and press Ctrl + Alt + U:
By default, it displays only class names and not all dependencies. To change it: right click -> Show Categories... and Show dependencies:
To genarate dependencies diagram (UML Deployment diagram) and you use maven go View -> Tool Windows -> Maven Projects and press Ctrl + Alt + U:
The result:
Also it is possible to generate more others diagrams. See documentation.
ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired
I had this error happen when I had 2 scripts I was running. I had:
- A SQL*Plus session connected directly using a schema user account (account #1)
- Another SQL*Plus session connected using a different schema user account (account #2), but connecting across a database link as the first account
I ran a table drop, then table creation as account #1.
I ran a table update on account #2's session. Did not commit changes.
Re-ran table drop/creation script as account #1. Got error on the drop table x
command.
I solved it by running COMMIT;
in the SQL*Plus session of account #2.
jquery-ui-dialog - How to hook into dialog close event
I have found it!
You can catch the close event using the following code:
$('div#popup_content').on('dialogclose', function(event) {
alert('closed');
});
Obviously I can replace the alert with whatever I need to do.
Edit: As of Jquery 1.7, the bind() has become on()
Split a string by a delimiter in python
You may be interested in the csv
module, which is designed for comma-separated files but can be easily modified to use a custom delimiter.
import csv
csv.register_dialect( "myDialect", delimiter = "__", <other-options> )
lines = [ "MATCHES__STRING" ]
for row in csv.reader( lines ):
...
Convert string to binary then back again using PHP
I would most definitely recommend using the built in standard password libraries that come with PHP - Here is a good example on how to use them.
For those coming here to figure out how to go from Binary Strings to Decimals and back, there are some good examples below.
For converting binary "strings" to decimals/chars you can do something like this...
echo bindec("00000001") . "\n";
echo bindec("00000010") . "\n";
echo bindec("00000100") . "\n";
echo bindec("00001000") . "\n";
echo bindec("00010000") . "\n";
echo bindec("00100000") . "\n";
echo bindec("01000000") . "\n";
echo bindec("10000000") . "\n";
echo bindec("01000001") . "\n";
# big binary string
echo bindec("111010110111011110000110001")."\n";
The above outputs:
1
2
4
8
16
32
64
128
65
123452465
For converting decimals to char/strings you can do this:
# convert to binary strings "00000001"
echo decbin(1) . "\n";
echo decbin(2) . "\n";
echo decbin(4) . "\n";
echo decbin(8) . "\n";
echo decbin(16) . "\n";
echo decbin(32) . "\n";
echo decbin(64) . "\n";
echo decbin(128) . "\n";
# convert a ascii character
echo str_pad(decbin(65), 8, 0, STR_PAD_LEFT) ."\n";
# convert a 'char'
echo str_pad(decbin(ord('A')), 8, 0, STR_PAD_LEFT) ."\n";
# big number...
echo str_pad(decbin(65535), 8, 0, STR_PAD_LEFT) ."\n";
echo str_pad(decbin(123452465), 8, 0, STR_PAD_LEFT) ."\n";
The above outputs:
1
10
100
1000
10000
100000
1000000
10000000
01000001
01000001
1111111111111111
111010110111011110000110001
Stacked Bar Plot in R
I'm obviosly not a very good R coder, but if you wanted to do this with ggplot2:
data<- rbind(c(480, 780, 431, 295, 670, 360, 190),
c(720, 350, 377, 255, 340, 615, 345),
c(460, 480, 179, 560, 60, 735, 1260),
c(220, 240, 876, 789, 820, 100, 75))
a <- cbind(data[, 1], 1, c(1:4))
b <- cbind(data[, 2], 2, c(1:4))
c <- cbind(data[, 3], 3, c(1:4))
d <- cbind(data[, 4], 4, c(1:4))
e <- cbind(data[, 5], 5, c(1:4))
f <- cbind(data[, 6], 6, c(1:4))
g <- cbind(data[, 7], 7, c(1:4))
data <- as.data.frame(rbind(a, b, c, d, e, f, g))
colnames(data) <-c("Time", "Type", "Group")
data$Type <- factor(data$Type, labels = c("A", "B", "C", "D", "E", "F", "G"))
library(ggplot2)
ggplot(data = data, aes(x = Type, y = Time, fill = Group)) +
geom_bar(stat = "identity") +
opts(legend.position = "none")
How do I center a Bootstrap div with a 'spanX' class?
Update
As of BS3 there's a .center-block
helper class. From the docs:
// Classes
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
// Usage as mixins
.element {
.center-block();
}
There is hidden complexity in this seemingly simple problem. All the answers given have some issues.
1. Create a Custom Class (Major Gotcha)
Create .col-centred
class, but there is a major gotcha.
.col-centred {
float: none !important;
margin: 0 auto;
}
<!-- Bootstrap 3 -->
<div class="col-lg-6 col-centred">
Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 col-centred">
Centred content.
</div>
The Gotcha
Bootstrap requires columns add up to 12. If they do not they will overlap, which is a problem. In this case the centred column will overlap the column above it. Visually the page may look the same, but mouse events will not work on the column being overlapped (you can't hover or click links, for example). This is because mouse events are registering on the centred column that's overlapping the elements you try to click.
The Fixes
You can resolve this issue by using a clearfix
element. Using z-index
to bring the centred column to the bottom will not work because it will be overlapped itself, and consequently mouse events will work on it.
<div class="row">
<div class="col-lg-12">
I get overlapped by `col-lg-7 centered` unless there's a clearfix.
</div>
<div class="clearfix"></div>
<div class="col-lg-7 centred">
</div>
</div>
Or you can isolate the centred column in its own row.
<div class="row">
<div class="col-lg-12">
</div>
</div>
<div class="row">
<div class="col-lg-7 centred">
Look I am in my own row.
</div>
</div>
2. Use col-lg-offset-x or spanx-offset (Major Gotcha)
<!-- Bootstrap 3 -->
<div class="col-lg-6 col-lg-offset-3">
Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 span-offset-3">
Centred content.
</div>
The first problem is that your centred column must be an even number because the offset value must divide evenly by 2 for the layout to be centered (left/right).
Secondly, as some have commented, using offsets is a bad idea. This is because when the browser resizes the offset will turn into blank space, pushing the actual content down the page.
3. Create an Inner Centred Column
This is the best solution in my opinion. No hacking required and you don't mess around with the grid, which could cause unintended consequences, as per solutions 1 and 2.
.col-centred {
margin: 0 auto;
}
<div class="row">
<div class="col-lg-12">
<div class="centred">
Look I am in my own row.
</div>
</div>
</div>
Changing the "tick frequency" on x or y axis in matplotlib?
You could explicitly set where you want to tick marks with plt.xticks
:
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
For example,
import numpy as np
import matplotlib.pyplot as plt
x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
plt.show()
(np.arange
was used rather than Python's range
function just in case min(x)
and max(x)
are floats instead of ints.)
The plt.plot
(or ax.plot
) function will automatically set default x
and y
limits. If you wish to keep those limits, and just change the stepsize of the tick marks, then you could use ax.get_xlim()
to discover what limits Matplotlib has already set.
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, stepsize))
The default tick formatter should do a decent job rounding the tick values to a sensible number of significant digits. However, if you wish to have more control over the format, you can define your own formatter. For example,
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
Here's a runnable example:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, 0.712123))
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
plt.show()
What is the difference between print and puts?
print
outputs each argument, followed by $,
, to $stdout
, followed by $\
. It is equivalent to args.join($,) + $\
puts
sets both $,
and $\
to "\n" and then does the same thing as print
. The key difference being that each argument is a new line with puts
.
You can require 'english'
to access those global variables with user-friendly names.
How do I add a newline using printf?
Try this:
printf '\n%s\n' 'I want this on a new line!'
That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.
quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f %s\n' "$quantity" "$price" "$description"
38 142.15 advanced widget
No module named _sqlite3
My _sqlite3.so is in /usr/lib/python2.5/lib-dynload/_sqlite3.so. Judging from your paths, you should have the file /usr/local/lib/python2.5/lib-dynload/_sqlite3.so.
Try the following:
find /usr/local -name _sqlite3.so
If the file isn't found, something may be wrong with your Python installation. If it is, make sure the path it's installed to is in the Python path. In the Python shell,
import sys
print sys.path
In my case, /usr/lib/python2.5/lib-dynload is in the list, so it's able to find /usr/lib/python2.5/lib-dynload/_sqlite3.so.
Powershell import-module doesn't find modules
My finding with PS 5.0 on Windows 7: $ENV:PsModulePath
has to end with a . This normally means it will load all modules in that path.
I'm not able to add a single module to $env:PsModulePath and get it to load with Import-Module ExampleModule
. I have to use the full path to the module. e.g. C:\MyModules\ExampleModule
. I am sure it used to work.
For example:
Say I have the modules:
C:\MyModules\ExampleModule
C:\MyModules\FishingModule
I need to add C:\MyModules\
to $env:PsModulePath
, which will allow me to do
Import-Module ExampleModule
Import-Module FishingModule
If for some reason, I didn't want FishingModule
, I thought I could add C:\MyModules\ExampleModule
only (no trailing \), but this doesn't seem to work now. To load it, I have to Import-Module C:\MyModules\ExampleModule
Interestingly, in both cases, doing Get-Module -ListAvailable
, shows the modules, but it won't import. Although, the module's cmdlets seem to work anyway.
AFAIK, to get the automatic import to work, one has to add the name of the function to FunctionsToExport in the manifest (.psd1) file. Adding FunctionsToExport = '*'
, breaks the auto load. You can still have Export-ModuleMember -Function *
in the module file (.psm1).
These are my findings. Whether there's been a change or my computer is broken, remains to be seen. HTH
Change color of bootstrap navbar on hover link?
This is cleaner:
ul.nav a:hover { color: #fff !important; }
There's no need to get more specific than this. Unfortunately, the !important
is necessary in this instance.
I also added :focus
and :active
to the same declaration for accessibility reasons and for smartphone/tablet/touchscreen users.
Is there a naming convention for MySQL?
Consistency is the key to any naming standard. As long as it's logical and consistent, you're 99% there.
The standard itself is very much personal preference - so if you like your standard, then run with it.
To answer your question outright - no, MySQL doesn't have a preferred naming convention/standard, so rolling your own is fine (and yours seems logical).
Command to run a .bat file
There are many possibilities to solve this task.
1. RUN the batch file with full path
The easiest solution is running the batch file with full path.
"F:\- Big Packets -\kitterengine\Common\Template.bat"
Once end of batch file Template.bat
is reached, there is no return to previous script in case of the command line above is within a *.bat or *.cmd file.
The current directory for the batch file Template.bat
is the current directory of the current process. In case of Template.bat
requires that the directory of this batch file is the current directory, the batch file Template.bat
should contain after @echo off
as second line the following command line:
cd /D "%~dp0"
Run in a command prompt window cd /?
for getting displayed the help of this command explaining parameter /D
... change to specified directory also on a different drive.
Run in a command prompt window call /?
for getting displayed the help of this command used also in 2., 4. and 5. solution and explaining also %~dp0
... drive and path of argument 0 which is the name of the batch file.
2. CALL the batch file with full path
Another solution is calling the batch file with full path.
call "F:\- Big Packets -\kitterengine\Common\Template.bat"
The difference to first solution is that after end of batch file Template.bat
is reached the batch processing continues in batch script containing this command line.
For the current directory read above.
3. Change directory and RUN batch file with one command line
There are 3 operators for running multiple commands on one command line: &
, &&
and ||
.
For details see answer on Single line with multiple commands using Windows batch file
I suggest for this task the &&
operator.
cd /D "F:\- Big Packets -\kitterengine\Common" && Template.bat
As on first solution there is no return to current script if this is a *.bat or *.cmd file and changing the directory and continuation of batch processing on Template.bat
is successful.
4. Change directory and CALL batch file with one command line
This command line changes the directory and on success calls the batch file.
cd /D "F:\- Big Packets -\kitterengine\Common" && call Template.bat
The difference to third solution is the return to current batch script on exiting processing of Template.bat
.
5. Change directory and CALL batch file with keeping current environment with one command line
The four solutions above change the current directory and it is unknown what Template.bat
does regarding
- current directory
- environment variables
- command extensions state
- delayed expansion state
In case of it is important to keep the environment of current *.bat or *.cmd script unmodified by whatever Template.bat
changes on environment for itself, it is advisable to use setlocal
and endlocal
.
Run in a command prompt window setlocal /?
and endlocal /?
for getting displayed the help of these two commands. And read answer on change directory command cd ..not working in batch file after npm install explaining more detailed what these two commands do.
setlocal & cd /D "F:\- Big Packets -\kitterengine\Common" & call Template.bat & endlocal
Now there is only &
instead of &&
used as it is important here that after setlocal
is executed the command endlocal
is finally also executed.
ONE MORE NOTE
If batch file Template.bat
contains the command exit
without parameter /B
and this command is really executed, the command process is always exited independent on calling hierarchy. So make sure Template.bat
contains exit /B
or goto :EOF
instead of just exit
if there is exit
used at all in this batch file.
Checking if a variable is initialized
You could reference the variable in an assertion and then build with -fsanitize=address
:
void foo (int32_t& i) {
// Assertion will trigger address sanitizer if not initialized:
assert(static_cast<int64_t>(i) != INT64_MAX);
}
This will cause the program to reliably crash with a stack trace (as opposed to undefined behavior).
c# how to add byte to byte array
You can't do that. It's not possible to resize an array. You have to create a new array and copy the data to it:
bArray = addByteToArray(bArray, newByte);
code:
public byte[] addByteToArray(byte[] bArray, byte newByte)
{
byte[] newArray = new byte[bArray.Length + 1];
bArray.CopyTo(newArray, 1);
newArray[0] = newByte;
return newArray;
}
Best way to create enum of strings?
Either set the enum name to be the same as the string you want or, more generally,you can associate arbitrary attributes with your enum values:
enum Strings {
STRING_ONE("ONE"), STRING_TWO("TWO");
private final String stringValue;
Strings(final String s) { stringValue = s; }
public String toString() { return stringValue; }
// further methods, attributes, etc.
}
It's important to have the constants at the top, and the methods/attributes at the bottom.
Detect whether current Windows version is 32 bit or 64 bit
The best way is surely just to check whether there are two program files directories, 'Program Files'and 'Program Files (x86)'
The advantage of this method is you can do it when the o/s is not running, for instance if the machine has failed to start and you wish to reinstall the operating system
Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)
I am amazed to see so many string replace ideas of UUID. How about this:
UUID temp = UUID.randomUUID();
String uuidString = Long.toHexString(temp.getMostSignificantBits())
+ Long.toHexString(temp.getLeastSignificantBits());
This is the fasted way of doing it since the whole toString() of UUID is already more expensive not to mention the regular expression which has to be parsed and executed or the replacing with empty string.
Google MAP API v3: Center & Zoom on displayed markers
I've also find this fix that zooms to fit all markers
LatLngList: an array of instances of latLng, for example:
// "map" is an instance of GMap3
var LatLngList = [
new google.maps.LatLng (52.537,-2.061),
new google.maps.LatLng (52.564,-2.017)
],
latlngbounds = new google.maps.LatLngBounds();
LatLngList.forEach(function(latLng){
latlngbounds.extend(latLng);
});
// or with ES6:
// for( var latLng of LatLngList)
// latlngbounds.extend(latLng);
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
What are projection and selection?
Projections and Selections are two unary operations in Relational Algebra and has practical applications in RDBMS (relational database management systems).
In practical sense, yes Projection means selecting specific columns (attributes) from a table and Selection means filtering rows (tuples). Also, for a conventional table, Projection and Selection can be termed as vertical and horizontal slicing or filtering.
Wikipedia provides more formal definitions of these with examples and they can be good for further reading on relational algebra:
What does Visual Studio mean by normalize inconsistent line endings?
The file you are editing has been edited with some other editor that does not use the same line endings, resulting in a file with mixed line endings.
The ASCII characters in use for line endings are:
CR, Carriage Return
LF, Line Feed
Windows = CRLF
Mac OS 9 or earlier = CR
Unix = LF
Java, return if trimmed String in List contains String
You can do it in a single line by using regex:
if (myList.toString().matches(".*\\bA\\b.*"))
This code should perform quite well.
BTW, you could build the regex from a variable, like this:
.matches("\\[.*\\b" + word + "\\b.*]")
I added [
and ]
to each end to prevent a false positive match when the search term contains an open/close square bracket at the start/end.
How is AngularJS different from jQuery
I think this is a very good chart describing the differences in short. A quick glance at it shows most of the differences.
One thing I would like to add is that, AngularJS can be made to follow the MVVM design pattern while jQuery does not follow any of the standard Object Oriented patterns.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined
Just another possibility:
Spring initializes bean by type not by name if you don't define bean with a name, which is ok if you use it by its type:
Producer:
@Service
public void FooServiceImpl implements FooService{}
Consumer:
@Autowired
private FooService fooService;
or
@Autowired
private void setFooService(FooService fooService) {}
but not ok if you use it by name:
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("fooService");
It would complain: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'fooService' is defined
In this case, assigning name to @Service("fooService")
would make it work.
jQuery select change event get selected option
You can use this jquery select change event for get selected option value
For Demo
_x000D_
_x000D_
$(document).ready(function () { _x000D_
$('body').on('change','#select', function() {_x000D_
$('#show_selected').val(this.value);_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html> _x000D_
<html> _x000D_
<title>Learn Jquery value Method</title>_x000D_
<head> _x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> _x000D_
</head> _x000D_
<body> _x000D_
<select id="select">_x000D_
<option value="">Select One</option>_x000D_
<option value="PHP">PHP</option>_x000D_
<option value="jAVA">JAVA</option>_x000D_
<option value="Jquery">jQuery</option>_x000D_
<option value="Python">Python</option>_x000D_
<option value="Mysql">Mysql</option>_x000D_
</select>_x000D_
<br><br> _x000D_
<input type="text" id="show_selected">_x000D_
</body> _x000D_
</html>
_x000D_
_x000D_
_x000D_
Parsing JSON from XmlHttpRequest.responseJSON
New ways I: fetch
TL;DR I'd recommend this way as long as you don't have to send synchronous requests or support old browsers.
A long as your request is asynchronous you can use the Fetch API to send HTTP requests. The fetch API works with promises, which is a nice way to handle asynchronous workflows in JavaScript. With this approach you use fetch()
to send a request and ResponseBody.json()
to parse the response:
fetch(url)
.then(function(response) {
return response.json();
})
.then(function(jsonResponse) {
// do something with jsonResponse
});
Compatibility: The Fetch API is not supported by IE11 as well as Edge 12 & 13. However, there are polyfills.
New ways II: responseType
As Londeren has written in his answer, newer browsers allow you to use the responseType
property to define the expected format of the response. The parsed response data can then be accessed via the response
property:
var req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', url, true);
req.onload = function() {
var jsonResponse = req.response;
// do something with jsonResponse
};
req.send(null);
Compatibility: responseType = 'json'
is not supported by IE11.
The classic way
The standard XMLHttpRequest has no responseJSON
property, just responseText
and responseXML
. As long as bitly really responds with some JSON to your request, responseText
should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse()
:
var req = new XMLHttpRequest();
req.overrideMimeType("application/json");
req.open('GET', url, true);
req.onload = function() {
var jsonResponse = JSON.parse(req.responseText);
// do something with jsonResponse
};
req.send(null);
Compatibility: This approach should work with any browser that supports XMLHttpRequest
and JSON
.
JSONHttpRequest
If you prefer to use responseJSON
, but want a more lightweight solution than JQuery, you might want to check out my JSONHttpRequest. It works exactly like a normal XMLHttpRequest, but also provides the responseJSON
property. All you have to change in your code would be the first line:
var req = new JSONHttpRequest();
JSONHttpRequest also provides functionality to easily send JavaScript objects as JSON. More details and the code can be found here: http://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/.
Full disclosure: I'm the owner of Pixels|Bytes. I thought that my script was a good solution for the original question, but it is rather outdated today. I do not recommend to use it anymore.
Call a PHP function after onClick HTML event
<div id="sample"></div>
<form>
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="[email protected]" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input type="submit" name="submit" id= "submitButton" class="button" value="Add Contact" onClick="" />
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<script>
$(document).ready(function(){
$("#submitButton").click(function(){
$("#sample").load(filenameofyourfunction?the the variable you need);
});
});
</script>
Eclipse can't find / load main class
I solved this error by closing the project, removing it from eclipse and then importing it again.
Might be a little simpler than to redo the whole workspace setup.
Find duplicate lines in a file and count how many time each line was duplicated?
This will print duplicate lines only, with counts:
sort FILE | uniq -cd
or, with GNU long options (on Linux):
sort FILE | uniq --count --repeated
on BSD and OSX you have to use grep to filter out unique lines:
sort FILE | uniq -c | grep -v '^ *1 '
For the given example, the result would be:
3 123
2 234
If you want to print counts for all lines including those that appear only once:
sort FILE | uniq -c
or, with GNU long options (on Linux):
sort FILE | uniq --count
For the given input, the output is:
3 123
2 234
1 345
In order to sort the output with the most frequent lines on top, you can do the following (to get all results):
sort FILE | uniq -c | sort -nr
or, to get only duplicate lines, most frequent first:
sort FILE | uniq -cd | sort -nr
on OSX and BSD the final one becomes:
sort FILE | uniq -c | grep -v '^ *1 ' | sort -nr
PDO mysql: How to know if insert was successful
Use id as primary key with auto increment
$stmt->execute();
$insertid = $conn->lastInsertId();
incremental id is always bigger than zero even on first record so that means it will always return a true value for id coz bigger than zero means true in PHP
if ($insertid)
echo "record inserted successfully";
else
echo "record insertion failed";
What are the differences between virtual memory and physical memory?
Virtual memory is, among other things, an abstraction to give the programmer the illusion of having infinite memory available on their system.
Virtual memory mappings are made to correspond to actual physical addresses. The operating system creates and deals with these mappings - utilizing the page table, among other data structures to maintain the mappings. Virtual memory mappings are always found in the page table or some similar data structure (in case of other implementations of virtual memory, we maybe shouldn't call it the "page table"). The page table is in physical memory as well - often in kernel-reserved spaces that user programs cannot write over.
Virtual memory is typically larger than physical memory - there wouldn't be much reason for virtual memory mappings if virtual memory and physical memory were the same size.
Only the needed part of a program is resident in memory, typically - this is a topic called "paging". Virtual memory and paging are tightly related, but not the same topic. There are other implementations of virtual memory, such as segmentation.
I could be assuming wrong here, but I'd bet the things you are finding hard to wrap your head around have to do with specific implementations of virtual memory, most likely paging. There is no one way to do paging - there are many implementations and the one your textbook describes is likely not the same as the one that appears in real OSes like Linux/Windows - there are probably subtle differences.
I could blab a thousand paragraphs about paging... but I think that is better left to a different question targeting specifically that topic.
Maven project.build.directory
You can find those maven properties in the super pom.
You find the jar here:
${M2_HOME}/lib/maven-model-builder-3.0.3.jar
Open the jar with 7-zip or some other archiver (or use the jar tool).
Navigate to
org/apache/maven/model
There you'll find the pom-4.0.0.xml
.
It contains all those "short cuts":
<project>
...
<build>
<directory>${project.basedir}/target</directory>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<finalName>${project.artifactId}-${project.version}</finalName>
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>${project.basedir}/src/test/resources</directory>
</testResource>
</testResources>
...
</build>
...
</project>
Update
After some lobbying I am adding a link to the pom-4.0.0.xml
. This allows you to see the properties without opening up the local jar file.
Error handling in Bash
That's a fine solution. I just wanted to add
set -e
as a rudimentary error mechanism. It will immediately stop your script if a simple command fails. I think this should have been the default behavior: since such errors almost always signify something unexpected, it is not really 'sane' to keep executing the following commands.
Is there a command to undo git init?
remove the .git
folder in your project root folder
if you installed submodules and want to remove their git, also remove .git
from submodules folders
How to disable Excel's automatic cell reference change after copy/paste?
I found this solution which automates @Alistair Collins solution.
Basically you will change the = in any formula to * then do the paste after that you will change it back
Dim cell As Range
msgResult = MsgBox("Yes to lock" & vbNewLine & "No unlock ", vbYesNoCancel + vbQuestion, "Forumula locker")
If msgResult = vbNo Then
For Each cell In Range("A1:i155")
If InStr(1, cell.Value, "*") > 0 Then
cell.Formula = Replace(cell.Formula, "*", "=")
End If
Next cell
ElseIf msgResult = vbYes Then
For Each cell In Range("A1:i155")
If cell.HasFormula = True Then
cell.Formula = Replace(cell.Formula, "=", "*")
End If
Next cell
End If
How to TryParse for Enum value?
Enum.IsDefined will get things done. It may not be as efficient as a TryParse would probably be, but it will work without exception handling.
public static TEnum ToEnum<TEnum>(this string strEnumValue, TEnum defaultValue)
{
if (!Enum.IsDefined(typeof(TEnum), strEnumValue))
return defaultValue;
return (TEnum)Enum.Parse(typeof(TEnum), strEnumValue);
}
Worth noting: a TryParse
method was added in .NET 4.0.
How to detect if user select cancel InputBox VBA Excel
Following example uses InputBox method to validate user entry to unhide sheets:
Important thing here is to use wrap InputBox variable inside StrPtr so it could be compared to '0' when user chose to click 'x' icon on the InputBox.
Sub unhidesheet()
Dim ws As Worksheet
Dim pw As String
pw = InputBox("Enter Password to Unhide Sheets:", "Unhide Data Sheets")
If StrPtr(pw) = 0 Then
Exit Sub
ElseIf pw = NullString Then
Exit Sub
ElseIf pw = 123456 Then
For Each ws In ThisWorkbook.Worksheets
ws.Visible = xlSheetVisible
Next
End If
End Sub
How can I use/create dynamic template to compile dynamic Component with Angular 2.0?
2019 June answer
Great news! It seems that the @angular/cdk package now has first-class support for portals!
As of the time of writing, I didn't find the above official docs particularly helpful (particularly with regard to sending data into and receiving events from the dynamic components). In summary, you will need to:
Step 1) Update your AppModule
Import PortalModule
from the @angular/cdk/portal
package and register your dynamic component(s) inside entryComponents
@NgModule({
declarations: [ ..., AppComponent, MyDynamicComponent, ... ]
imports: [ ..., PortalModule, ... ],
entryComponents: [ ..., MyDynamicComponent, ... ]
})
export class AppModule { }
Step 2. Option A: If you do NOT need to pass data into and receive events from your dynamic components:
@Component({
selector: 'my-app',
template: `
<button (click)="onClickAddChild()">Click to add child component</button>
<ng-template [cdkPortalOutlet]="myPortal"></ng-template>
`
})
export class AppComponent {
myPortal: ComponentPortal<any>;
onClickAddChild() {
this.myPortal = new ComponentPortal(MyDynamicComponent);
}
}
@Component({
selector: 'app-child',
template: `<p>I am a child.</p>`
})
export class MyDynamicComponent{
}
See it in action
Step 2. Option B: If you DO need to pass data into and receive events from your dynamic components:
// A bit of boilerplate here. Recommend putting this function in a utils
// file in order to keep your component code a little cleaner.
function createDomPortalHost(elRef: ElementRef, injector: Injector) {
return new DomPortalHost(
elRef.nativeElement,
injector.get(ComponentFactoryResolver),
injector.get(ApplicationRef),
injector
);
}
@Component({
selector: 'my-app',
template: `
<button (click)="onClickAddChild()">Click to add random child component</button>
<div #portalHost></div>
`
})
export class AppComponent {
portalHost: DomPortalHost;
@ViewChild('portalHost') elRef: ElementRef;
constructor(readonly injector: Injector) {
}
ngOnInit() {
this.portalHost = createDomPortalHost(this.elRef, this.injector);
}
onClickAddChild() {
const myPortal = new ComponentPortal(MyDynamicComponent);
const componentRef = this.portalHost.attach(myPortal);
setTimeout(() => componentRef.instance.myInput
= '> This is data passed from AppComponent <', 1000);
// ... if we had an output called 'myOutput' in a child component,
// this is how we would receive events...
// this.componentRef.instance.myOutput.subscribe(() => ...);
}
}
@Component({
selector: 'app-child',
template: `<p>I am a child. <strong>{{myInput}}</strong></p>`
})
export class MyDynamicComponent {
@Input() myInput = '';
}
See it in action
How do I hide certain files from the sidebar in Visual Studio Code?
You can configure patterns to hide files and folders from the explorer and searches.
- Open VS User Settings (Main menu:
File > Preferences > Settings
). This will open the setting screen.
- Search for
files:exclude
in the search at the top.
- Configure the User Setting with new glob patterns as needed. In this case add this pattern
node_modules/
then click OK. The pattern syntax is powerful. You can find pattern matching details under the Search Across Files topic.
When you are done it should look something like this:
If you want to directly edit the settings file:
For example to hide a top level node_modules folder in your workspace:
"files.exclude": {
"node_modules/": true
}
To hide all files that start with ._
such as ._.DS_Store
files found on OSX:
"files.exclude": {
"**/._*": true
}
You also have the ability to change Workspace Settings (Main menu: File > Preferences > Workspace Settings
). Workspace settings will create a .vscode/settings.json
file in your current workspace and will only be applied to that workspace. User Settings will be applied globally to any instance of VS Code you open, but they won't override Workspace Settings if present. Read more on customizing User and Workspace Settings.
Transparent scrollbar with css
.scrollable-content {
overflow-x:hidden;
overflow-y:scroll; // manage scrollbar content overflow settings
}
.scrollable-content::-webkit-scrollbar {
width:30px; // manage scrollbar width here
}
.scrollable-content::-webkit-scrollbar * {
background:transparent; // manage scrollbar background color here
}
.scrollable-content::-webkit-scrollbar-thumb {
background:rgba(255,0,0,0.1) !important; // manage scrollbar thumb background color here
}
How to combine paths in Java?
Rather than keeping everything string-based, you should use a class which is designed to represent a file system path.
If you're using Java 7 or Java 8, you should strongly consider using java.nio.file.Path
; Path.resolve
can be used to combine one path with another, or with a string. The Paths
helper class is useful too. For example:
Path path = Paths.get("foo", "bar", "baz.txt");
If you need to cater for pre-Java-7 environments, you can use java.io.File
, like this:
File baseDirectory = new File("foo");
File subDirectory = new File(baseDirectory, "bar");
File fileInDirectory = new File(subDirectory, "baz.txt");
If you want it back as a string later, you can call getPath()
. Indeed, if you really wanted to mimic Path.Combine
, you could just write something like:
public static String combine(String path1, String path2)
{
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
Formatting a field using ToText in a Crystal Reports formula field
I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))
You can use CCur
to convert numbers or string to Curency formats. CCur(number)
or CCur(string)
I think this may be what you are looking for,
Replace (ToText(CCur({field})),"$" , "")
that will give the parentheses for negative numbers
It is a little hacky, but I'm not sure CR is very kind in the ways of formatting
Resizing UITableView to fit content
You can try Out this Custom AGTableView
To Set a TableView Height Constraint Using storyboard or programmatically. (This class automatically fetch a height constraint and set content view height to yourtableview height).
class AGTableView: UITableView {
fileprivate var heightConstraint: NSLayoutConstraint!
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
self.associateConstraints()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.associateConstraints()
}
override open func layoutSubviews() {
super.layoutSubviews()
if self.heightConstraint != nil {
self.heightConstraint.constant = self.contentSize.height
}
else{
self.sizeToFit()
print("Set a heightConstraint to Resizing UITableView to fit content")
}
}
func associateConstraints() {
// iterate through height constraints and identify
for constraint: NSLayoutConstraint in constraints {
if constraint.firstAttribute == .height {
if constraint.relation == .equal {
heightConstraint = constraint
}
}
}
}
}
Note If any problem to set a Height then yourTableView.layoutSubviews()
.
Git fetch remote branch
I typed
git checkout <branch_name>
and got
Branch <branch_name> set up to track remote branch <branch_name> from origin.
Switched to a new branch '<branch_name>'
How to declare an array of strings in C++?
#include <iostream>
#include <string>
#include <vector>
#include <boost/assign/list_of.hpp>
int main()
{
const std::vector< std::string > v = boost::assign::list_of( "abc" )( "xyz" );
std::copy(
v.begin(),
v.end(),
std::ostream_iterator< std::string >( std::cout, "\n" ) );
}
Difference between dates in JavaScript
// This is for first date
first = new Date(2010, 03, 08, 15, 30, 10); // Get the first date epoch object
document.write((first.getTime())/1000); // get the actual epoch values
second = new Date(2012, 03, 08, 15, 30, 10); // Get the first date epoch object
document.write((second.getTime())/1000); // get the actual epoch values
diff= second - first ;
one_day_epoch = 24*60*60 ; // calculating one epoch
if ( diff/ one_day_epoch > 365 ) // check , is it exceei
{
alert( 'date is exceeding one year');
}
Pass Model To Controller using Jquery/Ajax
//C# class
public class DashBoardViewModel
{
public int Id { get; set;}
public decimal TotalSales { get; set;}
public string Url { get; set;}
public string MyDate{ get; set;}
}
//JavaScript file
//Create dashboard.js file
$(document).ready(function () {
// See the html on the View below
$('.dashboardUrl').on('click', function(){
var url = $(this).attr("href");
});
$("#inpDateCompleted").change(function () {
// Construct your view model to send to the controller
// Pass viewModel to ajax function
// Date
var myDate = $('.myDate').val();
// IF YOU USE @Html.EditorFor(), the myDate is as below
var myDate = $('#MyDate').val();
var viewModel = { Id : 1, TotalSales: 50, Url: url, MyDate: myDate };
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: '/Dashboard/IndexPartial',
data: viewModel ,
success: function (data, textStatus, jqXHR) {
//Do Stuff
$("#DailyInvoiceItems").html(data.Id);
},
error: function (jqXHR, textStatus, errorThrown) {
//Do Stuff or Nothing
}
});
});
});
//ASP.NET 5 MVC 6 Controller
public class DashboardController {
[HttpGet]
public IActionResult IndexPartial(DashBoardViewModel viewModel )
{
// Do stuff with my model
var model = new DashBoardViewModel { Id = 23 /* Some more results here*/ };
return Json(model);
}
}
// MVC View
// Include jQuerylibrary
// Include dashboard.js
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/dashboard.js"></script>
// If you want to capture your URL dynamically
<div>
<a class="dashboardUrl" href ="@Url.Action("IndexPartial","Dashboard")"> LinkText </a>
</div>
<div>
<input class="myDate" type="text"/>
//OR
@Html.EditorFor(model => model.MyDate)
</div>
How can I increase the size of a bootstrap button?
Default Bootstrap size classes
You can use btn-lg
, btn-sm
and btn-xs
classes for manipulating with its size.
btn-block
Also, there is a class btn-block
which will extend your button to the whole block. It is very convenient in combination with Bootstrap grid.
For example, this code will show a button with the width equal to half of screen for medium and large screens; and will show a full-width button for small screens:
<div class="container">
<div class="col-xs-12 col-xs-offset-0 col-sm-offset-3 col-sm-6">
<button class="btn btn-group">Click me!</button>
</div>
</div>
Check this JSFiddle out. Try to resize frame.
If it is not enough, you can easily create your custom class.
Best way to initialize (empty) array in PHP
$myArray = [];
Creates empty array.
You can push values onto the array later, like so:
$myArray[] = "tree";
$myArray[] = "house";
$myArray[] = "dog";
At this point, $myArray contains "tree", "house" and "dog". Each of the above commands appends to the array, preserving the items that were already there.
Having come from other languages, this way of appending to an array seemed strange to me. I expected to have to do something like $myArray += "dog" or something... or maybe an "add()" method like Visual Basic collections have. But this direct append syntax certainly is short and convenient.
You actually have to use the unset() function to remove items:
unset($myArray[1]);
... would remove "house" from the array (arrays are zero-based).
unset($myArray);
... would destroy the entire array.
To be clear, the empty square brackets syntax for appending to an array is simply a way of telling PHP to assign the indexes to each value automatically, rather than YOU assigning the indexes. Under the covers, PHP is actually doing this:
$myArray[0] = "tree";
$myArray[1] = "house";
$myArray[2] = "dog";
You can assign indexes yourself if you want, and you can use any numbers you want. You can also assign index numbers to some items and not others. If you do that, PHP will fill in the missing index numbers, incrementing from the largest index number assigned as it goes.
So if you do this:
$myArray[10] = "tree";
$myArray[20] = "house";
$myArray[] = "dog";
... the item "dog" will be given an index number of 21. PHP does not do intelligent pattern matching for incremental index assignment, so it won't know that you might have wanted it to assign an index of 30 to "dog". You can use other functions to specify the increment pattern for an array. I won't go into that here, but its all in the PHP docs.
Cheers,
-=Cameron
How to get full path of a file?
This worked pretty well for me. It doesn't rely on the file system (a pro/con depending on need) so it'll be fast; and, it should be portable to most any *NIX. It does assume the passed string is indeed relative to the PWD and not some other directory.
function abspath () {
echo $1 | awk '\
# Root parent directory refs to the PWD for replacement below
/^\.\.\// { sub("^", "./") } \
# Replace the symbolic PWD refs with the absolute PWD \
/^\.\// { sub("^\.", ENVIRON["PWD"])} \
# Print absolute paths \
/^\// {print} \'
}
How to Get True Size of MySQL Database?
if you want to find it in MB do this
SELECT table_schema "DB Name",
Round(Sum(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB"
FROM information_schema.tables
GROUP BY table_schema;
How do I rename a MySQL schema?
If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE
Edit: On the model overview it's under Physical Schemata
Screenshot:
When should I use a List vs a LinkedList
Linked lists provide very fast insertion or deletion of a list member. Each member in a linked list contains a pointer to the next member in the list so to insert a member at position i:
- update the pointer in member i-1 to point to the new member
- set the pointer in the new member to point to member i
The disadvantage to a linked list is that random access is not possible. Accessing a member requires traversing the list until the desired member is found.
SASS - use variables across multiple files
Create an index.scss and there you can import all file structure you have. I will paste you my index from an enterprise project, maybe it will help other how to structure files in css:
@import 'base/_reset';
@import 'helpers/_variables';
@import 'helpers/_mixins';
@import 'helpers/_functions';
@import 'helpers/_helpers';
@import 'helpers/_placeholders';
@import 'base/_typography';
@import 'pages/_versions';
@import 'pages/_recording';
@import 'pages/_lists';
@import 'pages/_global';
@import 'forms/_buttons';
@import 'forms/_inputs';
@import 'forms/_validators';
@import 'forms/_fieldsets';
@import 'sections/_header';
@import 'sections/_navigation';
@import 'sections/_sidebar-a';
@import 'sections/_sidebar-b';
@import 'sections/_footer';
@import 'vendors/_ui-grid';
@import 'components/_modals';
@import 'components/_tooltip';
@import 'components/_tables';
@import 'components/_datepickers';
And you can watch them with gulp/grunt/webpack etc, like:
gulpfile.js
// SASS Task
var gulp = require('gulp');
var sass = require('gulp-sass');
//var concat = require('gulp-concat');
var uglifycss = require('gulp-uglifycss');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('styles', function(){
return gulp
.src('sass/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(concat('styles.css'))
.pipe(uglifycss({
"maxLineLen": 80,
"uglyComments": true
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./build/css/'));
});
gulp.task('watch', function () {
gulp.watch('sass/**/*.scss', ['styles']);
});
gulp.task('default', ['watch']);
Multiple Image Upload PHP form with one input
Multipal image uplode with other taBLE
$sql1 = "INSERT INTO event(title) VALUES('$title')";
$result1 = mysqli_query($connection,$sql1) or die(mysqli_error($connection));
$lastid= $connection->insert_id;
foreach ($_FILES["file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK ){
$name = $lastid.$_FILES['file']['name'][$key];
$target_dir = "photo/";
$sql2 = "INSERT INTO photos(image,eventid) VALUES ('".$target_dir.$name."','".$lastid."')";
$result2 = mysqli_query($connection,$sql2) or die(mysqli_error($connection));
move_uploaded_file($_FILES['file']['tmp_name'][$key],$target_dir.$name);
}
}
And how to fetch
$query = "SELECT * FROM event ";
$result = mysqli_query($connection,$query) or die(mysqli_error());
if($result->num_rows > 0) {
while($r = mysqli_fetch_assoc($result)){
$eventid= $r['id'];
$sqli="select id,image from photos where eventid='".$eventid."'";
$resulti=mysqli_query($connection,$sqli);
$image_json_array = array();
while($row = mysqli_fetch_assoc($resulti)){
$image_id = $row['id'];
$image_name = $row['image'];
$image_json_array[] = array("id"=>$image_id,"name"=>$image_name);
}
$msg1[] = array ("imagelist" => $image_json_array);
}
in ajax
$(document).ready(function(){ $('#addCAT').validate({ rules:{name:required:true}submitHandler:function(form){var formurl = $(form).attr('action'); $.ajax({ url: formurl,type: "POST",data: new FormData(form),cache: false,processData: false,contentType: false,success: function(data) {window.location.href="{{ url('admin/listcategory')}}";}});
}
})})
How to pass List<String> in post method using Spring MVC?
I had the same use case,
You can change your method defination in the following way :
@RequestMapping(value = "/saveFruits", method = RequestMethod.POST,
consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody Map<String,List<String>> fruits) {
..
}
The only problem is it accepts any key in place of "fruits" but You can easily get rid of a wrapper if it is not big functionality.
What does "where T : class, new()" mean?
where T : struct
The type argument must be a value type. Any value type except Nullable can be specified. See Using Nullable Types (C# Programming Guide) for more information.
where T : class
The type argument must be a reference type, including any class, interface, delegate, or array type. (See note below.)
where T : new()
The type argument must have a public parameterless constructor. When used in conjunction with other constraints, the new() constraint must be specified last.
where T : [base class name]
The type argument must be or derive from the specified base class.
where T : [interface name]
The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.
where T : U
The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.
How can I remove the outline around hyperlinks images?
I would bet most users aren't the type of user that use the keyboard as a navigation control. Is it then acceptable to annoy the majority of your users for a small group that prefers to use keyboard navigation? Short answer — depends on who your users are.
Also, I don't see this experience in the same way in Firefox and Safari. So this argument seems to be mostly for IE. It all really depends on your user base and their level of knowledge — how they use the site.
If you really want to know where you are and you are a keyboard user, you can always look at the status bar as you key through the site.
Regular expression for URL validation (in JavaScript)
After a long research I build this reg expression. I hope it will help others too.......
url = 'https://google.co.in';
var re = /[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/;
if (!re.test(url)) {
alert("url error");
return false;
}else{
alert('success')
}
Javascript callback when IFRAME is finished loading?
First up, going by the function name xssRequest it sounds like you're trying cross site request - which if that's right, you're not going to be able to read the contents of the iframe.
On the other hand, if the iframe's URL is on your domain you can access the body, but I've found that if I use a timeout to remove the iframe the callback works fine:
// possibly excessive use of jQuery - but I've got a live working example in production
$('#myUniqueID').load(function () {
if (typeof callback == 'function') {
callback($('body', this.contentWindow.document).html());
}
setTimeout(function () {$('#frameId').remove();}, 50);
});
Find duplicate entries in a column
Try this query.. It uses the Analytic function SUM:
SELECT * FROM
(
SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
FROM table1 a
WHERE s_ind ='Y'
)
WHERE cnt > 2
Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1
How to Pass Parameters to Activator.CreateInstance<T>()
Keep in mind though that passing arguments on Activator.CreateInstance has a significant performance difference versus parameterless creation.
There are better alternatives for dynamically creating objects using pre compiled lambda. Of course always performance is subjective and it clearly depends on each case if it's worth it or not.
Details about the issue on this article.
Graph is taken from the article and represents time taken in ms per 1000 calls.
Downloading an entire S3 bucket?
Here is some stuff to download all buckets, list them, list their contents.
//connection string
private static void dBConnection() {
app.setAwsCredentials(CONST.getAccessKey(), CONST.getSecretKey());
conn = new AmazonS3Client(app.getAwsCredentials());
app.setListOfBuckets(conn.listBuckets());
System.out.println(CONST.getConnectionSuccessfullMessage());
}
private static void downloadBucket() {
do {
for (S3ObjectSummary objectSummary : app.getS3Object().getObjectSummaries()) {
app.setBucketKey(objectSummary.getKey());
app.setBucketName(objectSummary.getBucketName());
if(objectSummary.getKey().contains(CONST.getDesiredKey())){
//DOWNLOAD
try
{
s3Client = new AmazonS3Client(new ProfileCredentialsProvider());
s3Client.getObject(
new GetObjectRequest(app.getBucketName(),app.getBucketKey()),
new File(app.getDownloadedBucket())
);
} catch (IOException e) {
e.printStackTrace();
}
do
{
if(app.getBackUpExist() == true){
System.out.println("Converting back up file");
app.setCurrentPacsId(objectSummary.getKey());
passIn = app.getDataBaseFile();
CONVERT= new DataConversion(passIn);
System.out.println(CONST.getFileDownloadedMessage());
}
}
while(app.getObjectExist()==true);
if(app.getObjectExist()== false)
{
app.setNoObjectFound(true);
}
}
}
app.setS3Object(conn.listNextBatchOfObjects(app.getS3Object()));
}
while (app.getS3Object().isTruncated());
}
/----------------------------Extension Methods-------------------------------------/
//Unzip bucket after download
public static void unzipBucket() throws IOException {
unzip = new UnZipBuckets();
unzip.unZipIt(app.getDownloadedBucket());
System.out.println(CONST.getFileUnzippedMessage());
}
//list all S3 buckets
public static void listAllBuckets(){
for (Bucket bucket : app.getListOfBuckets()) {
String bucketName = bucket.getName();
System.out.println(bucketName + "\t" + StringUtils.fromDate(bucket.getCreationDate()));
}
}
//Get the contents from the auto back up bucket
public static void listAllBucketContents(){
do {
for (S3ObjectSummary objectSummary : app.getS3Object().getObjectSummaries()) {
if(objectSummary.getKey().contains(CONST.getDesiredKey())){
System.out.println(objectSummary.getKey() + "\t" + objectSummary.getSize() + "\t" + StringUtils.fromDate(objectSummary.getLastModified()));
app.setBackUpCount(app.getBackUpCount() + 1);
}
}
app.setS3Object(conn.listNextBatchOfObjects(app.getS3Object()));
}
while (app.getS3Object().isTruncated());
System.out.println("There are a total of : " + app.getBackUpCount() + " buckets.");
}
}
Java multiline string
I got a bit annoyed with reading that multiline syntax is indeed been planned for jdk7 (after about how many decades of java existence?). Funnily, there is not even yet a readAll() function for reading the complete contents of a file (from jdk7 only, huhh), so the code below reads single lines.
/*
MakeMultiline v1.0 (2010) - Free to use and copy.
Small gadget to turn text blobs into one java string literal
(doing the split in lines, adding \n at each end and enclosing
in double quotes). Does escape quotes encountered in the text blob.
Useful for working around missing multiline string syntax in java
prior jdk7. Use with:
java MakeMultiline " "
or
java MakeMultiline " " mytextfile.txt
*/
import java.io.*;
class MakeMultiline {
public static void main(String[] args) {
try {
// args[0]: indent
// args[1]: filename to read (optional; stdin if not given)
// Beware the nmb of newlines at the end when using stdin!
String indent = (args.length > 0 ? args[0] : "");
FileReader fr = null; BufferedReader br;
if (args.length > 1)
{ fr = new FileReader(args[1]); br = new BufferedReader(fr); }
else
{ br = new BufferedReader(new InputStreamReader(System.in)); }
String s; String res = "";
while((s = br.readLine()) != null) {
if (res.length() > 0) res += " +\n";
res += indent + "\"" + s.replace("\"", "\\\"") + "\\n\"";
}
br.close(); if (fr != null) fr.close();
System.out.println(res + ";");
}
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}
This was the quickest solution for me. (2010-01-27)
How to get Toolbar from fragment?
In case fragments should have custom view of ToolBar you can implement ToolBar for each fragment separately.
add ToolBar into fragment_layout:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimaryDark"/>
find it in fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
//set toolbar appearance
toolbar.setBackground(R.color.material_blue_grey_800);
//for crate home button
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
menu listener could be created two ways:
override onOptionsItemSelected in your fragment:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
getActivity().onBackPressed();
}
return super.onOptionsItemSelected(item);
}
or set listener for toolbar when create it in onCreateView():
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
return false;
}
});
Checking if an object is null in C#
public static bool isnull(object T)
{
return T == null ? true : false;
}
use:
isnull(object.check.it)
Conditional use:
isnull(object.check.it) ? DoWhenItsTrue : DoWhenItsFalse;
Update (another way) updated 08/31/2017 and 01/25/2021. Thanks for the comment.
public static bool IsNull(object T)
{
return (bool)T ? true : false;
}
Demostration
And for the records, you have my code on Github, go check it out:
https://github.com/j0rt3g4/ValidateNull
PS: This one is especially for you Chayim Friedman, don't use beta software assuming that is all true. Wait for final versions or use your own environment to test, before assuming true beta software without any sort of documentation or demonstration from your end.
Loop over array dimension in plpgsql
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
How to write a foreach in SQL Server?
I made a procedure that execute a FOREACH
with CURSOR
for any table.
Example of use:
CREATE TABLE #A (I INT, J INT)
INSERT INTO #A VALUES (1, 2), (2, 3)
EXEC PRC_FOREACH
#A --Table we want to do the FOREACH
, 'SELECT @I, @J' --The execute command, each column becomes a variable in the same type, so DON'T USE SPACES IN NAMES
--The third variable is the database, it's optional because a table in TEMPB or the DB of the proc will be discovered in code
The result is 2 selects for each row.
The syntax of UPDATE
and break the FOREACH
are written in the hints.
This is the proc code:
CREATE PROC [dbo].[PRC_FOREACH] (@TBL VARCHAR(100) = NULL, @EXECUTE NVARCHAR(MAX)=NULL, @DB VARCHAR(100) = NULL) AS BEGIN
--LOOP BETWEEN EACH TABLE LINE
IF @TBL + @EXECUTE IS NULL BEGIN
PRINT '@TBL: A TABLE TO MAKE OUT EACH LINE'
PRINT '@EXECUTE: COMMAND TO BE PERFORMED ON EACH FOREACH TRANSACTION'
PRINT '@DB: BANK WHERE THIS TABLE IS (IF NOT INFORMED IT WILL BE DB_NAME () OR TEMPDB)' + CHAR(13)
PRINT 'ROW COLUMNS WILL VARIABLE WITH THE SAME NAME (COL_A = @COL_A)'
PRINT 'THEREFORE THE COLUMNS CANT CONTAIN SPACES!' + CHAR(13)
PRINT 'SYNTAX UPDATE:
UPDATE TABLE
SET COL = NEW_VALUE
WHERE CURRENT OF MY_CURSOR
CLOSE CURSOR (BEFORE ALL LINES):
IF 1 = 1 GOTO FIM_CURSOR'
RETURN
END
SET @DB = ISNULL(@DB, CASE WHEN LEFT(@TBL, 1) = '#' THEN 'TEMPDB' ELSE DB_NAME() END)
--Identifies the columns for the variables (DECLARE and INTO (Next cursor line))
DECLARE @Q NVARCHAR(MAX)
SET @Q = '
WITH X AS (
SELECT
A = '', @'' + NAME
, B = '' '' + type_name(system_type_id)
, C = CASE
WHEN type_name(system_type_id) IN (''VARCHAR'', ''CHAR'', ''NCHAR'', ''NVARCHAR'') THEN ''('' + REPLACE(CONVERT(VARCHAR(10), max_length), ''-1'', ''MAX'') + '')''
WHEN type_name(system_type_id) IN (''DECIMAL'', ''NUMERIC'') THEN ''('' + CONVERT(VARCHAR(10), precision) + '', '' + CONVERT(VARCHAR(10), scale) + '')''
ELSE ''''
END
FROM [' + @DB + '].SYS.COLUMNS C WITH(NOLOCK)
WHERE OBJECT_ID = OBJECT_ID(''[' + @DB + '].DBO.[' + @TBL + ']'')
)
SELECT
@DECLARE = STUFF((SELECT A + B + C FROM X FOR XML PATH('''')), 1, 1, '''')
, @INTO = ''--Read the next line
FETCH NEXT FROM MY_CURSOR INTO '' + STUFF((SELECT A + '''' FROM X FOR XML PATH('''')), 1, 1, '''')'
DECLARE @DECLARE NVARCHAR(MAX), @INTO NVARCHAR(MAX)
EXEC SP_EXECUTESQL @Q, N'@DECLARE NVARCHAR(MAX) OUTPUT, @INTO NVARCHAR(MAX) OUTPUT', @DECLARE OUTPUT, @INTO OUTPUT
--PREPARE TO QUERY
SELECT
@Q = '
DECLARE ' + @DECLARE + '
-- Cursor to scroll through object names
DECLARE MY_CURSOR CURSOR FOR
SELECT *
FROM [' + @DB + '].DBO.[' + @TBL + ']
-- Opening Cursor for Reading
OPEN MY_CURSOR
' + @INTO + '
-- Traversing Cursor Lines (While There)
WHILE @@FETCH_STATUS = 0
BEGIN
' + @EXECUTE + '
-- Reading the next line
' + @INTO + '
END
FIM_CURSOR:
-- Closing Cursor for Reading
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR'
EXEC SP_EXECUTESQL @Q --MAGIA
END
How to create a batch file to run cmd as administrator
You can use a shortcut that links to the batch file. Just go into properties for the shortcut and select advanced, then "run as administrator".
Then just make the batch file hidden, and run the shortcut.
This way, you can even set your own icon for the shortcut.
White space showing up on right side of page when background image should extend full length of page
After exploring some of the helpful strategies provided here, I found that I only needed to add iOS specific CSS (I put it at the bottom of my main css sheet.) Seems like hiding the overflow-x was the answer for me. I assume that stating the width at 100% helps in the event that my content goes wide. It should be noted that I was only having this issue in iOS. If it is also in Firefox, just the html and body block should probably be used as the @media is specifically targeting mobile devices.
@media
only screen and (-webkit-min-device-pixel-ratio: 1.5),
only screen and (-o-min-device-pixel-ratio: 3/2),
only screen and (min--moz-device-pixel-ratio: 1.5),
only screen and (min-device-pixel-ratio: 1.5){
html,
body{
width:100%;
overflow-x:hidden;
}
}
Please hip me if this seems incorrect to anyone :)
PHP namespaces and "use"
If you need to order your code into namespaces, just use the keyword namespace
:
file1.php
namespace foo\bar;
In file2.php
$obj = new \foo\bar\myObj();
You can also use use
. If in file2 you put
use foo\bar as mypath;
you need to use mypath
instead of bar
anywhere in the file:
$obj = new mypath\myObj();
Using use foo\bar;
is equal to use foo\bar as bar;
.
Using Bootstrap Modal window as PartialView
I use AJAX to do this. You have your partial with your typical twitter modal template html:
<div class="container">
<!-- Modal -->
<div class="modal fade" id="LocationNumberModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">
Serial Numbers
</h4>
</div>
<div class="modal-body">
<span id="test"></span>
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
Close
</button>
</div>
</div>
</div>
</div>
</div>
Then you have your controller method, I use JSON and have a custom class that rendors the view to a string. I do this so I can perform multiple ajax updates on the screen with one ajax call. Reference here: Example but you can use an PartialViewResult/ActionResult on return if you are just doing the one call. I will show it using JSON..
And the JSON Method in Controller:
public JsonResult LocationNumberModal(string partNumber = "")
{
//Business Layer/DAL to get information
return Json(new {
LocationModal = ViewUtility.RenderRazorViewToString(this.ControllerContext, "LocationNumberModal.cshtml", new SomeModelObject())
},
JsonRequestBehavior.AllowGet
);
}
And then, in the view using your modal: You can package the AJAX in your partial and call @{Html.RenderPartial... Or you can have a placeholder with a div:
<div id="LocationNumberModalContainer"></div>
then your ajax:
function LocationNumberModal() {
var partNumber = "1234";
var src = '@Url.Action("LocationNumberModal", "Home", new { area = "Part" })'
+ '?partNumber='' + partNumber;
$.ajax({
type: "GET",
url: src,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
$("#LocationNumberModalContainer").html(data.LocationModal);
$('#LocationNumberModal').modal('show');
}
});
};
Then the button to your modal:
<button type="button" id="GetLocBtn" class="btn btn-default" onclick="LocationNumberModal()">Get</button>
JQuery Find #ID, RemoveClass and AddClass
jQuery('#testID2').find('.test2').replaceWith('.test3');
Semantically, you are selecting the element with the ID testID2
, then you are looking for any descendent elements with the class test2
(does not exist) and then you are replacing that element with another element (elements anywhere in the page with the class test3
) that also do not exist.
You need to do this:
jQuery('#testID2').addClass('test3').removeClass('test2');
This selects the element with the ID testID2
, then adds the class test3
to it. Last, it removes the class test2
from that element.
Excel Looping through rows and copy cell values to another worksheet
Private Sub CommandButton1_Click()
Dim Z As Long
Dim Cellidx As Range
Dim NextRow As Long
Dim Rng As Range
Dim SrcWks As Worksheet
Dim DataWks As Worksheet
Z = 1
Set SrcWks = Worksheets("Sheet1")
Set DataWks = Worksheets("Sheet2")
Set Rng = EntryWks.Range("B6:ad6")
NextRow = DataWks.UsedRange.Rows.Count
NextRow = IIf(NextRow = 1, 1, NextRow + 1)
For Each RA In Rng.Areas
For Each Cellidx In RA
Z = Z + 1
DataWks.Cells(NextRow, Z) = Cellidx
Next Cellidx
Next RA
End Sub
Alternatively
Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10")
This is a CopynPaste - Method
Sub CopyDataToPlan()
Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean
On Error GoTo Err_Execute
'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value
Sheets("Plan").Select
'Start at column B
LColumn = 2
LFound = False
While LFound = False
'Encountered blank cell in row 2, terminate search
If Len(Cells(2, LColumn)) = 0 Then
MsgBox "No matching date was found."
Exit Sub
'Found match in row 2
ElseIf Cells(2, LColumn) = LDate Then
'Select values to copy from "Rolling Plan" sheet
Sheets("Rolling Plan").Select
Range("B5:H6").Select
Selection.Copy
'Paste onto "Plan" sheet
Sheets("Plan").Select
Cells(3, LColumn).Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
LFound = True
MsgBox "The data has been successfully copied."
'Continue searching
Else
LColumn = LColumn + 1
End If
Wend
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
And there might be some methods doing that in Excel.
Css transition from display none to display block, navigation with subnav
Generally when people are trying to animate display: none
what they really want is:
- Fade content in, and
- Have the item not take up space in the document when hidden
Most popular answers use visibility
, which can only achieve the first goal, but luckily it's just as easy to achieve both by using position
.
Since position: absolute
removes the element from typing document flow spacing, you can toggle between position: absolute
and position: static
(global default), combined with opacity
. See the below example.
_x000D_
_x000D_
.content-page {_x000D_
position:absolute;_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
.content-page.active {_x000D_
position: static;_x000D_
opacity: 1;_x000D_
transition: opacity 1s linear;_x000D_
}
_x000D_
_x000D_
_x000D_
Android ClassNotFoundException: Didn't find class on path
This following method worked for me
- Right click on your
project
and select properties
- The "Properties for " panel will open. From the menu on the left go to
Java Build Path
-> Order and Export
- From the list below uncheck the box next to
"Android Dependencies"
- Finally
clean your project
and run
Where does the slf4j log file get saved?
The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)
-Dlogging.config={file_location}\log4j2.xml
or this:
-Dlog4j.configurationFile={file_location}\log4j2.xml
How to generate unique ID with node.js
edit: shortid has been deprecated. The maintainers recommend to use nanoid instead.
Another approach is using the shortid package from npm.
It is very easy to use:
var shortid = require('shortid');
console.log(shortid.generate()); // e.g. S1cudXAF
and has some compelling features:
ShortId creates amazingly short non-sequential url-friendly unique
ids. Perfect for url shorteners, MongoDB and Redis ids, and any other
id users might see.
- By default 7-14 url-friendly characters: A-Z, a-z, 0-9, _-
- Non-sequential so they are not predictable.
- Can generate any number of ids without duplicates, even millions per day.
- Apps can be restarted any number of times without any chance of repeating an id.
IsNumeric function in c#
http://msdn.microsoft.com/en-us/library/wkze6zky.aspx
menu:
Project-->Add Reference
click: assemblies, framework
Put a checkmark on Microsoft.VisualBasic.
Hit OK.
That link is for Visual Studio 2013, you can use the "Other versions" dropdown for different versions of visual studio.
In all cases you need to add a reference to the .NET assembly "Microsoft.VisualBasic".
At the top of your c# file you neeed:
using Microsoft.VisualBasic;
Then you can look at writing the code.
The code would be something like:
private void btnOK_Click(object sender, EventArgs e)
{
if ( Information.IsNumeric(startingbudget) )
{
MessageBox.Show("This is a number.");
}
}
Split (explode) pandas dataframe string entry to separate rows
UPDATE2: more generic vectorized function, which will work for multiple normal
and multiple list
columns
def explode(df, lst_cols, fill_value='', preserve_index=False):
# make sure `lst_cols` is list-alike
if (lst_cols is not None
and len(lst_cols) > 0
and not isinstance(lst_cols, (list, tuple, np.ndarray, pd.Series))):
lst_cols = [lst_cols]
# all columns except `lst_cols`
idx_cols = df.columns.difference(lst_cols)
# calculate lengths of lists
lens = df[lst_cols[0]].str.len()
# preserve original index values
idx = np.repeat(df.index.values, lens)
# create "exploded" DF
res = (pd.DataFrame({
col:np.repeat(df[col].values, lens)
for col in idx_cols},
index=idx)
.assign(**{col:np.concatenate(df.loc[lens>0, col].values)
for col in lst_cols}))
# append those rows that have empty lists
if (lens == 0).any():
# at least one list in cells is empty
res = (res.append(df.loc[lens==0, idx_cols], sort=False)
.fillna(fill_value))
# revert the original index order
res = res.sort_index()
# reset index if requested
if not preserve_index:
res = res.reset_index(drop=True)
return res
Demo:
Multiple list
columns - all list
columns must have the same # of elements in each row:
In [134]: df
Out[134]:
aaa myid num text
0 10 1 [1, 2, 3] [aa, bb, cc]
1 11 2 [] []
2 12 3 [1, 2] [cc, dd]
3 13 4 [] []
In [135]: explode(df, ['num','text'], fill_value='')
Out[135]:
aaa myid num text
0 10 1 1 aa
1 10 1 2 bb
2 10 1 3 cc
3 11 2
4 12 3 1 cc
5 12 3 2 dd
6 13 4
preserving original index values:
In [136]: explode(df, ['num','text'], fill_value='', preserve_index=True)
Out[136]:
aaa myid num text
0 10 1 1 aa
0 10 1 2 bb
0 10 1 3 cc
1 11 2
2 12 3 1 cc
2 12 3 2 dd
3 13 4
Setup:
df = pd.DataFrame({
'aaa': {0: 10, 1: 11, 2: 12, 3: 13},
'myid': {0: 1, 1: 2, 2: 3, 3: 4},
'num': {0: [1, 2, 3], 1: [], 2: [1, 2], 3: []},
'text': {0: ['aa', 'bb', 'cc'], 1: [], 2: ['cc', 'dd'], 3: []}
})
CSV column:
In [46]: df
Out[46]:
var1 var2 var3
0 a,b,c 1 XX
1 d,e,f,x,y 2 ZZ
In [47]: explode(df.assign(var1=df.var1.str.split(',')), 'var1')
Out[47]:
var1 var2 var3
0 a 1 XX
1 b 1 XX
2 c 1 XX
3 d 2 ZZ
4 e 2 ZZ
5 f 2 ZZ
6 x 2 ZZ
7 y 2 ZZ
using this little trick we can convert CSV-like column to list
column:
In [48]: df.assign(var1=df.var1.str.split(','))
Out[48]:
var1 var2 var3
0 [a, b, c] 1 XX
1 [d, e, f, x, y] 2 ZZ
UPDATE: generic vectorized approach (will work also for multiple columns):
Original DF:
In [177]: df
Out[177]:
var1 var2 var3
0 a,b,c 1 XX
1 d,e,f,x,y 2 ZZ
Solution:
first let's convert CSV strings to lists:
In [178]: lst_col = 'var1'
In [179]: x = df.assign(**{lst_col:df[lst_col].str.split(',')})
In [180]: x
Out[180]:
var1 var2 var3
0 [a, b, c] 1 XX
1 [d, e, f, x, y] 2 ZZ
Now we can do this:
In [181]: pd.DataFrame({
...: col:np.repeat(x[col].values, x[lst_col].str.len())
...: for col in x.columns.difference([lst_col])
...: }).assign(**{lst_col:np.concatenate(x[lst_col].values)})[x.columns.tolist()]
...:
Out[181]:
var1 var2 var3
0 a 1 XX
1 b 1 XX
2 c 1 XX
3 d 2 ZZ
4 e 2 ZZ
5 f 2 ZZ
6 x 2 ZZ
7 y 2 ZZ
OLD answer:
Inspired by @AFinkelstein solution, i wanted to make it bit more generalized which could be applied to DF with more than two columns and as fast, well almost, as fast as AFinkelstein's solution):
In [2]: df = pd.DataFrame(
...: [{'var1': 'a,b,c', 'var2': 1, 'var3': 'XX'},
...: {'var1': 'd,e,f,x,y', 'var2': 2, 'var3': 'ZZ'}]
...: )
In [3]: df
Out[3]:
var1 var2 var3
0 a,b,c 1 XX
1 d,e,f,x,y 2 ZZ
In [4]: (df.set_index(df.columns.drop('var1',1).tolist())
...: .var1.str.split(',', expand=True)
...: .stack()
...: .reset_index()
...: .rename(columns={0:'var1'})
...: .loc[:, df.columns]
...: )
Out[4]:
var1 var2 var3
0 a 1 XX
1 b 1 XX
2 c 1 XX
3 d 2 ZZ
4 e 2 ZZ
5 f 2 ZZ
6 x 2 ZZ
7 y 2 ZZ
Gson - convert from Json to a typed ArrayList<T>
Your JSON sample is:
{
"status": "ok",
"comment": "",
"result": {
"id": 276,
"firstName": "mohamed",
"lastName": "hussien",
"players": [
"player 1",
"player 2",
"player 3",
"player 4",
"player 5"
]
}
so if you want to save arraylist of modules in your SharedPrefrences so :
1- will convert your returned arraylist for json format using this method
public static String toJson(Object jsonObject) {
return new Gson().toJson(jsonObject);
}
2- Save it in shared prefreneces
PreferencesUtils.getInstance(context).setString("players", toJson((.....ArrayList you want to convert.....)));
3- to retrieve it at any time get JsonString from Shared preferences like that
String playersString= PreferencesUtils.getInstance(this).getString("players");
4- convert it again to array list
public static Object fromJson(String jsonString, Type type) {
return new Gson().fromJson(jsonString, type);
}
ArrayList<String> playersList= (ArrayList<String>) fromJson(playersString,
new TypeToken<ArrayList<String>>() {
}.getType());
this solution also doable if you want to parse ArrayList of Objects
Hope it's help you by using Gson Library .
scrollTop jquery, scrolling to div with id?
instead of
$('html, body').animate({scrollTop:xxx}, 'slow');
use
$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');
this will return the absolute top position of whatever element you select as #div_id
How to change webservice url endpoint?
IMO, the provider is telling you to change the service endpoint (i.e. where to reach the web service), not the client endpoint (I don't understand what this could be). To change the service endpoint, you basically have two options.
Use the Binding Provider to set the endpoint URL
The first option is to change the BindingProvider.ENDPOINT_ADDRESS_PROPERTY
property value of the BindingProvider
(every proxy implements javax.xml.ws.BindingProvider
interface):
...
EchoService service = new EchoService();
Echo port = service.getEchoPort();
/* Set NEW Endpoint Location */
String endpointURL = "http://NEW_ENDPOINT_URL";
BindingProvider bp = (BindingProvider)port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
System.out.println("Server said: " + echo.echo(args[0]));
...
The drawback is that this only works when the original WSDL is still accessible. Not recommended.
Use the WSDL to get the endpoint URL
The second option is to get the endpoint URL from the WSDL.
...
URL newEndpoint = new URL("NEW_ENDPOINT_URL");
QName qname = new QName("http://ws.mycompany.tld","EchoService");
EchoService service = new EchoService(newEndpoint, qname);
Echo port = service.getEchoPort();
System.out.println("Server said: " + echo.echo(args[0]));
...
Failed to load resource: the server responded with a status of 404 (Not Found) error in server
Use your browser's network inspector (F12) to see when the browser is requesting the bgbody.png image and what absolute path it's using and why the server is returning a 404 response.
...assuming that bgbody.png actually exists :)
Is your CSS in a stylesheet file or in a <style>
block in a page? If it's in a stylesheet then the relative path must be relative to the CSS stylesheet (not the document that references it). If it's in a page then it must be relative to the current resource path. If you're using non-filesystem-based resource paths (i.e. using URL rewriting or URL routing) then this will cause problems and it's best to always use absolute paths.
Going by your relative path it looks like you store your images separately from your stylesheets. I don't think this is a good idea - I support storing images and other resources, like fonts, in the same directory as the stylesheet itself, as it simplifies paths and is also a more logical filesystem arrangement.
Passing by reference in C
You're not passing an int by reference, you're passing a pointer-to-an-int by value. Different syntax, same meaning.
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
How to use a global array in C#?
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
Do you have to put Task.Run in a method to make it async?
One of the most important thing to remember when decorating a method with async is that at least there is one await operator inside the method. In your example, I would translate it as shown below using TaskCompletionSource.
private Task<int> DoWorkAsync()
{
//create a task completion source
//the type of the result value must be the same
//as the type in the returning Task
TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
Task.Run(() =>
{
int result = 1 + 2;
//set the result to TaskCompletionSource
tcs.SetResult(result);
});
//return the Task
return tcs.Task;
}
private async void DoWork()
{
int result = await DoWorkAsync();
}
How to convert Json array to list of objects in c#
you have an unmatched jSon string, if you want to convert into a list, try this
{
"id": "MyID",
"values": [
{
"id": "100",
"diaplayName": "MyValue1",
},
{
"id": "200",
"diaplayName": "MyValue2",
}
]
}
Format the date using Ruby on Rails
First you will need to convert the timestamp to an actual Ruby Date/Time.
If you receive it just as a string or int from facebook, you will need to do something like this:
my_date = Time.at(timestamp_from_facebook.to_i)
Then to format it nicely in the view, you can just use to_s
(for the default formatting):
<%= my_date.to_s %>
Note that if you don't put to_s
, it will still be called by default if you use it in a view or in a string e.g. the following will also call to_s
on the date:
<%= "Here is a date: #{my_date}" %>
or if you want the date formatted in a specific way (eg using "d/m/Y") - you can use strftime
as outlined in the other answer.
is it possible to add colors to python output?
IDLE's console does not support ANSI escape sequences, or any other form of escapes for coloring your output.
You can learn how to talk to IDLE's console directly instead of just treating it like normal stdout and printing to it (which is how it does things like color-coding your syntax), but that's pretty complicated. The idle
documentation just tells you the basics of using IDLE itself, and its idlelib
library has no documentation (well, there is a single line of documentation—"(New in 2.3) Support library for the IDLE development environment."—if you know where to find it, but that isn't very helpful). So, you need to either read the source, or do a whole lot of trial and error, to even get started.
Alternatively, you can run your script from the command line instead of from IDLE, in which case you can use whatever escape sequences your terminal handles. Most modern terminals will handle at least basic 16/8-color ANSI. Many will handle 16/16, or the expanded xterm-256 color sequences, or even full 24-bit colors. (I believe gnome-terminal
is the default for Ubuntu, and in its default configuration it will handle xterm-256, but that's really a question for SuperUser or AskUbuntu.)
Learning to read the termcap
entries to know which codes to enter is complicated… but if you only care about a single console—or are willing to just assume "almost everything handles basic 16/8-color ANSI, and anything that doesn't, I don't care about", you can ignore that part and just hardcode them based on, e.g., this page.
Once you know what you want to emit, it's just a matter of putting the codes in the strings before printing them.
But there are libraries that can make this all easier for you. One really nice library, which comes built in with Python, is curses
. This lets you take over the terminal and do a full-screen GUI, with colors and spinning cursors and anything else you want. It is a little heavy-weight for simple uses, of course. Other libraries can be found by searching PyPI, as usual.
Android Camera Preview Stretched
Just to make this thread more complete i am adding my version of answer:
What i wanted to achieve:
The surface view shouldn't be stretched, and it should cover the whole screen, Moreover, there was only a landscape mode in my app.
Solution:
The solution is an extremely small extension to F1sher's solution:
=> First step is to integrate F1sher's solution.
=> Now, there might arise a scenario in F1sher's solution when the surface view doesn't covers the whole screen, The solution is to make the surface view greater than the screen dimensions so that it covers the whole screen, for that:
size = getOptimalPreviewSize(mCamera.getParameters().getSupportedPreviewSizes(), screenWidth, screenHeight);
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(size.width, size.height);
mCamera.setParameters(parameters);
double screenRatio = (double) screenHeight / screenWidth;
double previewRatio = (double) size.height / size.width;
if (previewRatio > screenRatio) /*if preview ratio is greater than screen ratio then we will have to recalculate the surface height while keeping the surface width equal to the screen width*/
{
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(screenWidth, (int) (screenWidth * previewRatio));
params1.addRule(RelativeLayout.CENTER_IN_PARENT);
flPreview.setLayoutParams(params1);
flPreview.setClipChildren(false);
LayoutParams surfaceParams = new LayoutParams(screenWidth, (int) (screenWidth * previewRatio));
surfaceParams.gravity = Gravity.CENTER;
mPreview.setLayoutParams(surfaceParams);
}
else /*if preview ratio is smaller than screen ratio then we will have to recalculate the surface width while keeping the surface height equal to the screen height*/
{
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams((int) ((double) screenHeight / previewRatio), screenHeight);
params1.addRule(RelativeLayout.CENTER_IN_PARENT);
flPreview.setLayoutParams(params1);
flPreview.setClipChildren(false);
LayoutParams surfaceParams = new LayoutParams((int) ((double) screenHeight / previewRatio), screenHeight);
surfaceParams.gravity = Gravity.CENTER;
mPreview.setLayoutParams(surfaceParams);
}
flPreview.addView(mPreview);
/* The TopMost layout used is the RelativeLayout, flPreview is the FrameLayout in which Surface View is added, mPreview is an instance of a class which extends SurfaceView */
Add animated Gif image in Iphone UIImageView
Swift 3:
As suggested above I'm using FLAnimatedImage with an FLAnimatedImageView. And I'm loading the gif as a data set from xcassets. This allows me to provide different gifs for iphone and ipad for appearance and app slicing purposes. This is far more performant than anything else I've tried. It's also easy to pause using .stopAnimating().
if let asset = NSDataAsset(name: "animation") {
let gifData = asset.data
let gif = FLAnimatedImage(animatedGIFData: gifData)
imageView.animatedImage = gif
}
How to deploy ASP.NET webservice to IIS 7?
- rebuild project in VS
- copy project folder to iis folder, probably C:\inetpub\wwwroot\
- in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
- add web service to created website, almost the same as 3.
- INSTALL ASP
for windows 7 and .net 4.0:
c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
- check access to web service on your browser
Best way to convert strings to symbols in hash
Would something like the following work?
new_hash = Hash.new
my_hash.each { |k, v| new_hash[k.to_sym] = v }
It'll copy the hash, but you won't care about that most of the time. There's probably a way to do it without copying all the data.
How should you diagnose the error SEHException - External component has thrown an exception
The component makers say that this has been fixed in the latest version of their component which we are using in-house, but this has been given to the customer yet.
Ask the component maker how to test whether the problem that the customer is getting is the problem which they say they've fixed in their latest version, without/before deploying their latest version to the customer.
JFrame Maximize window
i like this version:
import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Test
{
public static void main(String [] args)
{
final JFrame frame = new JFrame();
final GraphicsConfiguration config = frame.getGraphicsConfiguration();
final int left = Toolkit.getDefaultToolkit().getScreenInsets(config).left;
final int right = Toolkit.getDefaultToolkit().getScreenInsets(config).right;
final int top = Toolkit.getDefaultToolkit().getScreenInsets(config).top;
final int bottom = Toolkit.getDefaultToolkit().getScreenInsets(config).bottom;
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final int width = screenSize.width - left - right;
final int height = screenSize.height - top - bottom;
frame.setResizable(false);
frame.setSize(width,height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
CSS Selector "(A or B) and C"?
No. Standard CSS does not provide the kind of thing you're looking for.
However, you might want to look into LESS and SASS.
These are two projects which aim to extend default CSS syntax by introducing additional features, including variables, nested rules, and other enhancements.
They allow you to write much more structured CSS code, and either of them will almost certainly solve your particular use case.
Of course, none of the browsers support their extended syntax (especially since the two projects each have different syntax and features), but what they do is provide a "compiler" which converts your LESS or SASS code into standard CSS, which you can then deploy on your site.
Multiple INSERT statements vs. single INSERT with multiple VALUES
The issue probably has to do with the time it takes to compile the query.
If you want to speed up the inserts, what you really need to do is wrap them in a transaction:
BEGIN TRAN;
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age)
VALUES ('6f3f7257-a3d8-4a78-b2e1-c9b767cfe1c1', 'First 0', 'Last 0', 0);
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age)
VALUES ('32023304-2e55-4768-8e52-1ba589b82c8b', 'First 1', 'Last 1', 1);
...
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age)
VALUES ('f34d95a7-90b1-4558-be10-6ceacd53e4c4', 'First 999', 'Last 999', 999);
COMMIT TRAN;
From C#, you might also consider using a table valued parameter. Issuing multiple commands in a single batch, by separating them with semicolons, is another approach that will also help.