How to display a loading screen while site content loads
How about with jQuery? A simple...
$(window).load(function() { //Do the code in the {}s when the window has loaded
$("#loader").fadeOut("fast"); //Fade out the #loader div
});
And the HTML...
<div id="loader"></div>
And CSS...
#loader {
width: 100%;
height: 100%;
background-color: white;
margin: 0;
}
Then in your loader div
you would put the GIF, and any text you wanted, and it will fade out once the page has loaded.
Using the "animated circle" in an ImageView while loading stuff
Simply put this block of xml in your activity layout file:
<RelativeLayout
android:id="@+id/loadingPanel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true" />
</RelativeLayout>
And when you finish loading, call this one line:
findViewById(R.id.loadingPanel).setVisibility(View.GONE);
The result (and it spins too):
WPF loading spinner
You can do it without any additional controls and libraries, using only Image control and transform:
<Image
Source="/images/spinner.png"
Width="100"
Height="100"
RenderTransformOrigin="0.5, 0.5" Visibility="{Binding IsLoading, Converter={StaticResource BooleanToVisibilityConverter}}">
<Image.RenderTransform>
<RotateTransform x:Name="noFreeze" />
</Image.RenderTransform>
<Image.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="(Image.RenderTransform).(RotateTransform.Angle)"
To="360" Duration="0:0:1" RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Image.Triggers>
</Image>
Replace /images/spinner.png
with your image. Change To="360"
to To="-360"
if you want to rotate it counterclockwise. Duration="0:0:1"
equals to 1 second per rotation.
Dynamic loading of images in WPF
Here is the extension method to load an image from URI:
public static BitmapImage GetBitmapImage(
this Uri imageAbsolutePath,
BitmapCacheOption bitmapCacheOption = BitmapCacheOption.Default)
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = bitmapCacheOption;
image.UriSource = imageAbsolutePath;
image.EndInit();
return image;
}
Sample of use:
Uri _imageUri = new Uri(imageAbsolutePath);
ImageXamlElement.Source = _imageUri.GetBitmapImage(BitmapCacheOption.OnLoad);
Simple as that!
How to add a spinner icon to button when it's in the Loading state?
Here is a full-fledged css solution inspired by Bulma. Just add
.button {
display: inline-flex;
align-items: center;
justify-content: center;
position: relative;
min-width: 200px;
max-width: 100%;
min-height: 40px;
text-align: center;
cursor: pointer;
}
@-webkit-keyframes spinAround {
from {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
to {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@keyframes spinAround {
from {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
to {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
.button.is-loading {
text-indent: -9999px;
box-shadow: none;
font-size: 1rem;
height: 2.25em;
line-height: 1.5;
vertical-align: top;
padding-bottom: calc(0.375em - 1px);
padding-left: 0.75em;
padding-right: 0.75em;
padding-top: calc(0.375em - 1px);
white-space: nowrap;
}
.button.is-loading::after {
-webkit-animation: spinAround 500ms infinite linear;
animation: spinAround 500ms infinite linear;
border: 2px solid #dbdbdb;
border-radius: 290486px;
border-right-color: transparent;
border-top-color: transparent;
content: "";
display: block;
height: 1em;
position: relative;
width: 1em;
}
Display loading image while post with ajax
_x000D_
_x000D_
//$(document).ready(function(){_x000D_
// $("a").click(function(event){_x000D_
// event.preventDefault();_x000D_
// $("div").html("This is prevent link...");_x000D_
// });_x000D_
//}); _x000D_
_x000D_
$(document).ready(function(){_x000D_
$("a").click(function(event){_x000D_
event.preventDefault();_x000D_
$.ajax({_x000D_
beforeSend: function(){_x000D_
$('#text').html("<img src='ajax-loader.gif' /> Loading...");_x000D_
},_x000D_
success : function(){_x000D_
setInterval(function(){ $('#text').load("cd_catalog.txt"); },1000);_x000D_
}_x000D_
});_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
_x000D_
<a href="http://www.wantyourhelp.com">[click to redirect][1]</a>_x000D_
<div id="text"></div>
_x000D_
_x000D_
_x000D_
JavaScript Loading Screen while page loads
You can wait until the body is ready:
_x000D_
_x000D_
function onReady(callback) {_x000D_
var intervalId = window.setInterval(function() {_x000D_
if (document.getElementsByTagName('body')[0] !== undefined) {_x000D_
window.clearInterval(intervalId);_x000D_
callback.call(this);_x000D_
}_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
function setVisible(selector, visible) {_x000D_
document.querySelector(selector).style.display = visible ? 'block' : 'none';_x000D_
}_x000D_
_x000D_
onReady(function() {_x000D_
setVisible('.page', true);_x000D_
setVisible('#loading', false);_x000D_
});
_x000D_
body {_x000D_
background: #FFF url("https://i.imgur.com/KheAuef.png") top left repeat-x;_x000D_
font-family: 'Alex Brush', cursive !important;_x000D_
}_x000D_
_x000D_
.page { display: none; padding: 0 0.5em; }_x000D_
.page h1 { font-size: 2em; line-height: 1em; margin-top: 1.1em; font-weight: bold; }_x000D_
.page p { font-size: 1.5em; line-height: 1.275em; margin-top: 0.15em; }_x000D_
_x000D_
#loading {_x000D_
display: block;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
z-index: 100;_x000D_
width: 100vw;_x000D_
height: 100vh;_x000D_
background-color: rgba(192, 192, 192, 0.5);_x000D_
background-image: url("https://i.stack.imgur.com/MnyxU.gif");_x000D_
background-repeat: no-repeat;_x000D_
background-position: center;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>_x000D_
<link href="https://fonts.googleapis.com/css?family=Alex+Brush" rel="stylesheet">_x000D_
<div class="page">_x000D_
<h1>The standard Lorem Ipsum passage</h1>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure_x000D_
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
</div>_x000D_
<div id="loading"></div>
_x000D_
_x000D_
_x000D_
Here is a JSFiddle that demonstrates this technique.
How to create a JavaScript callback for knowing when an image is loaded?
If you are using React.js, you could do this:
render() {
// ...
<img
onLoad={() => this.onImgLoad({ item })}
onError={() => this.onImgLoad({ item })}
src={item.src} key={item.key}
ref={item.key} />
// ...
}
Where:
- onLoad (...) now will called with something like this:
{ src: "https://......png", key:"1" }
you can use this as "key" to know which images is loaded correctly and which not.
- onError(...) it is the same but for errors.
- the object "item" is something like this { key:"..", src:".."}
you can use to store the images' URL and key in order to use in a list of images.
Display a loading bar before the entire page is loaded
Whenever you try to load any data in this window this gif will load.
HTML
Make a Div
<div class="loader"></div>
CSS
.
.loader {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('https://lkp.dispendik.surabaya.go.id/assets/loading.gif') 50% 50% no-repeat rgb(249,249,249);
jQuery
$(window).load(function() {
$(".loader").fadeOut("slow");
});
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
problem with php mail 'From' header
headers were not working for me on my shared hosting, reason was i was using my hotmail email address in header.
i created a email on my cpanel and i set that same email in the header yeah it worked like a charm!
$header = 'From: ShopFive <[email protected]>' . "\r\n";
How to return HTTP 500 from ASP.NET Core RC2 Web Api?
You could use Microsoft.AspNetCore.Mvc.ControllerBase.StatusCode
and Microsoft.AspNetCore.Http.StatusCodes
to form your response, if you don't wish to hardcode specific numbers.
return StatusCode(StatusCodes.Status500InternalServerError);
UPDATE: Aug 2019
Perhaps not directly related to the original question but when trying to achieve the same result with Microsoft Azure Functions
I found that I had to construct a new StatusCodeResult
object found in the Microsoft.AspNetCore.Mvc.Core
assembly. My code now looks like this;
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
Javascript String to int conversion
This is to do with JavaScript's +
in operator - if a number and a string are "added" up, the number is converted into a string:
0 + 1; //1
'0' + 1; // '01'
To solve this, use the +
unary operator, or use parseInt()
:
+'0' + 1; // 1
parseInt('0', 10) + 1; // 1
The unary +
operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt()
is self-explanatory (converts into number, ignoring decimal places).
The second argument is necessary for parseInt()
to use the correct base when leading 0s are placed:
parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what
There's also parseFloat()
if you need to convert decimals in strings to their numeric value - +
can do that too but it behaves slightly differently: that's another story though.
Loop through all the files with a specific extension
No fancy tricks needed:
for i in *.java; do
[ -f "$i" ] || break
...
done
The guard ensures that if there are no matching files, the loop will exit without trying to process a non-existent file name *.java
. In bash
(or shells supporting something similar), you can use the nullglob
option
to simply ignore a failed match and not enter the body of the loop.
shopt -s nullglob
for i in *.java; do
...
done
automating telnet session using bash scripts
While I'd suggest using expect, too, for non-interactive use the normal shell commands might suffice. Telnet accepts its command on stdin, so you just need to pipe or write the commands into it:
telnet 10.1.1.1 <<EOF
remotecommand 1
remotecommand 2
EOF
(Edit: Judging from the comments, the remote command needs some time to process the inputs or the early SIGHUP is not taken gracefully by the telnet. In these cases, you might try a short sleep on the input:)
{ echo "remotecommand 1"; echo "remotecommand 2"; sleep 1; } | telnet 10.1.1.1
In any case, if it's getting interactive or anything, use expect
.
How can I read a large text file line by line using Java?
FileReader won't let you specify the encoding, use InputStreamReader
instead if you need to specify it:
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "Cp1252"));
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
If you imported this file from Windows, it might have ANSI encoding (Cp1252), so you have to specify the encoding.
html table span entire width?
you need to set the margin of the body to 0 for the table to stretch the full width. alternatively you can set the margin of the table to a negative number as well.
django no such table:
Updated answer for Django migrations without south
plugin:
Like T.T suggested in his answer, my previous answer was for south
migration plugin, when Django hasn't any schema migration features.
Now (works in Django 1.9+):
T.T wrote:
You can try this!
python manage.py makemigrations
python manage.py migrate --run-syncdb
Outdated for south
migrations plugin
As I can see you done it all in wrong order, to fix it up your should
complete this checklist (I assume you can't delete sqlite3 database
file to start over):
- Grab any SQLite GUI tool (i.e. http://sqliteadmin.orbmu2k.de/)
- Change your model definition to match database definition (best approach is to comment new fields)
- Delete
migrations
folder in your model
- Delete rows in
south_migrationhistory
table where app_name
match your application name (probably homework
)
- Invoke:
./manage.py schemamigration <app_name> --initial
- Create tables by
./manage.py migrate <app_name> --fake
(--fake
will skip SQL execute because table already exists in your database)
- Make changes to your app's model
- Invoke
./manage.py schemamigration <app_name> --auto
- Then apply changes to database:
./manage.py migrate <app_name>
Steps 7,8,9 repeat whenever your model needs any changes.
How to get the wsdl file from a webservice's URL
To download the wsdl from a url using Developer Command Prompt for Visual Studio, run it in Administrator mode and enter the following command:
svcutil /t:metadata http://[your-service-url-here]
You can now consume the downloaded wsdl in your project as you see fit.
Ineligible Devices section appeared in Xcode 6.x.x
There is a lot of options (10 23 29 answers for this question!), that can cause this error. And no one is 100% solve this issue. Here is summarise of all solutions.
First of all:
0. Update to latest Xcode version
Most of the reasons, that cause this problem fixed in Xcode version 6.3.1
(6D1002 published April 21, 2015)
List of solutions in order frequency of occurrence:
The most likely solution::
- In Xcode status go to:
Menu bar
-> Product
-> Destination
and find your device. It will be listed under Ineligible
section
- Select your device. After you will be able to build and deploy to device! (thanks, @joshstaiger)
If it doesn't work:
iOS Deployment Target should be <=
of the version of your device.
You find this option in Build Settings
tab when you click on a target of your project in Xcode.
If version is correct - try to restart Mac and iPhone/iPad simultaneously. It resolve this issue in most cases! (thanks, @HoaParis)
Finally if either doesn't work - try to do this magic actions:
- switch
iOS Deployment Target
to 8.1
- restart
Xcode
- switch back to desired version.
Other problems, that cause this issue:
Xcode Beta 6.3
does not support iOS 8.2
(and also 8.1). You won't see your iDevice in deploy target list.
Use Xcode 6.2
instead of Xcode 6.3 beta
in order to debug with an iDevice iOS 8.2
Xcode 6.3
requires Unity 4.6.4
If you're using an older Unity
version (e.g. 4.6.3
) you'll always get your devices in the Ineligible Devices
section (thanks, @d4rk)
Also it appears in case of changing name of Xcode project. The fix it - create a new scheme by selecting Manage Schemes > (+) button
. (thanks, @dale-moore)
Beta to Release upgrade of Xcode can require upgrading iOS or watchOS from beta to release version. For example, when switching from Xcode 8 beta 6 to Xcode 8 release, watchOS 3 beta is listed as unsupported.
webpack command not working
The quickest way, just to get this working is to use the web pack from another location, this will stop you having to install it globally or if npm run webpack
fails.
When you install webpack with npm it goes inside the "node_modules\.bin
" folder of your project.
in command prompt (as administrator)
- go to the location of the project where your webpack.config.js is located.
- in command prompt write the following
"C:\Users\..\ProjectName\node_modules\.bin\webpack" --config webpack.config.vendor.js
node.js hash string?
you can use crypto-js javaScript library of crypto standards, there is easiest way to generate sha256
or sha512
const SHA256 = require("crypto-js/sha256");
const SHA512 = require("crypto-js/sha512");
let password = "hello"
let hash_256 = SHA256 (password).toString();
let hash_512 = SHA512 (password).toString();
Number of visitors on a specific page
As Blexy already answered, go to "Behavior > Site Content > All Pages".
Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:
Where does mysql store data?
From here:
Windows
- Locate the my.ini, which store in the MySQL installation folder.
For Example, C:\Program Files\MySQL\MySQL Server 5.1\my.ini
- Open the “my.ini” with our favor text editor.
#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/Program Files/MySQL/MySQL Server 5.1/"
#Path to the database root
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.1/Data/"
Find the “datadir”
, this is the where does MySQL stored the data in Windows.
Linux
- Locate the my.cnf with the find / -name my.cnf command.
yongmo@myserver:~$ find / -name my.cnf
find: /home/lost+found: Permission denied
find: /lost+found: Permission denied
/etc/mysql/my.cnf
- View the
my.cnf
file like this: cat /etc/mysql/my.cnf
yongmo@myserver:~$ cat /etc/mysql/my.cnf
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
[mysqld]
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/english
skip-external-locking
- Find the
“datadir”
, this is where does MySQL stored the data in Linux system.
beyond top level package error in relative import
This is very tricky in Python.
I'll first comment on why you're having that problem and then I will mention two possible solutions.
You must take this paragraph from the Python documentation into consideration:
Note that relative imports are based on the name of the current
module. Since the name of the main module is always "main",
modules intended for use as the main module of a Python application
must always use absolute imports.
And also the following from PEP 328:
Relative imports use a module's name attribute to determine that
module's position in the package hierarchy. If the module's name does
not contain any package information (e.g. it is set to 'main')
then relative imports are resolved as if the module were a top level
module, regardless of where the module is actually located on the file
system.
Relative imports work from the filename (__name__
attribute), which can take two values:
- It's the filename, preceded by the folder strucutre, separated by dots.
For eg:
package.test_A.test
Here Python knows the parent directories: before test
comes test_A
and then package
.
So you can use the dot notation for relative import.
# package.test_A/test.py
from ..A import foo
You can then have like a root file in the root directory which calls test.py
:
# root.py
from package.test_A import test
- When you run the module (
test.py
) directly, it becomes the entry point to the program , so __name__
== __main__
. The filename has no indication of the directory structure, so Python doesn't know how to go up in the directory. For Python, test.py
becomes the top-level script, there is nothing above it. That's why you cannot use relative import.
A) One way to solve this is to have a root file (in the root directory) which calls the modules/packages, like this:
root.py
imports test.py
. (entry point, __name__ == __main__
).
test.py
(relative) imports foo.py
.
foo.py
says the module has been imported.
The output is:
package.A.foo has been imported
Module's name is: package.test_A.test
B) If you want to execute the code as a module and not as a top-level script, you can try this from the command line:
python -m package.test_A.test
Any suggestions are welcomed.
You should also check: Relative imports for the billionth time , specially BrenBarn's answer.
convert json ipython notebook(.ipynb) to .py file
well first of all you need to install this packege below:
sudo apt install ipython
jupyter nbconvert --to script [YOUR_NOTEBOOK].ipynb
two option is avaliable either --to python or --to=python
mine was like this works fine:
jupyter nbconvert --to python while.ipynb
jupyter nbconvert --to python while.ipynb
[NbConvertApp] Converting notebook while.ipynb to python
[NbConvertApp] Writing 758 bytes to while.py
pip3 install ipython
if it does not work for you try, by pip3.
pip3 install ipython
Explain the different tiers of 2 tier & 3 tier architecture?
First, we must make a distinction between layers and tiers. Layers are the way to logically break code into components and tiers are the physical nodes to place the components on. This question explains it better:
What's the difference between "Layers" and "Tiers"?
A two layer architecture is usually just a presentation layer and data store layer. These can be on 1 tier (1 machine) or 2 tiers (2 machines) to achieve better performance by distributing the work load.
A three layer architecture usually puts something between the presentation and data store layers such as a business logic layer or service layer. Again, you can put this into 1,2, or 3 tiers depending on how much money you have for hardware and how much load you expect.
Putting multiple machines in a tier will help with the robustness of the system by providing redundancy.
Below is a good example of a layered architecture:
(source: microsoft.com)
A good reference for all of this can be found here on MSDN:
http://msdn.microsoft.com/en-us/library/ms978678.aspx
Finishing current activity from a fragment
Try this. There shouldn't be any warning...
Activity thisActivity = getActivity();
if (thisActivity != null) {
startActivity(new Intent(thisActivity, yourActivity.class)); // if needed
thisActivity.finish();
}
htaccess remove index.php from url
The original answer is actually correct, but lacks explanation. I would like to add some explanations and modifications.
I suggest reading this short introduction https://httpd.apache.org/docs/2.4/rewrite/intro.html (15mins) and reference these 2 pages while reading.
https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html
https://httpd.apache.org/docs/2.4/rewrite/flags.html
This is the basic rule to hide index.php
from the URL. Put this in your root .htaccess
file.
mod_rewrite
must be enabled with PHP and this will work for the PHP version higher than 5.2.6.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /index.php/$1 [L]
Think %{REQUEST_FILENAME}
as the the path after host.
E.g. https://www.example.com/index.html
, %{REQUEST_FILENAME}
is /index.html
So the last 3 lines means, if it's not a regular file !-f
and not a directory !-d
, then do the RewriteRule
.
As for RewriteRule formats:
So RewriteRule (.*) /index.php/$1 [L]
means, if the 2 RewriteCond
are satisfied, it (.*)
would match everything after the hostname. .
matches any single character , .*
matches any characters and (.*)
makes this a variables can be references with $1
, then replace with /index.php/$1
. The final effect is to add a preceding index.php
to the whole URL path.
E.g. for https://www.example.com/hello
, it would produce, https://www.example.com/index.php/hello
internally.
Another key problem is that this indeed solve the question. Internally, (I guess) it always need https://www.example.com/index.php/hello
, but with rewriting, you could visit the site without index.php
, apache adds that for you internally.
Btw, making an extra .htaccess
file is not very recommended by the Apache doc.
Rewriting is typically configured in the main server configuration
setting (outside any <Directory>
section) or inside <VirtualHost>
containers. This is the easiest way to do rewriting and is recommended
Returning a value from callback function in Node.js
I am facing small trouble in returning a value from callback function in Node.js
This is not a "small trouble", it is actually impossible to "return" a value in the traditional sense from an asynchronous function.
Since you cannot "return the value" you must call the function that will need the value once you have it. @display_name already answered your question, but I just wanted to point out that the return in doCall is not returning the value in the traditional way. You could write doCall as follow:
function doCall(urlToCall, callback) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
// call the function that needs the value
callback(finalData);
// we are done
return;
});
}
Line callback(finalData);
is what calls the function that needs the value that you got from the async function. But be aware that the return statement is used to indicate that the function ends here, but it does not mean that the value is returned to the caller (the caller already moved on.)
Qt jpg image display
#include ...
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
QGraphicsPixmapItem item(QPixmap("c:\\test.png"));
scene.addItem(&item);
view.show();
return a.exec();
}
This should work. :) List of supported formats can be found here
Disable submit button ONLY after submit
$(document).ready(function() {
$(body).submit(function () {
var btn = $(this).find("input[type=submit]:focus");
if($(btn).prop("id") == "YourButtonID")
$(btn).attr("disabled", "true");
});
}
how to apply click event listener to image in android
In xml:
<ImageView
android:clickable="true"
android:onClick="imageClick"
android:src="@drawable/myImage">
</ImageView>
In code
public class Test extends Activity {
........
........
public void imageClick(View view) {
//Implement image click function
}
Having a UITextField in a UITableViewCell
Try this one. It can handle scrolling as well and you can reuse the cells without the hassle of removing subviews you added before.
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:@"Cell"];
if( cell == nil)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] autorelease];
cell.textLabel.text = [[NSArray arrayWithObjects:@"First",@"Second",@"Third",@"Forth",@"Fifth",@"Sixth",@"Seventh",@"Eighth",@"Nineth",@"Tenth",nil]
objectAtIndex:indexPath.row];
if (indexPath.row % 2) {
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 21)];
textField.placeholder = @"Enter Text";
textField.text = [inputTexts objectAtIndex:indexPath.row/2];
textField.tag = indexPath.row/2;
textField.delegate = self;
cell.accessoryView = textField;
[textField release];
} else
cell.accessoryView = nil;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
[inputTexts replaceObjectAtIndex:textField.tag withObject:textField.text];
return YES;
}
- (void)viewDidLoad {
inputTexts = [[NSMutableArray alloc] initWithObjects:@"",@"",@"",@"",@"",nil];
[super viewDidLoad];
}
disable a hyperlink using jQuery
The disabled
attribute isn't valid on all HTML elements I believe, see the MSDN article. That and the proper value for disabled is simply "disabled". Your best approach is to bind a click function that returns false.
window.history.pushState refreshing the browser
window.history.pushState({urlPath:'/page1'},"",'/page1')
Only works after page is loaded, and when you will click on refresh it doesn't mean that there is any real URL.
What you should do here is knowing to which URL you are getting redirected when you reload this page.
And on that page you can get the conditions by getting the current URL and making all of your conditions.
Python - How to convert JSON File to Dataframe
There are 2 inputs you might have and you can also convert between them.
- input: listOfDictionaries --> use @VikashSingh solution
example: [{"":{"...
The pd.DataFrame() needs a listOfDictionaries as input.
- input: jsonStr --> use @JustinMalinchak solution
example: '{"":{"...
If you have jsonStr, you need an extra step to listOfDictionaries first. This is obvious as it is generated like:
jsonStr = json.dumps(listOfDictionaries)
Thus, switch back from jsonStr to listOfDictionaries first:
listOfDictionaries = json.loads(jsonStr)
Hide strange unwanted Xcode logs
This solution has been working for me:
- Run the app in the simulator
- Open the system log (
?
+ /
)
This will dump out all of the debug data and also your NSLogs.
To filter just your NSLog statements:
- Prefix each with a symbol, for example:
NSLog(@"^ Test Log")
- Filter the results using the search box on the top right, "^" in the case above
This is what you should get:
Folder is locked and I can't unlock it
Using svn command line to unlock the local folders, just use svn cleanup
.
Before:
# svn commit -m "fixing #1234"
# svn st
# svn cleanup
After:
# svn st
# svn commit -m "fixing #1234"
Consistency of hashCode() on a Java string
If you're worried about changes and possibly incompatibly VMs, just copy the existing hashcode implementation into your own utility class, and use that to generate your hashcodes .
Return 0 if field is null in MySQL
Use IFNULL:
IFNULL(expr1, 0)
From the documentation:
If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.
How to append rows to an R data frame
Suppose you simply don't know the size of the data.frame in advance. It can well be a few rows, or a few millions. You need to have some sort of container, that grows dynamically. Taking in consideration my experience and all related answers in SO I come with 4 distinct solutions:
rbindlist
to the data.frame
Use data.table
's fast set
operation and couple it with manually doubling the table when needed.
Use RSQLite
and append to the table held in memory.
data.frame
's own ability to grow and use custom environment (which has reference semantics) to store the data.frame so it will not be copied on return.
Here is a test of all the methods for both small and large number of appended rows. Each method has 3 functions associated with it:
create(first_element)
that returns the appropriate backing object with first_element
put in.
append(object, element)
that appends the element
to the end of the table (represented by object
).
access(object)
gets the data.frame
with all the inserted elements.
rbindlist
to the data.frame
That is quite easy and straight-forward:
create.1<-function(elems)
{
return(as.data.table(elems))
}
append.1<-function(dt, elems)
{
return(rbindlist(list(dt, elems),use.names = TRUE))
}
access.1<-function(dt)
{
return(dt)
}
data.table::set
+ manually doubling the table when needed.
I will store the true length of the table in a rowcount
attribute.
create.2<-function(elems)
{
return(as.data.table(elems))
}
append.2<-function(dt, elems)
{
n<-attr(dt, 'rowcount')
if (is.null(n))
n<-nrow(dt)
if (n==nrow(dt))
{
tmp<-elems[1]
tmp[[1]]<-rep(NA,n)
dt<-rbindlist(list(dt, tmp), fill=TRUE, use.names=TRUE)
setattr(dt,'rowcount', n)
}
pos<-as.integer(match(names(elems), colnames(dt)))
for (j in seq_along(pos))
{
set(dt, i=as.integer(n+1), pos[[j]], elems[[j]])
}
setattr(dt,'rowcount',n+1)
return(dt)
}
access.2<-function(elems)
{
n<-attr(elems, 'rowcount')
return(as.data.table(elems[1:n,]))
}
SQL should be optimized for fast record insertion, so I initially had high hopes for RSQLite
solution
This is basically copy&paste of Karsten W. answer on similar thread.
create.3<-function(elems)
{
con <- RSQLite::dbConnect(RSQLite::SQLite(), ":memory:")
RSQLite::dbWriteTable(con, 't', as.data.frame(elems))
return(con)
}
append.3<-function(con, elems)
{
RSQLite::dbWriteTable(con, 't', as.data.frame(elems), append=TRUE)
return(con)
}
access.3<-function(con)
{
return(RSQLite::dbReadTable(con, "t", row.names=NULL))
}
data.frame
's own row-appending + custom environment.
create.4<-function(elems)
{
env<-new.env()
env$dt<-as.data.frame(elems)
return(env)
}
append.4<-function(env, elems)
{
env$dt[nrow(env$dt)+1,]<-elems
return(env)
}
access.4<-function(env)
{
return(env$dt)
}
The test suite:
For convenience I will use one test function to cover them all with indirect calling. (I checked: using do.call
instead of calling the functions directly doesn't makes the code run measurable longer).
test<-function(id, n=1000)
{
n<-n-1
el<-list(a=1,b=2,c=3,d=4)
o<-do.call(paste0('create.',id),list(el))
s<-paste0('append.',id)
for (i in 1:n)
{
o<-do.call(s,list(o,el))
}
return(do.call(paste0('access.', id), list(o)))
}
Let's see the performance for n=10 insertions.
I also added a 'placebo' functions (with suffix 0
) that don't perform anything - just to measure the overhead of the test setup.
r<-microbenchmark(test(0,n=10), test(1,n=10),test(2,n=10),test(3,n=10), test(4,n=10))
autoplot(r)
For 1E5 rows (measurements done on Intel(R) Core(TM) i7-4710HQ CPU @ 2.50GHz):
nr function time
4 data.frame 228.251
3 sqlite 133.716
2 data.table 3.059
1 rbindlist 169.998
0 placebo 0.202
It looks like the SQLite-based sulution, although regains some speed on large data, is nowhere near data.table + manual exponential growth. The difference is almost two orders of magnitude!
Summary
If you know that you will append rather small number of rows (n<=100), go ahead and use the simplest possible solution: just assign the rows to the data.frame using bracket notation and ignore the fact that the data.frame is not pre-populated.
For everything else use data.table::set
and grow the data.table exponentially (e.g. using my code).
How to pass Multiple Parameters from ajax call to MVC Controller
I did that with helping from this question
jquery get querystring from URL
so let see how
we will use this function
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
and now just use it in Ajax call
"ajax": {
url: '/Departments/GetAllDepartments/',
type: 'GET',
dataType: 'json',
data: getUrlVars()// here is the tricky part
},
thats all, but if you want know how to use this function
or not send all the query string parameters
back to actual answer
How do I check if an integer is even or odd?
In the "creative but confusing category" I offer:
int isOdd(int n) { return n ^ n * n ? isOdd(n * n) : n; }
A variant on this theme that is specific to Microsoft C++:
__declspec(naked) bool __fastcall isOdd(const int x)
{
__asm
{
mov eax,ecx
mul eax
mul eax
mul eax
mul eax
mul eax
mul eax
ret
}
}
Difference between Running and Starting a Docker container
This is a very important question and the answer is very simple, but fundamental:
- Run: create a new container of an image, and execute the container. You can create N clones of the same image. The command is:
docker run IMAGE_ID
and not docker run CONTAINER_ID
- Start: Launch a container previously stopped. For example, if you had stopped a database with the command
docker stop CONTAINER_ID
, you can relaunch the same container with the command docker start CONTAINER_ID
, and the data and settings will be the same.
NHibernate.MappingException: No persister for: XYZ
Sounds like you forgot to add a mapping assembly to the session factory configuration..
If you're using app.config...
.
.
<property name="show_sql">true</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<mapping assembly="Project.DomainModel"/> <!-- Here -->
</session-factory>
.
.
How do I mock an open used in a with statement (using the Mock framework in Python)?
With the latest versions of mock, you can use the really useful mock_open helper:
mock_open(mock=None, read_data=None)
A helper function to create a
mock to replace the use of open. It works for open called directly or
used as a context manager.
The mock argument is the mock object to configure. If None (the
default) then a MagicMock will be created for you, with the API
limited to methods or attributes available on standard file handles.
read_data is a string for the read method of the file handle to
return. This is an empty string by default.
>>> from mock import mock_open, patch
>>> m = mock_open()
>>> with patch('{}.open'.format(__name__), m, create=True):
... with open('foo', 'w') as h:
... h.write('some stuff')
>>> m.assert_called_once_with('foo', 'w')
>>> handle = m()
>>> handle.write.assert_called_once_with('some stuff')
Reading an integer from user input
I would suggest you use TryParse
:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
string input = Console.ReadLine();
int number;
Int32.TryParse(input, out number);
This way, your application does not throw an exception, if you try to parse something like "1q" or "23e", because somebody made a faulty input.
Int32.TryParse
returns a boolean value, so you can use it in an if
statement, to see whether or not you need to branch of your code:
int number;
if(!Int32.TryParse(input, out number))
{
//no, not able to parse, repeat, throw exception, use fallback value?
}
To your question: You will not find a solution to read an integer because ReadLine()
reads the whole command line, threfor returns a string. What you can do is, try to convert this input into and int16/32/64 variable.
There are several methods for this:
If you are in doubt about the input, which is to be converted, always go for the TryParse methods, no matter if you try to parse strings, int variable or what not.
Update
In C# 7.0 out variables can be declared directly where they are passed in as an argument, so the above code could be condensed into this:
if(Int32.TryParse(input, out int number))
{
/* Yes input could be parsed and we can now use number in this code block
scope */
}
else
{
/* No, input could not be parsed to an integer */
}
A complete example would look like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var foo = Console.ReadLine();
if (int.TryParse(foo, out int number1)) {
Console.WriteLine($"{number1} is a number");
}
else
{
Console.WriteLine($"{foo} is not a number");
}
Console.WriteLine($"The value of the variable {nameof(number1)} is {number1}");
Console.ReadLine();
}
}
Here you can see, that the variable number1
does get initialized even if the input is not a number and has the value 0 regardless, so it is valid even outside the declaring if block
git - pulling from specific branch
Here are the steps to pull a specific or any branch,
1.clone the master(you need to provide username and password)
git clone <url>
2. the above command will clone the repository and you will be master branch now
git checkout <branch which is present in the remote repository(origin)>
3. The above command will checkout to the branch you want to pull and will be set to automatically track that branch
4.If for some reason it does not work like that, after checking out to that branch in your local system, just run the below command
git pull origin <branch>
Tracking Google Analytics Page Views with AngularJS
The best way to do this is using Google Tag Manager to fire your Google Analytics tags based on history listeners. These are built in to the GTM interface and easily allow tracking on client side HTML5 interactions .
Enable the built in History variables and create a trigger to fire an event based on history changes.
Reading RFID with Android phones
I recently worked on a project to read the RFID tags.
The project used the Devices from manufacturers like Zebra (we were using RFD8500 ) & TSL.
More devices are from Motorola & other vendors as well!
We have to use the native SDK api's provided by the manufacturer, how it works is by pairing the device by the Bluetooth of the phones and so the data transfer between both devices take place! The programming is based on subscribe pattern where the scan should be read by the device trigger(hardware trigger) or soft trigger (from the application).
The Tag read gives us the tagId & the RSSI which is the distance factor from the RFID tags!
This is the sample app:
We get all the device paired to our Android/iOS phones :
Returning a regex match in VBA (excel)
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
How to align the checkbox and label in same line in html?
Another approach here:
.checkbox-wrapper {
white-space: nowrap
}
.checkbox {
vertical-align: top;
display:inline-block
}
.checkbox-label {
white-space: normal
display:inline-block
}
<div class="text-left checkbox-wrapper">
<input type="checkbox" id="terms" class="checkbox">
<label class="checkbox-label" for="terms">I accept whatever you want!</label>
</div>
Insert json file into mongodb
This worked for me - ( from mongo shell )
var file = cat('./new.json'); # file name
use testdb # db name
var o = JSON.parse(file); # convert string to JSON
db.forms.insert(o) # collection name
How to add bootstrap to an angular-cli project
Install bootstrap
npm install bootstrap@next
Add code to .angular-cli.json:
"styles": [
"styles.css",
"../node_modules/bootstrap/dist/css/bootstrap.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/tether/dist/js/tether.js",
"../node_modules/bootstrap/dist/js/bootstrap.js"
],
Last add bootstrap.css to your code style.scss
@import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
Restart your local server
How do I get the n-th level parent of an element in jQuery?
using eq appears to grab the dynamic DOM whereas using .parent().parent() appears to grab the DOM that was initially loaded (if that is even possible).
I use them both on an element that has classes applied it to on onmouseover. eq shows the classes while .parent().parent() doesnt.
What is the best way to conditionally apply a class?
I'll add to this, because some of these answers seem out of date. Here's how I do it:
<class="ng-class:isSelected">
Where 'isSelected' is a javascript variable defined within the scoped angular controller.
To more specifically address your question, here's how you might generate a list with that:
HTML
<div ng-controller="ListCtrl">
<li class="ng-class:item.isSelected" ng-repeat="item in list">
{{item.name}}
</li>
</div>
JS
function ListCtrl($scope) {
$scope.list = [
{"name": "Item 1", "isSelected": "active"},
{"name": "Item 2", "isSelected": ""}
]
}
See: http://jsfiddle.net/tTfWM/
See: http://docs.angularjs.org/api/ng.directive:ngClass
How can I get the error message for the mail() function?
Try this. If I got any error on any file then I got error mail on my email id. Create two files index.php
and checkErrorEmail.php
and uploaded them to your server. Then load index.php
with your browser.
Index.php
<?php
include('checkErrorEmail.php');
include('dereporting.php');
$temp;
echo 'hi '.$temp;
?>
checkErrorEmail.php
<?php
// Destinations
define("ADMIN_EMAIL", "[email protected]");
//define("LOG_FILE", "/my/home/errors.log");
// Destination types
define("DEST_EMAIL", "1");
//define("DEST_LOGFILE", "3");
/* Examples */
// Send an e-mail to the administrator
//error_log("Fix me!", DEST_EMAIL, ADMIN_EMAIL);
// Write the error to our log file
//error_log("Error", DEST_LOGFILE, LOG_FILE);
/**
* my_error_handler($errno, $errstr, $errfile, $errline)
*
* Author(s): thanosb, ddonahue
* Date: May 11, 2008
*
* custom error handler
*
* Parameters:
* $errno: Error level
* $errstr: Error message
* $errfile: File in which the error was raised
* $errline: Line at which the error occurred
*/
function my_error_handler($errno, $errstr, $errfile, $errline)
{
echo "<br><br><br><br>errno ".$errno.",<br>errstr ".$errstr.",<br>errfile ".$errfile.",<br>errline ".$errline;
if($errno)
{
error_log("Error: $errstr \n error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);
}
/*switch ($errno) {
case E_USER_ERROR:
// Send an e-mail to the administrator
error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);
// Write the error to our log file
//error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_LOGFILE, LOG_FILE);
break;
case E_USER_WARNING:
// Write the error to our log file
//error_log("Warning: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;
case E_USER_NOTICE:
// Write the error to our log file
// error_log("Notice: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;
default:
// Write the error to our log file
//error_log("Unknown error [#$errno]: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;
}*/
// Don't execute PHP's internal error handler
return TRUE;
}
// Use set_error_handler() to tell PHP to use our method
$old_error_handler = set_error_handler("my_error_handler");
?>
How to use glyphicons in bootstrap 3.0
If you are using grunt to build your application, it's possible that during build the paths change. In this case you need to modify your grunt file like this:
copy: {
main: {
files: [{
src: ['fonts/**'],
dest: 'dist/fonts/',
filter: 'isFile',
expand: true,
flatten: true
}, {
src: ['bower_components/font-awesome/fonts/**'],
dest: 'dist/css/',
filter: 'isFile',
expand: true,
flatten: false
}]
}
},
org.hibernate.NonUniqueResultException: query did not return a unique result: 2?
Generally This exception is thrown from Oracle when query result (which is stored in an Object in your case), can not be cast to the desired object.
for example when result is a
List<T>
and you're putting the result into a single T object.
In case of casting to long error, besides it is recommended to use wrapper classes so that all of your columns act the same, I guess a problem in transaction or query itself would cause this issue.
Count number of objects in list
Advice for R
newcomers like me : beware, the following is a list of a single object :
> mylist <- list (1:10)
> length (mylist)
[1] 1
In such a case you are not looking for the length of the list, but of its first element :
> length (mylist[[1]])
[1] 10
This is a "true" list :
> mylist <- list(1:10, rnorm(25), letters[1:3])
> length (mylist)
[1] 3
Also, it seems that R
considers a data.frame as a list :
> df <- data.frame (matrix(0, ncol = 30, nrow = 2))
> typeof (df)
[1] "list"
In such a case you may be interested in ncol()
and nrow()
rather than length()
:
> ncol (df)
[1] 30
> nrow (df)
[1] 2
Though length()
will also work (but it's a trick when your data.frame has only one column) :
> length (df)
[1] 30
> length (df[[1]])
[1] 2
How to convert a byte to its binary string representation
You could check each bit on the byte then append either 0 or 1 to a string. Here is a little helper method I wrote for testing:
public static String byteToString(byte b) {
byte[] masks = { -128, 64, 32, 16, 8, 4, 2, 1 };
StringBuilder builder = new StringBuilder();
for (byte m : masks) {
if ((b & m) == m) {
builder.append('1');
} else {
builder.append('0');
}
}
return builder.toString();
}
Bash function to find newest file matching pattern
There is a much more efficient way of achieving this. Consider the following command:
find . -cmin 1 -name "b2*"
This command finds the latest file produced exactly one minute ago with the wildcard search on "b2*". If you want files from the last two days then you'll be better off using the command below:
find . -mtime 2 -name "b2*"
The "." represents the current directory.
Hope this helps.
Convert JS date time to MySQL datetime
JS time value for MySQL
var datetime = new Date().toLocaleString();
OR
const DATE_FORMATER = require( 'dateformat' );
var datetime = DATE_FORMATER( new Date(), "yyyy-mm-dd HH:MM:ss" );
OR
const MOMENT= require( 'moment' );
let datetime = MOMENT().format( 'YYYY-MM-DD HH:mm:ss.000' );
you can send this in params its will work.
Uncaught ReferenceError: $ is not defined error in jQuery
Change the order you're including your scripts (jQuery first):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>
C++ code file extension? .cc vs .cpp
I personally use .cc
extension for implementation files, .hh
for headers, and .inl
for inline/templates.
As said before, it is mainly a matter of taste.
From what I've seen, .cc
seems to be more "open source projects oriented", as it is advised in some great open source software coding styles, whereas .cpp
seems to be more Windowish.
--- EDIT
As mentioned, this is "from what i've seen", it may be wrong.
It's just that all Windows projects I've worked on used .cpp
, and a lot of open source projects (which are mainly on unix-likes) use .cc
.
Examples coding styles using .cc
:
ggplot2: sorting a plot
This seems to be what you're looking for:
g <- ggplot(x, aes(reorder(variable, value), value))
g + geom_bar() + scale_y_continuous(formatter="percent") + coord_flip()
The reorder()
function will reorder your x axis items according to the value
of variable
.
How to use cookies in Python Requests
Summary (@Freek Wiekmeijer, @gtalarico) other's answer:
Logic of Login
- Many resource(pages, api) need
authentication
, then can access, otherwise 405 Not Allowed
- Common
authentication
=grant access
method are:
cookie
auth header
Basic xxx
Authorization xxx
How use cookie
in requests
to auth
- first get/generate cookie
- send cookie for following request
- manual set
cookie
in headers
- auto process
cookie
by requests
's
session
to auto manage cookies
response.cookies
to manually set cookies
use requests
's session
auto manage cookies
curSession = requests.Session()
# all cookies received will be stored in the session object
payload={'username': "yourName",'password': "yourPassword"}
curSession.post(firstUrl, data=payload)
# internally return your expected cookies, can use for following auth
# internally use previously generated cookies, can access the resources
curSession.get(secondUrl)
curSession.get(thirdUrl)
manually control requests
's response.cookies
payload={'username': "yourName",'password': "yourPassword"}
resp1 = requests.post(firstUrl, data=payload)
# manually pass previously returned cookies into following request
resp2 = requests.get(secondUrl, cookies= resp1.cookies)
resp3 = requests.get(thirdUrl, cookies= resp2.cookies)
No ConcurrentList<T> in .Net 4.0?
System.Collections.Generic.List<t>
is already thread safe for multiple readers. Trying to make it thread safe for multiple writers wouldn't make sense. (For reasons Henk and Stephen already mentioned)
rotating axis labels in R
As Maciej Jonczyk mentioned, you may also need to increase margins
par(las=2)
par(mar=c(8,8,1,1)) # adjust as needed
plot(...)
Bootstrap button - remove outline on Chrome OS X
In the mixins of the Bootstrap sources Sass files, remove all $border
references (not in the outline variant).
@mixin button-variant($color, $background, $border){
$active-background: darken($background, 10%);
//$active-border: darken($border, 12%);
color: $color;
background-color: $background;
//border-color: $border;
@include box-shadow($btn-box-shadow);
[...]
}
Or simply code you own _customButton.scss mixin.
How to redirect the output of an application in background to /dev/null
You use:
yourcommand > /dev/null 2>&1
If it should run in the Background add an &
yourcommand > /dev/null 2>&1 &
>/dev/null 2>&1
means redirect stdout
to /dev/null
AND stderr
to the place where stdout
points at that time
If you want stderr
to occur on console and only stdout
going to /dev/null
you can use:
yourcommand 2>&1 > /dev/null
In this case stderr
is redirected to stdout
(e.g. your console) and afterwards the original stdout
is redirected to /dev/null
If the program should not terminate you can use:
nohup yourcommand &
Without any parameter all output lands in nohup.out
How can I dynamically switch web service addresses in .NET without a recompile?
Definitely using the Url property is the way to go. Whether to set it in the app.config, the database, or a third location sort of depends on your configuration needs. Sometimes you don't want the app to restart when you change the web service location. You might not have a load balancer scaling the backend. You might be hot-patching a web service bug. Your implementation might have security configuration issues as well. Whether it's production db usernames and passwords or even the ws security auth info. The proper separation of duties can get you into some more involved configuration setups.
If you add a wrapper class around the proxy generated classes, you can set the Url property in some unified fashion every time you create the wrapper class to call a web method.
What does "if (rs.next())" mean?
Since Result Set is an interface, When you obtain a reference to a ResultSet through a JDBC call, you are getting an instance of a class that implements the ResultSet interface. This class provides concrete implementations of all of the ResultSet methods.
Interfaces are used to divorce implementation from, well, interface. This allows the creation of generic algorithms and the abstraction of object creation. For example, JDBC drivers for different databases will return different ResultSet implementations, but you don't have to change your code to make it work with the different drivers
In very short, if your ResultSet contains result, then using rs.next return true if you have recordset else it returns false.
Hash and salt passwords in C#
create proc [dbo].[hash_pass] @family nvarchar(50), @username nvarchar(50), @pass nvarchar(Max),``` @semat nvarchar(50), @tell nvarchar(50)
as insert into tbl_karbar values (@family,@username,(select HASHBYTES('SHA1' ,@pass)),@semat,@tell)
Drag and drop menuitems
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
Unstaged changes left after git reset --hard
Git won't reset files that aren't on repository. So, you can:
$ git add .
$ git reset --hard
This will stage all changes, which will cause Git to be aware of those files, and then reset them.
If this does not work, you can try to stash and drop your changes:
$ git stash
$ git stash drop
When to use extern in C++
It is useful when you share a variable between a few modules. You define it in one module, and use extern in the others.
For example:
in file1.cpp:
int global_int = 1;
in file2.cpp:
extern int global_int;
//in some function
cout << "global_int = " << global_int;
How to detect if multiple keys are pressed at once using JavaScript?
for who needs complete example code. Right+Left added
var keyPressed = {};
document.addEventListener('keydown', function(e) {
keyPressed[e.key + e.location] = true;
if(keyPressed.Shift1 == true && keyPressed.Control1 == true){
// Left shift+CONTROL pressed!
keyPressed = {}; // reset key map
}
if(keyPressed.Shift2 == true && keyPressed.Control2 == true){
// Right shift+CONTROL pressed!
keyPressed = {};
}
}, false);
document.addEventListener('keyup', function(e) {
keyPressed[e.key + e.location] = false;
keyPressed = {};
}, false);
Select row with most recent date per user
select result from (
select vorsteuerid as result, count(*) as anzahl from kreditorenrechnung where kundeid = 7148
group by vorsteuerid
) a order by anzahl desc limit 0,1
Why shouldn't I use "Hungarian Notation"?
Joel is wrong, and here is why.
That "application" information he's talking about should be encoded in the type system. You should not depend on flipping variable names to make sure you don't pass unsafe data to functions requiring safe data. You should make it a type error, so that it is impossible to do so. Any unsafe data should have a type that is marked unsafe, so that it simply cannot be passed to a safe function. To convert from unsafe to safe should require processing with some kind of a sanitize function.
A lot of the things that Joel talks of as "kinds" are not kinds; they are, in fact, types.
What most languages lack, however, is a type system that's expressive enough to enforce these kind of distinctions. For example, if C had a kind of "strong typedef" (where the typedef name had all the operations of the base type, but was not convertible to it) then a lot of these problems would go away. For example, if you could say, strong typedef std::string unsafe_string;
to introduce a new type unsafe_string
that could not be converted to a std::string (and so could participate in overload resolution etc. etc.) then we would not need silly prefixes.
So, the central claim that Hungarian is for things that are not types is wrong. It's being used for type information. Richer type information than the traditional C type information, certainly; it's type information that encodes some kind of semantic detail to indicate the purpose of the objects. But it's still type information, and the proper solution has always been to encode it into the type system. Encoding it into the type system is far and away the best way to obtain proper validation and enforcement of the rules. Variables names simply do not cut the mustard.
In other words, the aim should not be "make wrong code look wrong to the developer". It should be "make wrong code look wrong to the compiler".
How to restrict the selectable date ranges in Bootstrap Datepicker?
With selectable date ranges you might want to use something like this. My solution prevents selecting #from_date bigger than #to_date and changes #to_date startDate every time when user selects new date in #from_date box:
http://bootply.com/74352
JS file:
var startDate = new Date('01/01/2012');
var FromEndDate = new Date();
var ToEndDate = new Date();
ToEndDate.setDate(ToEndDate.getDate()+365);
$('.from_date').datepicker({
weekStart: 1,
startDate: '01/01/2012',
endDate: FromEndDate,
autoclose: true
})
.on('changeDate', function(selected){
startDate = new Date(selected.date.valueOf());
startDate.setDate(startDate.getDate(new Date(selected.date.valueOf())));
$('.to_date').datepicker('setStartDate', startDate);
});
$('.to_date')
.datepicker({
weekStart: 1,
startDate: startDate,
endDate: ToEndDate,
autoclose: true
})
.on('changeDate', function(selected){
FromEndDate = new Date(selected.date.valueOf());
FromEndDate.setDate(FromEndDate.getDate(new Date(selected.date.valueOf())));
$('.from_date').datepicker('setEndDate', FromEndDate);
});
HTML:
<input class="from_date" placeholder="Select start date" contenteditable="false" type="text">
<input class="to_date" placeholder="Select end date" contenteditable="false" type="text"
And do not forget to include bootstrap datepicker.js and .css files aswell.
How to print an exception in Python 3?
I've use this :
except (socket.timeout, KeyboardInterrupt) as e:
logging.debug("Exception : {}".format(str(e.__str__).split(" ")[3]))
break
Let me know if it does not work for you !!
How does `scp` differ from `rsync`?
One major feature of rsync
over scp
(beside the delta algorithm and encryption if used w/ ssh) is that it automatically verifies if the transferred file has been transferred correctly. Scp will not do that, which occasionally might result in corruption when transferring larger files. So in general rsync is a copy with guarantee.
Centos manpages mention this the end of the --checksum
option description:
Note that rsync always verifies that each transferred file was
correctly reconstructed on the receiving side by checking a whole-file
checksum that is generated as the file is transferred, but that
automatic after-the-transfer verification has nothing to do with this
option’s before-the-transfer “Does this file need to be updated?”
check.
How to create a circle icon button in Flutter?
I used this one because I like the customisation of the border-radius and size.
Material( // pause button (round)
borderRadius: BorderRadius.circular(50), // change radius size
color: Colors.blue, //button colour
child: InkWell(
splashColor: Colors.blue[900], // inkwell onPress colour
child: SizedBox(
width: 35,height: 35, //customisable size of 'button'
child: Icon(Icons.pause,color: Colors.white,size: 16,),
),
onTap: () {}, // or use onPressed: () {}
),
),
Material( // eye button (customised radius)
borderRadius: BorderRadius.only(
topRight: Radius.circular(10.0),
bottomLeft: Radius.circular(50.0),),
color: Colors.blue,
child: InkWell(
splashColor: Colors.blue[900], // inkwell onPress colour
child: SizedBox(
width: 40, height: 40, //customisable size of 'button'
child: Icon(Icons.remove_red_eye,color: Colors.white,size: 16,),),
onTap: () {}, // or use onPressed: () {}
),
),
How do I get the file name from a String containing the Absolute file path?
Considering the String
you're asking about is
C:\Hello\AnotherFolder\The File Name.PDF
we need to extract everything after the last separator, ie. \
. That is what we are interested in.
You can do
String fullPath = "C:\\Hello\\AnotherFolder\\The File Name.PDF";
int index = fullPath.lastIndexOf("\\");
String fileName = fullPath.substring(index + 1);
This will retrieve the index of the last \
in your String
and extract everything that comes after it into fileName
.
If you have a String
with a different separator, adjust the lastIndexOf
to use that separator. (There's even an overload that accepts an entire String
as a separator.)
I've omitted it in the example above, but if you're unsure where the String
comes from or what it might contain, you'll want to validate that the lastIndexOf
returns a non-negative value because the Javadoc states it'll return
-1 if there is no such occurrence
Convert text to columns in Excel using VBA
Try this
Sub Txt2Col()
Dim rng As Range
Set rng = [C7]
Set rng = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))
rng.TextToColumns Destination:=rng, DataType:=xlDelimited, ' rest of your settings
Update: button click event to act on another sheet
Private Sub CommandButton1_Click()
Dim rng As Range
Dim sh As Worksheet
Set sh = Worksheets("Sheet2")
With sh
Set rng = .[C7]
Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp))
rng.TextToColumns Destination:=rng, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=False, _
Comma:=True,
Space:=False,
Other:=False, _
FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
TrailingMinusNumbers:=True
End With
End Sub
Note the .
's (eg .Range
) they refer to the With
statement object
How to undo a SQL Server UPDATE query?
If you already have a full backup from your database, fortunately, you have an option in SQL Management Studio. In this case, you can use the following steps:
Right click on database -> Tasks -> Restore -> Database.
In General tab, click on Timeline -> select Specific date and time option.
Move the timeline slider to before update command time -> click OK.
In the destination database name, type a new name.
In the Files tab, check in Reallocate all files to folder and then select a new path to save your recovered database.
In the options tab, check in Overwrite ... and remove Take tail-log... check option.
Finally, click on OK and wait until the recovery process is over.
I have used this method myself in an operational database and it was very useful.
Controller not a function, got undefined, while defining controllers globally
I just migrate to angular 1.3.3 and I found that If I had multiple controllers in different files when app is override and I lost first declared containers.
I don't know if is a good practise, but maybe can be helpful for another one.
var app = app;
if(!app) {
app = angular.module('web', ['ui.bootstrap']);
}
app.controller('SearchCtrl', SearchCtrl);
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
Get div to take up 100% body height, minus fixed-height header and footer
Here's a solution that doesn't use negative margins or calc
. Run the snippet below to see the final result.
Explanation
We give the header and the footer a fixed height of 30px
and position them absolutely at the top and bottom, respectively. To prevent the content from falling underneath, we use two classes: below-header
and above-footer
to pad the div above and below with 30px
.
All of the content is wrapped in a position: relative
div so that the header and footer are at the top/bottom of the content and not the window.
We use the classes fit-to-parent
and min-fit-to-parent
to make the content fill out the page. This gives us a sticky footer which is at least as low as the window, but hidden if the content is longer than the window.
Inside the header and footer, we use the display: table
and display: table-cell
styles to give the header and footer some vertical padding without disrupting the shrink-wrap quality of the page. (Giving them real padding can cause the total height of the page to be more than 100%
, which causes a scroll bar to appear when it isn't really needed.)
_x000D_
_x000D_
.fit-parent {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
.min-fit-parent {_x000D_
min-height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
.below-header {_x000D_
padding-top: 30px;_x000D_
}_x000D_
.above-footer {_x000D_
padding-bottom: 30px;_x000D_
}_x000D_
.header {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
height: 30px;_x000D_
width: 100%;_x000D_
}_x000D_
.footer {_x000D_
position: absolute;_x000D_
bottom: 0;_x000D_
height: 30px;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
/* helper classes */_x000D_
_x000D_
.padding-lr-small {_x000D_
padding: 0 5px;_x000D_
}_x000D_
.relative {_x000D_
position: relative;_x000D_
}_x000D_
.auto-scroll {_x000D_
overflow: auto;_x000D_
}_x000D_
/* these two classes work together to create vertical centering */_x000D_
.valign-outer {_x000D_
display: table;_x000D_
}_x000D_
.valign-inner {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<html class='fit-parent'>_x000D_
<body class='fit-parent'>_x000D_
<div class='min-fit-parent auto-scroll relative' style='background-color: lightblue'>_x000D_
<div class='header valign-outer' style='background-color: black; color: white;'>_x000D_
<div class='valign-inner padding-lr-small'>_x000D_
My webpage_x000D_
</div>_x000D_
</div>_x000D_
<div class='fit-parent above-footer below-header'>_x000D_
<div class='fit-parent' id='main-inner'>_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
</div>_x000D_
</div>_x000D_
<div class='footer valign-outer' style='background-color: white'>_x000D_
<div class='valign-inner padding-lr-small'>_x000D_
© 2005 Old Web Design_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
Android: remove left margin from actionbar's custom layout
The left inset is caused by Toolbar's contentInsetStart
which by default is 16dp.
Change this to align to the keyline.
Update for support library v24.0.0:
To match the Material Design spec there's an additional attribute contentInsetStartWithNavigation
which by default is 16dp. Change this if you also have a navigation icon.
It turned out that this is part of a new Material Design Specification introduced in version 24 of Design library.
https://material.google.com/patterns/navigation.html
However, it is possible to remove the extra space by adding the following property to Toolbar widget.
app:contentInsetStartWithNavigation="0dp"
Before :
After :
PG COPY error: invalid input syntax for integer
Just came across this while looking for a solution and wanted to add I was able to solve the issue by adding the "null" parameter to the copy_from call:
cur.copy_from(f, tablename, sep=',', null='')
What's the best strategy for unit-testing database-driven applications?
I use the first (running the code against a test database). The only substantive issue I see you raising with this approach is the possibilty of schemas getting out of sync, which I deal with by keeping a version number in my database and making all schema changes via a script which applies the changes for each version increment.
I also make all changes (including to the database schema) against my test environment first, so it ends up being the other way around: After all tests pass, apply the schema updates to the production host. I also keep a separate pair of testing vs. application databases on my development system so that I can verify there that the db upgrade works properly before touching the real production box(es).
Plot logarithmic axes with matplotlib in python
You can use the Axes.set_yscale
method. That allows you to change the scale after the Axes
object is created. That would also allow you to build a control to let the user pick the scale if you needed to.
The relevant line to add is:
ax.set_yscale('log')
You can use 'linear'
to switch back to a linear scale. Here's what your code would look like:
import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)
line, = ax.plot(a, color='blue', lw=2)
ax.set_yscale('log')
pylab.show()
Redirect stdout to a file in Python?
Quoted from PEP 343 -- The "with" Statement (added import statement):
Redirect stdout temporarily:
import sys
from contextlib import contextmanager
@contextmanager
def stdout_redirected(new_stdout):
save_stdout = sys.stdout
sys.stdout = new_stdout
try:
yield None
finally:
sys.stdout = save_stdout
Used as follows:
with open(filename, "w") as f:
with stdout_redirected(f):
print "Hello world"
This isn't thread-safe, of course, but neither is doing this same dance manually. In single-threaded programs (for example in scripts) it is a popular way of doing things.
Simulation of CONNECT BY PRIOR of Oracle in SQL Server
@Alex Martelli
's answer is great!
But it work only for one element at time (WHERE name = 'Joan'
)
If you take out the WHERE
clause, the query will return all the root rows together...
I changed a little bit for my situation, so it can show the entire tree for a table.
table definition:
CREATE TABLE [dbo].[mar_categories] (
[category] int IDENTITY(1,1) NOT NULL,
[name] varchar(50) NOT NULL,
[level] int NOT NULL,
[action] int NOT NULL,
[parent] int NULL,
CONSTRAINT [XPK_mar_categories] PRIMARY KEY([category])
)
(level
is literally the level of a category 0: root, 1: first level after root, ...)
and the query:
WITH n(category, name, level, parent, concatenador) AS
(
SELECT category, name, level, parent, '('+CONVERT(VARCHAR (MAX), category)+' - '+CONVERT(VARCHAR (MAX), level)+')' as concatenador
FROM mar_categories
WHERE parent is null
UNION ALL
SELECT m.category, m.name, m.level, m.parent, n.concatenador+' * ('+CONVERT (VARCHAR (MAX), case when ISNULL(m.parent, 0) = 0 then 0 else m.category END)+' - '+CONVERT(VARCHAR (MAX), m.level)+')' as concatenador
FROM mar_categories as m, n
WHERE n.category = m.parent
)
SELECT distinct * FROM n ORDER BY concatenador asc
(You don't need to concatenate the level
field, I did just to make more readable)
the answer for this query should be something like:
I hope it helps someone!
now, I'm wondering how to do this on MySQL... ^^
constant pointer vs pointer on a constant value
char * const a;
*a
is writable, but a
is not; in other words, you can modify the value pointed to by a
, but you cannot modify a
itself. a
is a constant pointer to char
.
const char * a;
a
is writable, but *a
is not; in other words, you can modify a
(pointing it to a new location), but you cannot modify the value pointed to by a
.
Note that this is identical to
char const * a;
In this case, a
is a pointer to a const char
.
Pandas: Setting no. of max rows
pd.set_option('display.max_rows', 500)
df
Does not work in Jupyter!
Instead use:
pd.set_option('display.max_rows', 500)
df.head(500)
What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
I can explain in a more specific way starting with this example that's based on Fredrik's good one.
var test1 = [];
test1.push("value");
test1.push("value2");
var test2 = new Array();
test2.push("value");
test2.push("value2");
alert(test1);
alert(test2);
alert(test1 == test2);
alert(test1.value == test2.value);
I just added another value to the arrays, and made four alerts:
The first and second are to give us the value stored in each array, to be sure about the values. They will return the same!
Now try the third one, it returns false, that's because
JS treats test1 as a VARIABLE with a data type of array, and it treats test2 as an OBJECT with the functionality of an array, and
there are few slight differences here.
The first difference is when we call test1 it calls a variable without thinking, it just returns the values that are stored in this variable disregarding its data type!
But, when we call test2 it calls the Array() function and then it stores our "Pushed" values in its "Value" property, and the same happens when we alert test2, it returns the "Value" property of the array object.
So when we check if test1 equals test2 of course they will never return true, one is a function and the other is a variable (with a type of array), even if they have the same value!
To be sure about that, try the 4th alert, with the .value added to it; it will return true. In this case we tell JS "Disregarding the type of the container, whether was it function or variable, please compare the values that are stored in each container and tell us what you've seen!" that's exactly what happens.
I hope I said the idea behind that clearly, and sorry for my bad English.
Is there a way to create multiline comments in Python?
A multiline comment doesn't actually exist in Python. The below example consists of an unassigned string, which is validated by Python for syntactical errors.
A few text editors, like Notepad++, provide us shortcuts to comment out a written piece of code or words.
def foo():
"This is a doc string."
# A single line comment
"""
This
is a multiline
comment/String
"""
"""
print "This is a sample foo function"
print "This function has no arguments"
"""
return True
Also, Ctrl + K is a shortcut in Notepad++ to block comment. It adds a #
in front of every line under the selection. Ctrl + Shift + K is for block uncomment.
PHP header() redirect with POST variables
// from http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
Returning string from C function
Either allocate the string on the stack on the caller side and pass it to your function:
void getStr(char *wordd, int length) {
...
}
int main(void) {
char wordd[10 + 1];
getStr(wordd, sizeof(wordd) - 1);
...
}
Or make the string static in getStr
:
char *getStr(void) {
static char wordd[10 + 1];
...
return wordd;
}
Or allocate the string on the heap:
char *getStr(int length) {
char *wordd = malloc(length + 1);
...
return wordd;
}
insert password into database in md5 format?
Darren Davies is partially correct in saying that you should use a salt - there are several issues with his claim that MD5 is insecure.
You've said that you have to insert the password using an Md5 hash, but that doesn't really tell us why. Is it because that's the format used when validatinb the password? Do you have control over the code which validates the password?
The thing about using a salt is that it avoids the problem where 2 users have the same password - they'll also have the same hash - not a desirable outcome. By using a diferent salt for each password then this does not arise (with very large volumes of data there is still a risk of collisions arising from 2 different passwords - but we'll ignore that for now).
So you can aither generate a random value for the salt and store that in the record too, or you could use some of the data you already hold - such as the username:
$query="INSERT INTO ptb_users (id,
user_id,
first_name,
last_name,
email )
VALUES('NULL',
'NULL',
'".$firstname."',
'".$lastname."',
'".$email."',
MD5('"$user_id.$password."')
)";
(I am assuming that you've properly escaped all those strings earlier in your code)
Best practices for adding .gitignore file for Python projects?
Github has a great boilerplate .gitignore
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
# C extensions
*.so
# Distribution / packaging
bin/
build/
develop-eggs/
dist/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
.tox/
.coverage
.cache
nosetests.xml
coverage.xml
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
# Rope
.ropeproject
# Django stuff:
*.log
*.pot
# Sphinx documentation
docs/_build/
ASP.NET Web API session or something?
You can use cookies if the data is small enough and does not present a security concern. The same HttpContext.Current based approach should work.
Request and response HTTP headers can also be used to pass information between service calls.
How do I get ASP.NET Web API to return JSON instead of XML using Chrome?
It's unclear to me why there is all of this complexity in the answer. Sure there are lots of ways you can do this, with QueryStrings, headers and options... but what I believe to be the best practice is simple. You request a plain URL (ex: http://yourstartup.com/api/cars
) and in return you get JSON. You get JSON with the proper response header:
Content-Type: application/json
In looking for an answer to this very same question, I found this thread, and had to keep going because this accepted answer doesn't work exactly. I did find an answer which I feel is just too simple not to be the best one:
Set the default WebAPI formatter
I'll add my tip here as well.
WebApiConfig.cs
namespace com.yourstartup
{
using ...;
using System.Net.Http.Formatting;
...
config.Formatters.Clear(); //because there are defaults of XML..
config.Formatters.Add(new JsonMediaTypeFormatter());
}
I do have a question of where the defaults (at least the ones I am seeing) come from. Are they .NET defaults, or perhaps created somewhere else (by someone else on my project). Anways, hope this helps.
How do I add button on each row in datatable?
Basically your code is okay, thats the right way to do this. Anyhow, there are some misunderstandings:
fetchUserData.cfm does not contain key/value pairs. So it doesn't make sense to address keys in mData. Just use mData[index]
dataTables expects some more info from your serverside. At least you should tell datatables how many items in total are on your serverside and how many are filtered.
I just hardcoded this info to your data. You should get the right values from counts in your server sided script.
{
"iTotalRecords":"6",
"iTotalDisplayRecords":"6",
"aaData": [
[
"1",
"sameek",
"sam",
"sam",
"[email protected]",
"1",
""
],...
If you have the column names already set in the html part, you don't need to add sTitle.
The mRender Function takes three parameters:
- data = The data for this cell, as defined in mData
- type = The datatype (can be ignored mostly)
- full = The full data array for this row.
So your mRender function should look like this:
"mRender": function(data, type, full) {
return '<a class="btn btn-info btn-sm" href=#/' + full[0] + '>' + 'Edit' + '</a>';
}
Find a working Plunker here
How to get the Power of some Integer in Swift language?
If you really want an 'Int only' implementation and don't want to coerce to/from Double
, you'll need to implement it. Here is a trivial implementation; there are faster algorithms but this will work:
func pow (_ base:Int, _ power:UInt) -> Int {
var answer : Int = 1
for _ in 0..<power { answer *= base }
return answer
}
> pow (2, 4)
$R3: Int = 16
> pow (2, 8)
$R4: Int = 256
> pow (3,3)
$R5: Int = 27
In a real implementation you'd probably want some error checking.
Is there a way to only install the mysql client (Linux)?
there are two ways to install mysql client on centOS.
1. First method (download rpm package)
download rpm package from mysql website https://downloads.mysql.com/archives/community/
if you download this rpm package like picture, it's filename like mysql-community-client-8.0.21-1.el8.x86_64.rpm.
then execute sudo rpm -ivh --nodeps --force mysql-community-client-8.0.21-1.el8.x86_64.rpm
can install the rpm package the parameters -ivh
means install, print output, don't verify and check.
if raise error, maybe version conflict, you can execute rpm -pa | grep mysql
to find conflicting package, then execute rpm -e --nodeps <package name>
to remove them, and install once more.
finnaly, you can execute which mysql
, it's success if print /usr/bin/mysql.
2.Second method (Set repo of yum)
Please refer to this official website:
MySQL Yum Repository
A Quick Guide to Using the MySQL Yum Repository
A TypeScript GUID class?
There is an implementation in my TypeScript utilities based on JavaScript GUID generators.
Here is the code:
_x000D_
_x000D_
class Guid {_x000D_
static newGuid() {_x000D_
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
var r = Math.random() * 16 | 0,_x000D_
v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
return v.toString(16);_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
var id = Guid.newGuid();_x000D_
console.log(id);_x000D_
}
_x000D_
_x000D_
_x000D_
Please note the following:
C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.
JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).
Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?
Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered this thread [emphasis mine]:
Subject: Claiming (?P...) regex syntax extensions
From: Guido van Rossum ([email protected])
Date: Dec 10, 1997 3:36:19 pm
I have an unusual request for the Perl developers (those that develop
the Perl language). I hope this (perl5-porters) is the right list. I
am cc'ing the Python string-sig because it is the origin of most of
the work I'm discussing here.
You are probably aware of Python. I am Python's creator; I am
planning to release a next "major" version, Python 1.5, by the end of
this year. I hope that Python and Perl can co-exist in years to come;
cross-pollination can be good for both languages. (I believe Larry
had a good look at Python when he added objects to Perl 5; O'Reilly
publishes books about both languages.)
As you may know, Python 1.5 adds a new regular expression module that
more closely matches Perl's syntax. We've tried to be as close to the
Perl syntax as possible within Python's syntax. However, the regex
syntax has some Python-specific extensions, which all begin with (?P .
Currently there are two of them:
(?P<foo>...)
Similar to regular grouping parentheses, but the text
matched by the group is accessible after the match has been performed,
via the symbolic group name "foo".
(?P=foo)
Matches the same string as that matched by the group named
"foo". Equivalent to \1, \2, etc. except that the group is referred
to by name, not number.
I hope that this Python-specific extension won't conflict with any
future Perl extensions to the Perl regex syntax. If you have plans to
use (?P, please let us know as soon as possible so we can resolve the
conflict. Otherwise, it would be nice if the (?P syntax could be
permanently reserved for Python-specific syntax extensions. (Is
there some kind of registry of extensions?)
to which Larry Wall replied:
[...] There's no registry as of now--yours is the first request from
outside perl5-porters, so it's a pretty low-bandwidth activity.
(Sorry it was even lower last week--I was off in New York at Internet
World.)
Anyway, as far as I'm concerned, you may certainly have 'P' with my
blessing. (Obviously Perl doesn't need the 'P' at this point. :-) [...]
So I don't know what the original choice of P was motivated by -- pattern? placeholder? penguins? -- but you can understand why I've always associated it with Python. Which considering that (1) I don't like regular expressions and avoid them wherever possible, and (2) this thread happened fifteen years ago, is kind of odd.
how to use math.pi in java
Your diameter variable won't work because you're trying to store a String into a variable that will only accept a double. In order for it to work you will need to parse it
Ex:
diameter = Double.parseDouble(JOptionPane.showInputDialog("enter the diameter of a sphere.");
How do I print out the value of this boolean? (Java)
There are several problems.
One is of style; always capitalize class names. This is a universally observed Java convention. Failing to do so confuses other programmers.
Secondly, the line
System.out.println(boolean isLeapYear);
is a syntax error. Delete it.
Thirdly.
You never call the function from your main routine. That is why you never see any reply
to the input.
Apache Spark: The number of cores vs. the number of executors
To hopefully make all of this a little more concrete, here’s a worked example of configuring a Spark app to use as much of the cluster as
possible: Imagine a cluster with six nodes running NodeManagers, each
equipped with 16 cores and 64GB of memory. The NodeManager capacities,
yarn.nodemanager.resource.memory-mb and
yarn.nodemanager.resource.cpu-vcores, should probably be set to 63 *
1024 = 64512 (megabytes) and 15 respectively. We avoid allocating 100%
of the resources to YARN containers because the node needs some
resources to run the OS and Hadoop daemons. In this case, we leave a
gigabyte and a core for these system processes. Cloudera Manager helps
by accounting for these and configuring these YARN properties
automatically.
The likely first impulse would be to use --num-executors 6
--executor-cores 15 --executor-memory 63G. However, this is the wrong approach because:
63GB + the executor memory overhead won’t fit within the 63GB capacity
of the NodeManagers. The application master will take up a core on one
of the nodes, meaning that there won’t be room for a 15-core executor
on that node. 15 cores per executor can lead to bad HDFS I/O
throughput.
A better option would be to use --num-executors 17
--executor-cores 5 --executor-memory 19G. Why?
This config results in three executors on all nodes except for the one
with the AM, which will have two executors.
--executor-memory was derived as (63/3 executors per node) = 21. 21 * 0.07 = 1.47. 21 – 1.47 ~ 19.
The explanation was given in an article in Cloudera's blog, How-to: Tune Your Apache Spark Jobs (Part 2).
npm - EPERM: operation not permitted on Windows
Running this command was my mistake.
npm config set prefix /usr/local
Path /usr/local
is not for windows. This command changed the prefix variable at 'C:\Program Files (x86)\Git\local'
To access and make a change to this directory I need to run my cmd as administrator.
So I did:
- Run cmd as administrator
- Run
npm config edit
(You will get notepad editor)
- Change
prefix
variable to C:\Users\<User Name>\AppData\Roaming\npm
Then npm start
works in a normal console.
Checking host availability by using ping in bash scripts
You don't need the backticks in the if statement. You can use this check
if ping -c 1 some_ip_here &> /dev/null
then
echo 1
else
echo 0
fi
The if command checks the exit code of the following command (the ping). If the exit code is zero (which means that the command exited successfully) the then block will be executed. If it return a non-zero exit code, then the else block will be executed.
XSD - how to allow elements in any order any number of times?
If none of the above is working, you are probably working on EDI trasaction where you need to validate your result against an HIPPA schema or any other complex xsd for that matter.
The requirement is that, say there 8 REF segments and any of them have to appear in any order and also not all are required, means to say you may have them in following order 1st REF, 3rd REF , 2nd REF, 9th REF.
Under default situation EDI receive will fail, beacause default complex type is
<xs:sequence>
<xs:element.../>
</xs:sequence>
The situation is even complex when you are calling your element by refrence and then that element in its original spot is quite complex itself.
for example:
<xs:element>
<xs:complexType>
<xs:sequence>
<element name="REF1" ref= "REF1_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF2" ref= "REF2_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF3" ref= "REF3_Mycustomelment" minOccurs="0" maxOccurs="1">
</xs:sequence>
</xs:complexType>
</xs:element>
Solution:
Here simply replacing "sequence" with "all" or using "choice" with min/max combinations won't work!
First thing replace "xs:sequence" with "<xs:all>"
Now,You need to make some changes where you are Referring the element from,
There go to:
<xs:annotation>
<xs:appinfo>
<b:recordinfo structure="delimited" field.........Biztalk/2003">
***Now in the above segment add trigger point in the end like this trigger_field="REF01_...complete name.." trigger_value = "38"
Do the same for other REF segments where trigger value will be different like say "18", "XX" , "YY" etc..so that your record info now looks like:b:recordinfo structure="delimited" field.........Biztalk/2003" trigger_field="REF01_...complete name.." trigger_value="38">
This will make each element unique, reason being All REF segements (above example) have same structure like REF01, REF02, REF03. And during validation the structure validation is ok but it doesn't let the values repeat because it tries to look for remaining values in first REF itself. Adding triggers will make them all unique and they will pass in any order and situational cases (like use 5 out 9 and not all 9/9).
Hope it helps you, for I spent almost 20 hrs on this.
Good Luck
Cannot connect to Database server (mysql workbench)
I struggled with this problem for awhile and did several reinstalls of MySQL before discovering this.
I know that MySQL server was running OK because I could access all my DB's using the command line.
Hope this works for you.
In MySQL Workbench (5.2.47 CE)
click Mange Server Instances (bottom right corner)
click Connection
in the Connection box select:
Local Instance ($ServerName) - [email protected]:3306 '<'Standard(TCP/IP)>
click Edit Selected...
under Parameters, Hostname change localhost or 127.0.0.1 to your NetBIOS name
click Test Connection
If this works for you, great. If not change the hostname back to what it was.
How to prevent going back to the previous activity?
paulsm4's answer is the correct one. If in onBackPressed()
you just return, it will disable the back button. However, I think a better approach given your use case is to flip the activity logic, i.e. make your home activity the main one, check if the user is signed in there, if not, start the sign in activity. The reason is that if you override the back button in your main activity, most users will be confused when they press back and your app does nothing.
Difference between git checkout --track origin/branch and git checkout -b branch origin/branch
The two commands have the same effect (thanks to Robert Siemer’s answer for pointing it out).
The practical difference comes when using a local branch named differently:
git checkout -b mybranch origin/abranch
will create mybranch
and track origin/abranch
git checkout --track origin/abranch
will only create 'abranch
', not a branch with a different name.
(That is, as commented by Sebastian Graf, if the local branch did not exist already.
If it did, you would need git checkout -B abranch origin/abranch
)
Note: with Git 2.23 (Q3 2019), that would use the new command git switch
:
git switch -c <branch> --track <remote>/<branch>
If the branch exists in multiple remotes and one of them is named by the checkout.defaultRemote
configuration variable, we'll use that one for the purposes of disambiguation, even if the <branch>
isn't unique across all remotes.
Set it to e.g. checkout.defaultRemote=origin
to always checkout remote branches from there if <branch>
is ambiguous but exists on the 'origin' remote.
Here, '-c
' is the new '-b
'.
First, some background: Tracking means that a local branch has its upstream set to a remote branch:
# git config branch.<branch-name>.remote origin
# git config branch.<branch-name>.merge refs/heads/branch
git checkout -b branch origin/branch
will:
- create/reset
branch
to the point referenced by origin/branch
.
- create the branch
branch
(with git branch
) and track the remote tracking branch origin/branch
.
When a local branch is started off a remote-tracking branch, Git sets up the branch (specifically the branch.<name>.remote
and branch.<name>.merge
configuration entries) so that git pull
will appropriately merge from the remote-tracking branch.
This behavior may be changed via the global branch.autosetupmerge
configuration flag. That setting can be overridden by using the --track
and --no-track
options, and changed later using git branch --set-upstream-to
.
And git checkout --track origin/branch
will do the same as git branch --set-upstream-to
):
# or, since 1.7.0
git branch --set-upstream upstream/branch branch
# or, since 1.8.0 (October 2012)
git branch --set-upstream-to upstream/branch branch
# the short version remains the same:
git branch -u upstream/branch branch
It would also set the upstream for 'branch
'.
(Note: git1.8.0 will deprecate git branch --set-upstream
and replace it with git branch -u|--set-upstream-to
: see git1.8.0-rc1 announce)
Having an upstream branch registered for a local branch will:
- tell git to show the relationship between the two branches in
git status
and git branch -v
.
- directs
git pull
without arguments to pull from the upstream when the new branch is checked out.
See "How do you make an existing git branch track a remote branch?" for more.
How to create an HTTPS server in Node.js?
You can use also archive this with the Fastify framework:
const { readFileSync } = require('fs')
const Fastify = require('fastify')
const fastify = Fastify({
https: {
key: readFileSync('./test/asset/server.key'),
cert: readFileSync('./test/asset/server.cert')
},
logger: { level: 'debug' }
})
fastify.listen(8080)
(and run openssl req -nodes -new -x509 -keyout server.key -out server.cert
to create the files if you need to write tests)
string decode utf-8
A string needs no encoding. It is simply a sequence of Unicode characters.
You need to encode when you want to turn a String into a sequence of bytes. The charset the you choose (UTF-8, cp1255, etc.) determines the Character->Byte mapping. Note that a character is not necessarily translated into a single byte. In most charsets, most Unicode characters are translated to at least two bytes.
Encoding of a String is carried out by:
String s1 = "some text";
byte[] bytes = s1.getBytes("UTF-8"); // Charset to encode into
You need to decode when you have ? sequence of bytes and you want to turn them into a String. When y?u d? that you need to specify, again, the charset with which the byt?s were originally encoded (otherwise you'll end up with garbl?d t?xt).
Decoding:
String s2 = new String(bytes, "UTF-8"); // Charset with which bytes were encoded
If you want to understand this better, a great text is "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)"
ActiveModel::ForbiddenAttributesError when creating new user
I guess you are using Rails 4. If so, the needed parameters must be marked as required.
You might want to do it like this:
class UsersController < ApplicationController
def create
@user = User.new(user_params)
# ...
end
private
def user_params
params.require(:user).permit(:username, :email, :password, :salt, :encrypted_password)
end
end
How can I submit a POST form using the <a href="..."> tag?
There really seems no way for fooling the <a href= ..
into a POST method. However, given that you have access to CSS of a page, this can be substituted by using a form instead.
Unfortunately, the obvious way of just styling the button in CSS as an anchor tag, is not cross-browser compatible, since different browsers treat <button value= ...
differently.
Incorrect:
<form action='actbusy.php' method='post'>
<button type='submit' name='parameter' value='One'>Two</button>
</form>
The above example will be showing 'Two' and transmit 'parameter:One' in FireFox, while it will show 'One' and transmit also 'parameter:One' in IE8.
The way around is to use hidden input field(s) for delivering data and the button just for submitting it.
<form action='actbusy.php' method='post'>
<input class=hidden name='parameter' value='blaah'>
<button type='submit' name='delete' value='Delete'>Delete</button>
</form>
Note, that this method has a side effect that besides 'parameter:blaah' it will also deliver 'delete:Delete' as surplus parameters in POST.
You want to keep for a button the value attribute and button label between tags both the same ('Delete' on this case), since (as stated above) some browsers will display one and some display another as a button label.
Convert integer to class Date
as.character()
would be the general way rather than use paste()
for its side effect
> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"
(I presume this is a simple example and something like this:
v <- "20081101"
isn't possible?)
Changing element style attribute dynamically using JavaScript
Assuming you have HTML like this:
<div id='thediv'></div>
If you want to modify the style attribute of this div, you'd use
document.getElementById('thediv').style.[ATTRIBUTE] = '[VALUE]'
Replace [ATTRIBUTE]
with the style attribute you want. Remember to remove '-' and make the following letter uppercase.
Examples
document.getElementById('thediv').style.display = 'none'; //changes the display
document.getElementById('thediv').style.paddingLeft = 'none'; //removes padding
Delete commits from a branch in Git
In my case, my magic code for this pupose is this one:
git reset --hard @{u}
Test it and tell me. I have tried a few different ones, but this one was the only that helped me.
Switch statement fall-through...should it be allowed?
It is powerful and dangerous. The biggest problem with fall-through is that it's not explicit. For example, if you come across frequently-edited code that has a switch with fall-throughs, how do you know that's intentional and not a bug?
Anywhere I use it, I ensure that it's properly commented:
switch($var) {
case 'first':
// Fall-through
case 'second':
i++;
break;
}
bower proxy configuration
Inside your local project open the .bowerrc that contains:
{
"directory": "bower_components"
}
and add the following code-line:
{
"directory": "bower_components",
"proxy": "http://yourProxy:yourPort",
"https-proxy":"http://yourProxy:yourPort"
}
bower version: 1.7.1
Cheers
PostgreSQL database service
(start -> run -> services.msc) and look for the postgresql-[version] service then right click and enable it
Get refresh token google api
For those using the Google API Client Library for PHP and seeking offline access and refresh tokens beware as of the time of this writing the docs are showing incorrect examples.
currently it's showing:
$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
// offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access, you can omit this.
$client->setApprovalPrompt("consent");
$client->setIncludeGrantedScopes(true); // incremental auth
source: https://developers.google.com/identity/protocols/OAuth2WebServer#offline
All of this works great - except ONE piece
$client->setApprovalPrompt("consent");
After a bit of reasoning I changed this line to the following and EVERYTHING WORKED
$client->setPrompt("consent");
It makes sense since using the HTTP requests it was changed from approval_prompt=force to prompt=consent. So changing the setter method from setApprovalPrompt to setPrompt follows natural convention - BUT IT'S NOT IN THE DOCS!!! That I found at least.
Why does python use 'else' after for and while loops?
I agree, it's more like an 'elif not [condition(s) raising break]'.
I know this is an old thread, but I am looking into the same question right now, and I'm not sure anyone has captured the answer to this question in the way I understand it.
For me, there are three ways of "reading" the else
in For... else
or While... else
statements, all of which are equivalent, are:
else
==
if the loop completes normally (without a break or error)
else
==
if the loop does not encounter a break
else
==
else not (condition raising break)
(presumably there is such a condition, or you wouldn't have a loop)
So, essentially, the "else" in a loop is really an "elif ..." where '...' is (1) no break, which is equivalent to (2) NOT [condition(s) raising break].
I think the key is that the else
is pointless without the 'break', so a for...else
includes:
for:
do stuff
conditional break # implied by else
else not break:
do more stuff
So, essential elements of a for...else
loop are as follows, and you would read them in plainer English as:
for:
do stuff
condition:
break
else: # read as "else not break" or "else not condition"
do more stuff
As the other posters have said, a break is generally raised when you are able to locate what your loop is looking for, so the else:
becomes "what to do if target item not located".
Example
You can also use exception handling, breaks, and for loops all together.
for x in range(0,3):
print("x: {}".format(x))
if x == 2:
try:
raise AssertionError("ASSERTION ERROR: x is {}".format(x))
except:
print(AssertionError("ASSERTION ERROR: x is {}".format(x)))
break
else:
print("X loop complete without error")
Result
x: 0
x: 1
x: 2
ASSERTION ERROR: x is 2
----------
# loop not completed (hit break), so else didn't run
Example
Simple example with a break being hit.
for y in range(0,3):
print("y: {}".format(y))
if y == 2: # will be executed
print("BREAK: y is {}\n----------".format(y))
break
else: # not executed because break is hit
print("y_loop completed without break----------\n")
Result
y: 0
y: 1
y: 2
BREAK: y is 2
----------
# loop not completed (hit break), so else didn't run
Example
Simple example where there no break, no condition raising a break, and no error are encountered.
for z in range(0,3):
print("z: {}".format(z))
if z == 4: # will not be executed
print("BREAK: z is {}\n".format(y))
break
if z == 4: # will not be executed
raise AssertionError("ASSERTION ERROR: x is {}".format(x))
else:
print("z_loop complete without break or error\n----------\n")
Result
z: 0
z: 1
z: 2
z_loop complete without break or error
----------
writing a batch file that opens a chrome URL
@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://tweetdeck.twitter.com/"
@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://web.whatsapp.com/"
Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax
The easy solution is to create a payload class that has the str1 and the str2 as attributes:
@Getter
@Setter
public class ObjHolder{
String str1;
String str2;
}
And after you can pass
@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody ObjHolder Str) {}
and the body of your request is:
{
"str1": "test one",
"str2": "two test"
}
Condition within JOIN or WHERE
WHERE will filter after the JOIN has occurred.
Filter on the JOIN to prevent rows from being added during the JOIN process.
Split string and get first value only
You can do it:
var str = "Doctor Who,Fantasy,Steven Moffat,David Tennant";
var title = str.Split(',').First();
Also you can do it this way:
var index = str.IndexOf(",");
var title = index < 0 ? str : str.Substring(0, index);
CSS height 100% percent not working
I would say you have two options:
to get all parent divs styled with 100%
height (including body and html)
to use absolute positioning for one of the parent divs (for example #content
) and then all child divs set to height 100%
How do I pass JavaScript variables to PHP?
We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -
function statusChangeCallback(response) {
console.log('statusChangeCallback');
if (response.status === 'connected') {
// Logged into your app and Facebook.
FB.api('/me?fields=id,first_name,last_name,email', function (result) {
document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
console.log(document.cookie);
});
}
}
And I've accessed it (in any file) using -
<?php
if(isset($_COOKIE['fbdata'])) {
echo "welcome ".$_COOKIE['fbdata'];
}
?>
How to clear a data grid view
You could take this next instruction and would do the work with lack of perfomance. If you want to see the effect of that, put one of the 2 next instructions (Technically similars) where you need to clear the DataGridView into a try{} catch(...){} finally block and wait what occurs.
while (dataGridView1.Rows.Count > 1)
{
dataGridView1.Rows.RemoveAt(0);
}
foreach (object _Cols in dataGridView1.Columns)
{
dataGridView1.Columns.RemoveAt(0);
}
You improve this task but its not enough, there is a problem to reset a DataGridView, because of the colums that remains in the DataGridView object. Finally I suggest, the best way i've implemented in my home practice is to handle this gridView as a file with rows, columns: a record collection based on the match between rows and columns. If you can improve, then take your own choice a) or b): foreach or while.
//(a): With foreach
foreach (object _Cols in dataGridView1.Columns)
{
dataGridView1.Columns.RemoveAt(0);
}
foreach(object _row in dataGridView1.Rows){
dataGridView1.Rows.RemoveAt(0);
}
//(b): With foreach
while (dataGridView1.Rows.Count > 1)
{
dataGridView1.Rows.RemoveAt(0);
}
while (dataGridView1.Columns.Count > 0)
{
dataGridView1.Columns.RemoveAt(0);
}
Well, as a recomendation Never in your life delete the columns first, the order is before the rows after the cols, because logically the columns where created first and then the rows.It would be a penalty in terms of correct analisys.
foreach (object _Cols in dataGridView1.Columns)
{
dataGridView1.Columns.RemoveAt(0);
}
foreach (object _row in dataGridView1.Rows)
{
dataGridView1.Rows.RemoveAt(0);
}
while (dataGridView1.Rows.Count > 1)
{
dataGridView1.Rows.RemoveAt(0);
}
while (dataGridView1.Columns.Count > 0)
{
dataGridView1.Columns.RemoveAt(0);
}
Then, Put it inside a function or method.
private void ClearDataGridViewLoopWhile()
{
while (dataGridView1.Rows.Count > 1)
{
dataGridView1.Rows.RemoveAt(0);
}
while (dataGridView1.Columns.Count > 0)
{
dataGridView1.Columns.RemoveAt(0);
}
}
private void ClearDataGridViewForEach()
{
foreach (object _Cols in dataGridView1.Columns)
{
dataGridView1.Columns.RemoveAt(0);
}
foreach (object _row in dataGridView1.Rows)
{
dataGridView1.Rows.RemoveAt(0);
}
}
Finally, call your new function ClearDataGridViewLoopWhile(); or ClearDataGridViewForEach(); where you need to use it, but its recomended when you are making queries and changing over severall tables that will load with diferents header names in the grieView. But if you want preserve headers here there is a solution given.
How can I convert a dictionary into a list of tuples?
You can use list comprehensions.
[(k,v) for k,v in a.iteritems()]
will get you [ ('a', 1), ('b', 2), ('c', 3) ]
and
[(v,k) for k,v in a.iteritems()]
the other example.
Read more about list comprehensions if you like, it's very interesting what you can do with them.
Android : Fill Spinner From Java Code Programmatically
Here is an example to fully programmatically:
- init a Spinner.
- fill it with data via a String List.
- resize the Spinner and add it to my View.
- format the Spinner font (font size, colour, padding).
- clear the Spinner.
- add new values to the Spinner.
- redraw the Spinner.
I am using the following class vars:
Spinner varSpinner;
List<String> varSpinnerData;
float varScaleX;
float varScaleY;
A - Init and render the Spinner (varRoot is a pointer to my main Activity):
public void renderSpinner() {
List<String> myArraySpinner = new ArrayList<String>();
myArraySpinner.add("red");
myArraySpinner.add("green");
myArraySpinner.add("blue");
varSpinnerData = myArraySpinner;
Spinner mySpinner = new Spinner(varRoot);
varSpinner = mySpinner;
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
mySpinner.setAdapter(spinnerArrayAdapter);
B - Resize and Add the Spinner to my View:
FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
myParamsLayout.gravity = Gravity.NO_GRAVITY;
myParamsLayout.leftMargin = (int) (100 * varScaleX);
myParamsLayout.topMargin = (int) (350 * varScaleY);
myParamsLayout.width = (int) (300 * varScaleX);;
myParamsLayout.height = (int) (60 * varScaleY);;
varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);
C - Make the Click handler and use this to set the font.
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {
Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);
((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
D - Update the Spinner with new data:
private void updateInitSpinners(){
String mySelected = varSpinner.getSelectedItem().toString();
Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);
varSpinnerData.clear();
varSpinnerData.add("Hello World");
varSpinnerData.add("Hello World 2");
((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
varSpinner.invalidate();
varSpinner.setSelection(1);
}
}
What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.
UPDATE:
This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:
private void updateInitSpinners(){
String mySelected = varSpinner.getSelectedItem().toString();
Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);
varSpinnerData.clear();
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
varSpinner.setAdapter(spinnerArrayAdapter);
varSpinnerData.add("Hello World");
varSpinnerData.add("Hello World 2");
((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
varSpinner.invalidate();
varSpinner.setSelection(0);
}
}
Hope this helps......
How to prevent colliders from passing through each other?
Old Question but maybe it helps someone.
Go to Project settings > Time and Try dividing the fixed timestep and maximum allowed timestep by two or by four.
I had the problem that my player was able to squeeze through openings smaller than the players collider and that solved it. It also helps with stopping fast moving objects.
Check if a Class Object is subclass of another Class Object in Java
You want this method:
boolean isList = List.class.isAssignableFrom(myClass);
where in general, List
(above) should be replaced with superclass
and myClass
should be replaced with subclass
From the JavaDoc:
Determines if the class or interface represented by this Class
object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class
parameter. It returns true
if so; otherwise it returns false
. If this Class
object represents a primitive type, this method returns true
if the specified Class
parameter is exactly this Class
object; otherwise it returns false
.
Reference:
Related:
a) Check if an Object is an instance of a Class or Interface (including subclasses) you know at compile time:
boolean isInstance = someObject instanceof SomeTypeOrInterface;
Example:
assertTrue(Arrays.asList("a", "b", "c") instanceof List<?>);
b) Check if an Object is an instance of a Class or Interface (including subclasses) you only know at runtime:
Class<?> typeOrInterface = // acquire class somehow
boolean isInstance = typeOrInterface.isInstance(someObject);
Example:
public boolean checkForType(Object candidate, Class<?> type){
return type.isInstance(candidate);
}
Print a file's last modified date in Bash
You can use:
ls -lrt filename |awk '{print "%02d",$7}'
This will display the date in 2 digits.
If between 1 to 9 it adds "0" prefix to it and converts to 01 - 09.
Hope this meets the expectation.
Computing cross-correlation function?
For 1D array, numpy.correlate
is faster than scipy.signal.correlate
, under different sizes, I see a consistent 5x peformance gain using numpy.correlate
. When two arrays are of similar size (the bright line connecting the diagonal), the performance difference is even more outstanding (50x +).
# a simple benchmark
res = []
for x in range(1, 1000):
list_x = []
for y in range(1, 1000):
# generate different sizes of series to compare
l1 = np.random.choice(range(1, 100), size=x)
l2 = np.random.choice(range(1, 100), size=y)
time_start = datetime.now()
np.correlate(a=l1, v=l2)
t_np = datetime.now() - time_start
time_start = datetime.now()
scipy.signal.correlate(in1=l1, in2=l2)
t_scipy = datetime.now() - time_start
list_x.append(t_scipy / t_np)
res.append(list_x)
plt.imshow(np.matrix(res))
As default, scipy.signal.correlate calculates a few extra numbers by padding and that might explained the performance difference.
>> l1 = [1,2,3,2,1,2,3]
>> l2 = [1,2,3]
>> print(numpy.correlate(a=l1, v=l2))
>> print(scipy.signal.correlate(in1=l1, in2=l2))
[14 14 10 10 14]
[ 3 8 14 14 10 10 14 8 3] # the first 3 is [0,0,1]dot[1,2,3]
How to return a PNG image from Jersey REST service method to the browser
If you have a number of image resource methods, it is well worth creating a MessageBodyWriter to output the BufferedImage:
@Produces({ "image/png", "image/jpg" })
@Provider
public class BufferedImageBodyWriter implements MessageBodyWriter<BufferedImage> {
@Override
public boolean isWriteable(Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
return type == BufferedImage.class;
}
@Override
public long getSize(BufferedImage t, Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
return -1; // not used in JAX-RS 2
}
@Override
public void writeTo(BufferedImage image, Class<?> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, Object> mm, OutputStream out) throws IOException, WebApplicationException {
ImageIO.write(image, mt.getSubtype(), out);
}
}
This MessageBodyWriter will be used automatically if auto-discovery is enabled for Jersey, otherwise it needs to be returned by a custom Application sub-class. See JAX-RS Entity Providers for more info.
Once this is set up, simply return a BufferedImage from a resource method and it will be be output as image file data:
@Path("/whatever")
@Produces({"image/png", "image/jpg"})
public Response getFullImage(...) {
BufferedImage image = ...;
return Response.ok(image).build();
}
A couple of advantages to this approach:
- It writes to the response OutputSteam rather than an intermediary BufferedOutputStream
- It supports both png and jpg output (depending on the media types allowed by the resource method)
Excel: Searching for multiple terms in a cell
Another way
=IF(SUMPRODUCT(--(NOT(ISERR(SEARCH({"Gingrich","Obama","Romney"},C1)))))>0,"1","")
Also, if you keep a list of values in, say A1 to A3, then you can use
=IF(SUMPRODUCT(--(NOT(ISERR(SEARCH($A$1:$A$3,C1)))))>0,"1","")
The wildcards are not necessary at all in the Search() function, since Search() returns the position of the found string.
Launch custom android application from android browser
In my case I had to set two categories for the <intent-filter>
and then it worked:
<intent-filter>
<data android:scheme="my.special.scheme" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
</intent-filter>
.htaccess, order allow, deny, deny from all: confused?
This is a quite confusing way of using Apache configuration directives.
Technically, the first bit is equivalent to
Allow From All
This is because Order Deny,Allow
makes the Deny directive evaluated before the Allow Directives.
In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.
Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.
The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.
Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.
It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.
The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
which forbids access to any file beginning by ".ht".
The equivalent Apache 2.4 configuration should look like:
<Files ~ "^\.ht">
Require all denied
</Files>
AngularJS ng-class if-else expression
This is the best and reliable way to do this.
Here is a simple example and after that you can develop your custom logic:
//In .ts
public showUploadButton:boolean = false;
if(some logic)
{
//your logic
showUploadButton = true;
}
//In template
<button [class]="showUploadButton ? 'btn btn-default': 'btn btn-info'">Upload</button>
How to represent a DateTime in Excel
Excel can display a Date type in a similar manner to a DateTime. Right click on the affected cell, select Format Cells, then under Category select Date and under Type select the type that looks something like this:
3/14/01 1:30 PM
That should do what you requested. I tested sorting on some sample data with this format and it seemed to work fine.
What is the difference between CSS and SCSS?
css
has variables as well. You can use them like this:
--primaryColor: #ffffff;
--width: 800px;
body {
width: var(--width);
color: var(--primaryColor);
}
.content{
width: var(--width);
background: var(--primaryColor);
}
How do I set the background color of my main screen in Flutter?
Here's one way that I found to do it. I don't know if there are better ways, or what the trade-offs are.
Container "tries to be as big as possible", according to https://flutter.io/layout/. Also, Container can take a decoration
, which can be a BoxDecoration, which can have a color
(which, is the background color).
Here's a sample that does indeed fill the screen with red, and puts "Hello, World!" into the center:
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new Container(
decoration: new BoxDecoration(color: Colors.red),
child: new Center(
child: new Text("Hello, World!"),
),
);
}
}
Note, the Container is returned by the MyApp build(). The Container has a decoration and a child, which is the centered text.
See it in action here: