Load data from txt with pandas
You can use:
data = pd.read_csv('output_list.txt', sep=" ", header=None)
data.columns = ["a", "b", "c", "etc."]
Add sep=" "
in your code, leaving a blank space between the quotes. So pandas can detect spaces between values and sort in columns. Data columns is for naming your columns.
Change Oracle port from port 8080
Just open Run SQL Command Line
and login as sysadmin and then enter below command
Exec DBMS_XDB.SETHTTPPORT(8181);
That's it. You are done.....
Boolean operators ( &&, -a, ||, -o ) in Bash
-a and -o are the older and/or operators for the test command.
&& and || are and/or operators for the shell.
So (assuming an old shell) in your first case,
[ "$1" = 'yes' ] && [ -r $2.txt ]
The shell is evaluating the and condition.
In your second case,
[ "$1" = 'yes' -a $2 -lt 3 ]
The test command (or builtin test) is evaluating the and condition.
Of course in all modern or semi-modern shells, the test command is built in to the shell, so there really isn't any or much difference. In modern shells, the if statement can be written:
[[ $1 == yes && -r $2.txt ]]
Which is more similar to modern programming languages and thus is more readable.
What is console.log?
In java scripts there is no input and output functions. So to debug the code console.log() method is used.It is a method for logging. It will be printed under console log (development tools).
Its is not present in IE8 and under until you open IE development tool.
jQuery Dialog Box
I had the same problem and was looking for a way to solve it which brought me here. After reviewing the suggestion made from RaeLehman it led me to the solution. Here's my implementation.
In my $(document).ready event I initialize my dialog with the autoOpen set to false. I also chose to bind a click event to an element, like a button, which will open my dialog.
$(document).ready(function(){
// Initialize my dialog
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons: {
"OK":function() { // do something },
"Cancel": function() { $(this).dialog("close"); }
}
});
// Bind to the click event for my button and execute my function
$("#x-button").click(function(){
Foo.DoSomething();
});
});
Next, I make sure that the function is defined and that is where I implement the dialog open method.
var Foo = {
DoSomething: function(){
$("#dialog").dialog("open");
}
}
By the way, I tested this in IE7 and Firefox and it works fine. Hope this helps!
XAMPP: Couldn't start Apache (Windows 10)
You may just have updated your Windows to Version 1903 (OS Build:18362.239) or have changed user passwords. Despite having eliminated all port conflicts, I still kept getting the messages described by the OP at the very start of this post.
In the end I cured it by upgrading to XAMPP to 7.3.7. (When forced to reinstall, you might as well upgrade at the same time!)
But the problem reoccurred when I again went to change the 'root' user password.
The console error messages were masking the fact that table mysql.user was corrupt.
Check file mysql_error.log. If you are seeing Fatal error: Can't open and lock privilege tables: Index for table 'user' is corrupt; try to repair it, then have a look at this.
Make install, but not to default directories?
Since don't know which version of automake you can use DESTDIR environment variable.
See Makefile to be sure.
For example:
export DESTDIR="$HOME/Software/LocalInstall" && make -j4 install
How do I compare 2 rows from the same table (SQL Server)?
You can join a table to itself as many times as you require, it is called a self join.
An alias is assigned to each instance of the table (as in the example below) to differentiate one from another.
SELECT a.SelfJoinTableID
FROM dbo.SelfJoinTable a
INNER JOIN dbo.SelfJoinTable b
ON a.SelfJoinTableID = b.SelfJoinTableID
INNER JOIN dbo.SelfJoinTable c
ON a.SelfJoinTableID = c.SelfJoinTableID
WHERE a.Status = 'Status to filter a'
AND b.Status = 'Status to filter b'
AND c.Status = 'Status to filter c'
Git fails when pushing commit to github
If this command not help
git config http.postBuffer 524288000
Try to change ssh method to https
git remote -v
git remote rm origin
git remote add origin https://github.com/username/project.git
Adding line break in C# Code behind page
All you need to do is add \n or to write on files go \r\n.
Examples:
say you wanted to write duck(line break) cow this is how you would do it
Console.WriteLine("duck\n cow");
Edit: I think I didn't understand the question. You can use
@"duck
cow".Replace("\r\n", "")
as a linebreak in code, that produces \r\n which is used Windows.
Check if url contains string with JQuery
Use Window.location.href to take the url in javascript. it's a
property that will tell you the current URL location of the browser.
Setting the property to something different will redirect the page.
if (window.location.href.indexOf("?added-to-cart=555") > -1) {
alert("found it");
}
Truncate a string straight JavaScript
Yes, substring
works great:
stringTruncate('Hello world', 5); //output "Hello..."
stringTruncate('Hello world', 20);//output "Hello world"
var stringTruncate = function(str, length){
var dots = str.length > length ? '...' : '';
return str.substring(0, length)+dots;
};
Do not want scientific notation on plot axis
The R
graphics
package has the function axTicks
that returns the tick locations of the ticks that the axis
and plot
functions would set automatically. The other answers given to this question define the tick locations manually which might not be convenient in some situations.
myTicks = axTicks(1)
axis(1, at = myTicks, labels = formatC(myTicks, format = 'd'))
A minimal example would be
plot(10^(0:10), 0:10, log = 'x', xaxt = 'n')
myTicks = axTicks(1)
axis(1, at = myTicks, labels = formatC(myTicks, format = 'd'))
There is also an log
parameter in the axTicks
function but in this situation it does not need to be set to get the proper logarithmic axis tick location.
Classes vs. Functions
Before answering your question:
If you do not have a Person
class, first you must consider whether you want to create a Person
class. Do you plan to reuse the concept of a Person
very often? If so, you should create a Person
class. (You have access to this data in the form of a passed-in variable and you don't care about being messy and sloppy.)
To answer your question:
You have access to their birthyear, so in that case you likely have a Person
class with a someperson.birthdate
field. In that case, you have to ask yourself, is someperson.age
a value that is reusable?
The answer is yes. We often care about age more than the birthdate, so if the birthdate is a field, age should definitely be a derived field. (A case where we would not do this: if we were calculating values like someperson.chanceIsFemale
or someperson.positionToDisplayInGrid
or other irrelevant values, we would not extend the Person
class; you just ask yourself, "Would another program care about the fields I am thinking of extending the class with?" The answer to that question will determine if you extend the original class, or make a function (or your own class like PersonAnalysisData
or something).)
Is it necessary to use # for creating temp tables in SQL server?
The difference between this two tables ItemBack1
and #ItemBack1
is that the first on is persistent (permanent) where as the other is temporary.
Now if take a look at your question again
Is it necessary to Use # for creating temp table in sql server?
The answer is Yes, because without this preceding #
the table will not be a temporary table, it will be independent of all sessions and scopes.
Imshow: extent and aspect
You can do it by setting the aspect of the image manually (or by letting it auto-scale to fill up the extent of the figure).
By default, imshow
sets the aspect of the plot to 1, as this is often what people want for image data.
In your case, you can do something like:
import matplotlib.pyplot as plt
import numpy as np
grid = np.random.random((10,10))
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10))
ax1.imshow(grid, extent=[0,100,0,1])
ax1.set_title('Default')
ax2.imshow(grid, extent=[0,100,0,1], aspect='auto')
ax2.set_title('Auto-scaled Aspect')
ax3.imshow(grid, extent=[0,100,0,1], aspect=100)
ax3.set_title('Manually Set Aspect')
plt.tight_layout()
plt.show()
run a python script in terminal without the python command
Add the following line to the beginning script1.py
#!/usr/bin/env python
and then make the script executable:
$ chmod +x script1.py
If the script resides in a directory that appears in your PATH
variable, you can simply type
$ script1.py
Otherwise, you'll need to provide the full path (either absolute or relative). This includes the current working directory, which should not be in your PATH
.
$ ./script1.py
Keras model.summary() result - Understanding the # of Parameters
I feed a 514 dimensional real-valued input to a Sequential
model in Keras.
My model is constructed in following way :
predictivemodel = Sequential()
predictivemodel.add(Dense(514, input_dim=514, W_regularizer=WeightRegularizer(l1=0.000001,l2=0.000001), init='normal'))
predictivemodel.add(Dense(257, W_regularizer=WeightRegularizer(l1=0.000001,l2=0.000001), init='normal'))
predictivemodel.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
When I print model.summary()
I get following result:
Layer (type) Output Shape Param # Connected to
================================================================
dense_1 (Dense) (None, 514) 264710 dense_input_1[0][0]
________________________________________________________________
activation_1 (None, 514) 0 dense_1[0][0]
________________________________________________________________
dense_2 (Dense) (None, 257) 132355 activation_1[0][0]
================================================================
Total params: 397065
________________________________________________________________
For the dense_1 layer , number of params is 264710.
This is obtained as : 514 (input values) * 514 (neurons in the first layer) + 514 (bias values)
For dense_2 layer, number of params is 132355.
This is obtained as : 514 (input values) * 257 (neurons in the second layer) + 257 (bias values for neurons in the second layer)
How to access a value defined in the application.properties file in Spring Boot
For me, none of the above did directly work for me.
What I did is the following:
Additionally to @Rodrigo Villalba Zayas answer up there I added
implements InitializingBean
to the class
and implemented the method
@Override
public void afterPropertiesSet() {
String path = env.getProperty("userBucket.path");
}
So that will look like
import org.springframework.core.env.Environment;
public class xyz implements InitializingBean {
@Autowired
private Environment env;
private String path;
....
@Override
public void afterPropertiesSet() {
path = env.getProperty("userBucket.path");
}
public void method() {
System.out.println("Path: " + path);
}
}
PostgreSQL Exception Handling
Use the DO statement, a new option in version 9.0:
DO LANGUAGE plpgsql
$$
BEGIN
CREATE TABLE "Logs"."Events"
(
EventId BIGSERIAL NOT NULL PRIMARY KEY,
PrimaryKeyId bigint NOT NULL,
EventDateTime date NOT NULL DEFAULT(now()),
Action varchar(12) NOT NULL,
UserId integer NOT NULL REFERENCES "Office"."Users"(UserId),
PrincipalUserId varchar(50) NOT NULL DEFAULT(user)
);
CREATE TABLE "Logs"."EventDetails"
(
EventDetailId BIGSERIAL NOT NULL PRIMARY KEY,
EventId bigint NOT NULL REFERENCES "Logs"."Events"(EventId),
Resource varchar(64) NOT NULL,
OldVal varchar(4000) NOT NULL,
NewVal varchar(4000) NOT NULL
);
RAISE NOTICE 'Task completed sucessfully.';
END;
$$;
Excel tab sheet names vs. Visual Basic sheet names
This a very basic solution (maybe I'm missing the full point of the question). ActiveSheet.Name will RETURN the string of the current tab name (and will reflect any future changes by the user). I just call the active sheet, set the variable and then use it as the Worksheets' object. Here I'm retrieving data from a table to set up a report for a division. This macro will work on any sheet in my workbook that is formatted for the same filter (criteria and copytorange) - each division gets their own sheet and can alter the criteria and update using this single macro.
Dim currRPT As String
ActiveSheet.Select
currRPT = (ActiveSheet.Name)
Range("A6").Select
Selection.RemoveSubtotal
Selection.AutoFilter
Range("PipeData").AdvancedFilter Action:=xlFilterCopy, CriteriaRange:=Range _
("C1:D2"), CopyToRange:=Range("A6:L9"), Unique:=True
Worksheets(currRPT).AutoFilter.Sort.SortFields.Clear
Worksheets(currRPT).AutoFilter.Sort.SortFields.Add Key:= _
Range("C7"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
Disabling the button after once click
To submit form in MVC NET Core you can submit using INPUT:
<input type="submit" value="Add This Form">
To make it a button I am using Bootstrap for example:
<input type="submit" value="Add This Form" class="btn btn-primary">
To prevent sending duplicate forms in MVC NET Core, you can add onclick event, and use this.disabled = true; to disable the button:
<input type="submit" value="Add This Form" class="btn btn-primary" onclick="this.disabled = true;">
If you want check first if form is valid and then disable the button, add this.form.submit(); first, so if form is valid, then this button will be disabled, otherwise button will still be enabled to allow you to correct your form when validated.
<input type="submit" value="Add This Form" class="btn btn-primary" onclick="this.form.submit(); this.disabled = true;">
You can add text to the disabled button saying you are now in the process of sending form, when all validation is correct using this.value='text';:
<input type="submit" value="Add This Form" class="btn btn-primary" onclick="this.form.submit(); this.disabled = true; this.value = 'Submitting the form';">
Add CSS class to a div in code behind
I'm also looking for the same solution. And I think of
BtnventCss.CssClass = BtnventCss.CssClass + " hom_but_a";
It seems working fine but I'm not sure if it is a good practice
Android check permission for LocationManager
if you are working on dynamic permissions and any permission like ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION giving error "cannot resolve method PERMISSION_NAME" in this case write you code with permission name and then rebuild your project this will regenerate the manifest(Manifest.permission) file.
WPF Datagrid set selected row
It's a little trickier to do what you're trying to do than I'd prefer, but that's because you don't really directly bind a DataGrid
to a DataTable
.
When you bind DataGrid.ItemsSource
to a DataTable
, you're really binding it to the default DataView
, not to the table itself. This is why, for instance, you don't have to do anything to make a DataGrid
sort rows when you click on a column header - that functionality's baked into DataView
, and DataGrid
knows how to access it (through the IBindingList
interface).
The DataView
implements IEnumerable<DataRowView>
(more or less), and the DataGrid
fills its items by iterating over this. This means that when you've bound DataGrid.ItemsSource
to a DataTable
, its SelectedItem
property will be a DataRowView
, not a DataRow
.
If you know all this, it's pretty straightforward to build a wrapper class that lets you expose properties that you can bind to. There are three key properties:
Table
, the DataTable
,
Row
, a two-way bindable property of type DataRowView
, and
SearchText
, a string property that, when it's set, will find the first matching DataRowView
in the table's default view, set the Row
property, and raise PropertyChanged
.
It looks like this:
public class DataTableWrapper : INotifyPropertyChanged
{
private DataRowView _Row;
private string _SearchText;
public DataTableWrapper()
{
// using a parameterless constructor lets you create it directly in XAML
DataTable t = new DataTable();
t.Columns.Add("id", typeof (int));
t.Columns.Add("text", typeof (string));
// let's acquire some sample data
t.Rows.Add(new object[] { 1, "Tower"});
t.Rows.Add(new object[] { 2, "Luxor" });
t.Rows.Add(new object[] { 3, "American" });
t.Rows.Add(new object[] { 4, "Festival" });
t.Rows.Add(new object[] { 5, "Worldwide" });
t.Rows.Add(new object[] { 6, "Continental" });
t.Rows.Add(new object[] { 7, "Imperial" });
Table = t;
}
// you should have this defined as a code snippet if you work with WPF
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
{
h(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
// SelectedItem gets bound to this two-way
public DataRowView Row
{
get { return _Row; }
set
{
if (_Row != value)
{
_Row = value;
OnPropertyChanged("Row");
}
}
}
// the search TextBox is bound two-way to this
public string SearchText
{
get { return _SearchText; }
set
{
if (_SearchText != value)
{
_SearchText = value;
Row = Table.DefaultView.OfType<DataRowView>()
.Where(x => x.Row.Field<string>("text").Contains(_SearchText))
.FirstOrDefault();
}
}
}
public DataTable Table { get; private set; }
}
And here's XAML that uses it:
<Window x:Class="DataGridSelectionDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
xmlns:DataGridSelectionDemo="clr-namespace:DataGridSelectionDemo"
Title="DataGrid selection demo"
Height="350"
Width="525">
<Window.DataContext>
<DataGridSelectionDemo:DataTableWrapper />
</Window.DataContext>
<DockPanel>
<Grid DockPanel.Dock="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label>Text</Label>
<TextBox Grid.Column="1"
Text="{Binding SearchText, Mode=TwoWay}" />
</Grid>
<dg:DataGrid DockPanel.Dock="Top"
ItemsSource="{Binding Table}"
SelectedItem="{Binding Row, Mode=TwoWay}" />
</DockPanel>
</Window>
Best way to check if a URL is valid
function is_url($uri){
if(preg_match( '/^(http|https):\\/\\/[a-z0-9_]+([\\-\\.]{1}[a-z_0-9]+)*\\.[_a-z]{2,5}'.'((:[0-9]{1,5})?\\/.*)?$/i' ,$uri)){
return $uri;
}
else{
return false;
}
}
How to copy to clipboard using Access/VBA?
User Leigh Webber on the social.msdn.microsoft.com site posted VBA code implementing an easy-to-use clipboard interface that uses the Windows API:
http://social.msdn.microsoft.com/Forums/en/worddev/thread/ee9e0d28-0f1e-467f-8d1d-1a86b2db2878
You can get Leigh Webber's source code here
If this link doesn't go through, search for "A clipboard object for VBA" in the Office Dev Center > Microsoft Office for Developers Forums > Word for Developers section.
I created the two classes, ran his test cases, and it worked perfectly inside Outlook 2007 SP3 32-bit VBA under Windows 7 64-bit. It will most likely work for Access.
Tip: To rename classes, select the class in the VBA 'Project' window, then click 'View' on the menu bar and click 'Properties Window' (or just hit F4).
With his classes, this is what it takes to copy to/from the clipboard:
Dim myClipboard As New vbaClipboard ' Create clipboard
' Copy text to clipboard as ClipboardFormat TEXT (CF_TEXT)
myClipboard.SetClipboardText "Text to put in clipboard", "CF_TEXT"
' Retrieve clipboard text in CF_TEXT format (CF_TEXT = 1)
mytxt = myClipboard.GetClipboardText(1)
He also provides other functions for manipulating the clipboard.
It also overcomes 32KB MSForms_DataObject.SetText limitation - the main reason why SetText often fails. However, bear in mind that, unfortunatelly, I haven't found a reference on Microsoft recognizing this limitation.
-Jim
Set Content-Type to application/json in jsp file
You can do via Page directive.
For example:
<%@ page language="java" contentType="application/json; charset=UTF-8"
pageEncoding="UTF-8"%>
- contentType="mimeType [ ;charset=characterSet ]" |
"text/html;charset=ISO-8859-1"
The MIME type and character encoding the JSP file uses for the
response it sends to the client. You can use any MIME type or
character set that are valid for the JSP container. The default MIME
type is text/html, and the default character set is ISO-8859-1.
TypeError: 'str' object is not callable (Python)
Another case of this: Messing with the __repr__
function of an object where a format()
call fails non-transparently.
In our case, we used a @property
decorator on the __repr__
and passed that object to a format()
. The @property
decorator causes the __repr__
object to be turned into a string, which then results in the str
object is not callable error.
How to change the font on the TextView?
First download the .ttf
file of the font you need (arial.ttf
). Place it in the assets
folder. (Inside assets folder create new folder named fonts and place it inside it.) Use the following code to apply the font to your TextView
:
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/arial.ttf");
textView.setTypeface(type);
How do I enable the column selection mode in Eclipse?
As RichieHindle pointed out the shortcut for column (block) selection is Alt+Shift+A
. The problem I ran into is that the Android SDK on Eclipse uses 3 shortcuts that all start with Alt+Shift+A
, so if you type that, you'll be given a choice of continuing with D
, S
, or R
.
To solve this I redefined the column selection as Alt+Shift+A,A
(Alt
, Shift
, A
pressed together and then followed by a subsequent A
). To do this go to Windows > Preferences
then type keys
or navigate to General > Keys
. Under the Keys enter the filter text
of block selection
to quickly find the shortcut listing for toggle block selection
. Here you can adjust the shortcut for column selection as you wish.
How do I tell what type of value is in a Perl variable?
$x
is always a scalar. The hint is the sigil $
: any variable (or dereferencing of some other type) starting with $
is a scalar. (See perldoc perldata for more about data types.)
A reference is just a particular type of scalar.
The built-in function ref
will tell you what kind of reference it is. On the other hand, if you have a blessed reference, ref
will only tell you the package name the reference was blessed into, not the actual core type of the data (blessed references can be hashrefs, arrayrefs or other things). You can use Scalar::Util 's reftype
will tell you what type of reference it is:
use Scalar::Util qw(reftype);
my $x = bless {}, 'My::Foo';
my $y = { };
print "type of x: " . ref($x) . "\n";
print "type of y: " . ref($y) . "\n";
print "base type of x: " . reftype($x) . "\n";
print "base type of y: " . reftype($y) . "\n";
...produces the output:
type of x: My::Foo
type of y: HASH
base type of x: HASH
base type of y: HASH
For more information about the other types of references (e.g. coderef, arrayref etc), see this question: How can I get Perl's ref() function to return REF, IO, and LVALUE? and perldoc perlref.
Note: You should not use ref
to implement code branches with a blessed object (e.g. $ref($a) eq "My::Foo" ? say "is a Foo object" : say "foo not defined";
) -- if you need to make any decisions based on the type of a variable, use isa
(i.e if ($a->isa("My::Foo") { ...
or if ($a->can("foo") { ...
). Also see polymorphism.
SQLException : String or binary data would be truncated
With Linq To SQL I debugged by logging the context, eg. Context.Log = Console.Out
Then scanned the SQL to check for any obvious errors, there were two:
-- @p46: Input Char (Size = -1; Prec = 0; Scale = 0) [some long text value1]
-- @p8: Input Char (Size = -1; Prec = 0; Scale = 0) [some long text value2]
the last one I found by scanning the table schema against the values, the field was nvarchar(20) but the value was 22 chars
-- @p41: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [1234567890123456789012]
Read a Csv file with powershell and capture corresponding data
What you should be looking at is Import-Csv
Once you import the CSV you can use the column header as the variable.
Example CSV:
Name | Phone Number | Email
Elvis | 867.5309 | [email protected]
Sammy | 555.1234 | [email protected]
Now we will import the CSV, and loop through the list to add to an array. We can then compare the value input to the array:
$Name = @()
$Phone = @()
Import-Csv H:\Programs\scripts\SomeText.csv |`
ForEach-Object {
$Name += $_.Name
$Phone += $_."Phone Number"
}
$inputNumber = Read-Host -Prompt "Phone Number"
if ($Phone -contains $inputNumber)
{
Write-Host "Customer Exists!"
$Where = [array]::IndexOf($Phone, $inputNumber)
Write-Host "Customer Name: " $Name[$Where]
}
And here is the output:
Cross-Origin Read Blocking (CORB)
In most cases, the blocked response should not affect the web page's behavior and the CORB error message can be safely ignored. For example, the warning may occur in cases when the body of the blocked response was empty already, or when the response was going to be delivered to a context that can't handle it (e.g., a HTML document such as a 404 error page being delivered to an tag).
https://www.chromium.org/Home/chromium-security/corb-for-developers
I had to clean my browser's cache, I was reading in this link, that, if the request get a empty response, we get this warning error. I was getting some CORS on my request, and so the response of this request got empty, All I had to do was clear the browser's cache, and the CORS got away. I was receiving CORS because the chrome had saved the PORT number on the cache, The server would just accept localhost:3010
and I was doing localhost:3002
, because of the cache.
what does this mean ? image/png;base64?
That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).
An "and" operator for an "if" statement in Bash
What you have should work, unless ${STATUS}
is empty. It would probably be better to do:
if ! [ "${STATUS}" -eq 200 ] 2> /dev/null && [ "${STRING}" != "${VALUE}" ]; then
or
if [ "${STATUS}" != 200 ] && [ "${STRING}" != "${VALUE}" ]; then
It's hard to say, since you haven't shown us exactly what is going wrong with your script.
Personal opinion: never use [[
. It suppresses important error messages and is not portable to different shells.
How do I use TensorFlow GPU?
Uninstall tensorflow and install only tensorflow-gpu; this should be sufficient. By default, this should run on the GPU and not the CPU. However, further you can do the following to specify which GPU you want it to run on.
If you have an nvidia GPU, find out your GPU id using the command nvidia-smi
on the terminal. After that, add these lines in your script:
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = #GPU_ID from earlier
config = tf.ConfigProto()
sess = tf.Session(config=config)
For the functions where you wish to use GPUs, write something like the following:
with tf.device(tf.DeviceSpec(device_type="GPU", device_index=gpu_id)):
How to npm install to a specified directory?
I am using a powershell build and couldn't get npm to run without changing the current directory.
Ended up using the start command and just specifying the working directory:
start "npm" -ArgumentList "install --warn" -wo $buildFolder
Converting Secret Key into a String and Vice Versa
You can convert the SecretKey
to a byte array (byte[]
), then Base64 encode that to a String
. To convert back to a SecretKey
, Base64 decode the String and use it in a SecretKeySpec
to rebuild your original SecretKey
.
For Java 8
SecretKey to String:
// create new key
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
// get base64 encoded version of the key
String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());
String to SecretKey:
// decode the base64 encoded string
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
For Java 7 and before (including Android):
NOTE I: you can skip the Base64 encoding/decoding part and just store the byte[]
in SQLite. That said, performing Base64 encoding/decoding is not an expensive operation and you can store strings in almost any DB without issues.
NOTE II: Earlier Java versions do not include a Base64 in one of the java.lang
or java.util
packages. It is however possible to use codecs from Apache Commons Codec, Bouncy Castle or Guava.
SecretKey to String:
// CREATE NEW KEY
// GET ENCODED VERSION OF KEY (THIS CAN BE STORED IN A DB)
SecretKey secretKey;
String stringKey;
try {secretKey = KeyGenerator.getInstance("AES").generateKey();}
catch (NoSuchAlgorithmException e) {/* LOG YOUR EXCEPTION */}
if (secretKey != null) {stringKey = Base64.encodeToString(secretKey.getEncoded(), Base64.DEFAULT)}
String to SecretKey:
// DECODE YOUR BASE64 STRING
// REBUILD KEY USING SecretKeySpec
byte[] encodedKey = Base64.decode(stringKey, Base64.DEFAULT);
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
Convert date time string to epoch in Bash
What you're looking for is date --date='06/12/2012 07:21:22' +"%s"
. Keep in mind that this assumes you're using GNU coreutils, as both --date
and the %s
format string are GNU extensions. POSIX doesn't specify either of those, so there is no portable way of making such conversion even on POSIX compliant systems.
Consult the appropriate manual page for other versions of date
.
Note: bash --date
and -d
option expects the date in US or ISO8601 format, i.e. mm/dd/yyyy
or yyyy-mm-dd
, not in UK, EU, or any other format.
cat, grep and cut - translated to python
You need a loop over the lines of a file, you need to learn about string methods
with open(filename,'r') as f:
for line in f.readlines():
# python can do regexes, but this is for s fixed string only
if "something" in line:
idx1 = line.find('"')
idx2 = line.find('"', idx1+1)
field = line[idx1+1:idx2-1]
print(field)
and you need a method to pass the filename to your python program and while you are at it, maybe also the string to search for...
For the future, try to ask more focused questions if you can,
Parse JSON in JavaScript?
If you use jQuery, it is simple:
var response = '{"result":true,"count":1}';
var obj = $.parseJSON(response);
alert(obj.result); //true
alert(obj.count); //1
Quicker way to get all unique values of a column in VBA?
Use Excel's AdvancedFilter function to do this.
Using Excels inbuilt C++ is the fastest way with smaller datasets, using the dictionary is faster for larger datasets. For example:
Copy values in Column A and insert the unique values in column B:
Range("A1:A6").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("B1"), Unique:=True
It works with multiple columns too:
Range("A1:B4").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("D1:E1"), Unique:=True
Be careful with multiple columns as it doesn't always work as expected. In those cases I resort to removing duplicates which works by choosing a selection of columns to base uniqueness. Ref: MSDN - Find and remove duplicates
Here I remove duplicate columns based on the third column:
Range("A1:C4").RemoveDuplicates Columns:=3, Header:=xlNo
Here I remove duplicate columns based on the second and third column:
Range("A1:C4").RemoveDuplicates Columns:=Array(2, 3), Header:=xlNo
How do I make an input field accept only letters in javaScript?
If you want only letters - so from a to z, lower case or upper case, excluding everything else (numbers, blank spaces, symbols), you can modify your function like this:
function validate() {
if (document.myForm.name.value == "") {
alert("Enter a name");
document.myForm.name.focus();
return false;
}
if (!/^[a-zA-Z]*$/g.test(document.myForm.name.value)) {
alert("Invalid characters");
document.myForm.name.focus();
return false;
}
}
GROUP BY + CASE statement
Your query would work already - except that you are running into naming conflicts or just confusing the output column (the CASE
expression) with source column result
, which has different content.
...
GROUP BY model.name, attempt.type, attempt.result
...
You need to GROUP BY
your CASE
expression instead of your source column:
...
GROUP BY model.name, attempt.type
, CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END
...
Or provide a column alias that's different from any column name in the FROM
list - or else that column takes precedence:
SELECT ...
, CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END AS result1
...
GROUP BY model.name, attempt.type, result1
...
The SQL standard is rather peculiar in this respect. Quoting the manual here:
An output column's name can be used to refer to the column's value in
ORDER BY
and GROUP BY
clauses, but not in the WHERE
or HAVING
clauses;
there you must write out the expression instead.
And:
If an ORDER BY
expression is a simple name that matches both an output
column name and an input column name, ORDER BY
will interpret it as
the output column name. This is the opposite of the choice that GROUP BY
will make in the same situation. This inconsistency is made to be
compatible with the SQL standard.
Bold emphasis mine.
These conflicts can be avoided by using positional references (ordinal numbers) in GROUP BY
and ORDER BY
, referencing items in the SELECT
list from left to right. See solution below.
The drawback is, that this may be harder to read and vulnerable to edits in the SELECT
list (one might forget to adapt positional references accordingly).
But you do not have to add the column day
to the GROUP BY
clause, as long as it holds a constant value (CURRENT_DATE-1
).
Rewritten and simplified with proper JOIN syntax and positional references it could look like this:
SELECT m.name
, a.type
, CASE WHEN a.result = 0 THEN 0 ELSE 1 END AS result
, CURRENT_DATE - 1 AS day
, count(*) AS ct
FROM attempt a
JOIN prod_hw_id p USING (hard_id)
JOIN model m USING (model_id)
WHERE ts >= '2013-11-06 00:00:00'
AND ts < '2013-11-07 00:00:00'
GROUP BY 1,2,3
ORDER BY 1,2,3;
Also note that I am avoiding the column name time
. That's a reserved word and should never be used as identifier. Besides, your "time" obviously is a timestamp
or date
, so that is rather misleading.
Create a string of variable length, filled with a repeated character
The best way to do this (that I've seen) is
var str = new Array(len + 1).join( character );
That creates an array with the given length, and then joins it with the given string to repeat. The .join()
function honors the array length regardless of whether the elements have values assigned, and undefined values are rendered as empty strings.
You have to add 1 to the desired length because the separator string goes between the array elements.
How do you import an Eclipse project into Android Studio now?
Stop installing android studio 3.0.1 and go back 2.3.3 ( Stable version) . Check for the stable version and you can find them a lot
All you have to do uninstall and go back to the other version. Yes it asks to create gradle file seperately which is completely new to me!
Failure is the stepping stone for success..
Pycharm and sys.argv arguments
For the sake of others who are wondering on how to get to this window. Here's how:
You can access this by clicking on Select Run/Debug Configurations
(to the left of ) and going to the Edit Configurations
. A
gif provided for clarity.
Magento: get a static block as html in a phtml file
If you have created CMS block named 'block_identifier' from admin panel.
Then following will be code to call them in .phtml
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('block_identifier')->toHtml();
?>
Mod in Java produces negative numbers
The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results. There's some more information about it in this question.
You can find the positive value by doing this:
int i = (((-1 % 2) + 2) % 2)
or this:
int i = -1 % 2;
if (i<0) i += 2;
(obviously -1 or 2 can be whatever you want the numerator or denominator to be)
How do I get the max ID with Linq to Entity?
NisaPrieto
Users user = bd.Users.Where(u=> u.UserAge > 21).Max(u => u.UserID);
will not work because MAX returns the same type of variable that the field is so in this case is an INT not an User object.
Can I do Model->where('id', ARRAY) multiple where conditions?
If you need by several params:
$ids = [1,2,3,4];
$not_ids = [5,6,7,8];
DB::table('table')->whereIn('id', $ids)
->whereNotIn('id', $not_ids)
->where('status', 1)
->get();
Update data on a page without refreshing
Suppose you want to display some live feed content (say livefeed.txt) on you web page without any page refresh then the following simplified example is for you.
In the below html file, the live data gets updated on the div element of id "liveData"
index.html
<!DOCTYPE html>
<html>
<head>
<title>Live Update</title>
<meta charset="UTF-8">
<script type="text/javascript" src="autoUpdate.js"></script>
</head>
<div id="liveData">
<p>Loading Data...</p>
</div>
</body>
</html>
Below autoUpdate.js reads the live data using XMLHttpRequest object and updates the html div element on every 1 second. I have given comments on most part of the code for better understanding.
autoUpdate.js
window.addEventListener('load', function()
{
var xhr = null;
getXmlHttpRequestObject = function()
{
if(!xhr)
{
// Create a new XMLHttpRequest object
xhr = new XMLHttpRequest();
}
return xhr;
};
updateLiveData = function()
{
var now = new Date();
// Date string is appended as a query with live data
// for not to use the cached version
var url = 'livefeed.txt?' + now.getTime();
xhr = getXmlHttpRequestObject();
xhr.onreadystatechange = evenHandler;
// asynchronous requests
xhr.open("GET", url, true);
// Send the request over the network
xhr.send(null);
};
updateLiveData();
function evenHandler()
{
// Check response is ready or not
if(xhr.readyState == 4 && xhr.status == 200)
{
dataDiv = document.getElementById('liveData');
// Set current data text
dataDiv.innerHTML = xhr.responseText;
// Update the live data every 1 sec
setTimeout(updateLiveData(), 1000);
}
}
});
For testing purpose: Just write some thing in the livefeed.txt - You will get updated the same in index.html without any refresh.
livefeed.txt
Hello
World
blah..
blah..
Note: You need to run the above code on the web server (ex: http://localhost:1234/index.html) not as a client html file (ex: file:///C:/index.html).
How does delete[] know it's an array?
Agree that the compiler doesn't know if it is an array or not. It is up to the programmer.
The compiler sometimes keep track of how many objects need to be deleted by over-allocating enough to store the array size, but not always necessary.
For a complete specification when extra storage is allocated, please refer to C++ ABI (how compilers are implemented): Itanium C++ ABI: Array Operator new Cookies
Adding hours to JavaScript Date object?
I also think the original object should not be modified. So to save future manpower here's a combined solution based on Jason Harwig's and Tahir Hasan answers:
Date.prototype.addHours= function(h){
var copiedDate = new Date();
copiedDate.setTime(this.getTime() + (h*60*60*1000));
return copiedDate;
}
Methods vs Constructors in Java
In Java, classes you write are Objects. Constructors construct those objects. For example if I have an Apple.class
like so:
public class Apple {
//instance variables
String type; // macintosh, green, red, ...
/**
* This is the default constructor that gets called when you use
* Apple a = new Apple(); which creates an Apple object named a.
*/
public Apple() {
// in here you initialize instance variables, and sometimes but rarely
// do other functionality (at least with basic objects)
this.type = "macintosh"; // the 'this' keyword refers to 'this' object. so this.type refers to Apple's 'type' instance variable.
}
/**
* this is another constructor with a parameter. You can have more than one
* constructor as long as they have different parameters. It creates an Apple
* object when called using Apple a = new Apple("someAppleType");
*/
public Apple(String t) {
// when the constructor is called (i.e new Apple() ) this code is executed
this.type = t;
}
/**
* methods in a class are functions. They are whatever functionality needed
* for the object
*/
public String someAppleRelatedMethod(){
return "hello, Apple class!";
}
public static void main(String[] args) {
// construct an apple
Apple a = new Apple("green");
// 'a' is now an Apple object and has all the methods and
// variables of the Apple class.
// To use a method from 'a':
String temp = a.someAppleRelatedMethod();
System.out.println(temp);
System.out.println("a's type is " + a.type);
}
}
Hopefully I explained everything in the comments of the code, but here is a summary:
Constructors 'construct' an object of type of the class. The constructor must be named the same thing as the class. They are mostly used for initializing instance varibales
Methods are functionality of the objects.
how to get value of selected item in autocomplete
$(document).ready(function () {
$('#tags').on('change', function () {
$('#tagsname').html('You selected: ' + this.value);
}).change();
$('#tags').on('blur', function (e, ui) {
$('#tagsname').html('You selected: ' + ui.item.value);
});
});
How do I directly modify a Google Chrome Extension File? (.CRX)
Now Chrome is multi-user so Extensions
should be nested under the OS user profile then the Chrome user profile, My first Chrome user was called Profile 1
, my Extensions
path was C:\Users\
username
\AppData\Local\Google\Chrome\User Data\
Profile 1
\Extensions\
.
To find yours Navigate to chrome://version/
(I use about:
out of laziness).
Notice the Profile Path
and just append \Extensions\
and you have yours.
Hope this brings this info on this question up to date more.
Getting the parameters of a running JVM
Windows 10 or Windows Server 2016 provide such information in their standard task manager. A rare case for production, but if the target JVM is running on Windows, the simplest way to see its parameters is to press Ctrl+Alt+Delete, choose the Processes tab and add the Command line column (by clicking the right mouse button on any existing column header).
error CS0103: The name ' ' does not exist in the current context
using System;
using System.Collections.Generic; (???????? ?????????? ?? ?? ?????
using System.Linq; ?????? PlayerScript.health =
using System.Text; 999999; ??? ?? ???? ??????)
using System.Threading.Tasks;
using UnityEngine;
namespace OneHack
{
public class One
{
public Rect RT_MainMenu = new Rect(0f, 100f, 120f, 100f); //Rect ??? ????????????????? ???? ?? x,y ? ??????, ??????.
public int ID_RTMainMenu = 1;
private bool MainMenu = true;
private void Menu_MainMenu(int id) //??????? ????
{
if (GUILayout.Button("???????? ????? ??????", new GUILayoutOption[0]))
{
if (GUILayout.Button("??????????", new GUILayoutOption[0]))
{
PlayerScript.health = 999999;//??? ??????? ?? ?????? ? ?????? ??????????????? ???????? 999999 //????? ???, ??????? ????? ??????????? ??? ??????? ?? ??? ??????
}
}
}
private void OnGUI()
{
if (this.MainMenu)
{
this.RT_MainMenu = GUILayout.Window(this.ID_RTMainMenu, this.RT_MainMenu, new GUI.WindowFunction(this.Menu_MainMenu), "MainMenu", new GUILayoutOption[0]);
}
}
private void Update() //????????? ??????????? ?????, ??? ??? ????? ????? ????????? ????? ??????????? ??????????
{
if (Input.GetKeyDown(KeyCode.Insert)) //?????? ?? ??????? ????? ??????????? ? ??????????? ????, ????? ????????? ??????
{
this.MainMenu = !this.MainMenu;
}
}
}
}
How to start a Process as administrator mode in C#
Process proc = new Process();
ProcessStartInfo info =
new ProcessStartInfo("Your Process name".exe, "Arguments");
info.WindowStyle = ProcessWindowStyle.Hidden;
info.UseShellExecute =true;
info.Verb ="runas";
proc.StartInfo = info;
proc.Start();
How to use EOF to run through a text file in C?
How you detect EOF depends on what you're using to read the stream:
function result on EOF or error
-------- ----------------------
fgets() NULL
fscanf() number of succesful conversions
less than expected
fgetc() EOF
fread() number of elements read
less than expected
Check the result of the input call for the appropriate condition above, then call feof()
to determine if the result was due to hitting EOF or some other error.
Using fgets()
:
char buffer[BUFFER_SIZE];
while (fgets(buffer, sizeof buffer, stream) != NULL)
{
// process buffer
}
if (feof(stream))
{
// hit end of file
}
else
{
// some other error interrupted the read
}
Using fscanf()
:
char buffer[BUFFER_SIZE];
while (fscanf(stream, "%s", buffer) == 1) // expect 1 successful conversion
{
// process buffer
}
if (feof(stream))
{
// hit end of file
}
else
{
// some other error interrupted the read
}
Using fgetc()
:
int c;
while ((c = fgetc(stream)) != EOF)
{
// process c
}
if (feof(stream))
{
// hit end of file
}
else
{
// some other error interrupted the read
}
Using fread()
:
char buffer[BUFFER_SIZE];
while (fread(buffer, sizeof buffer, 1, stream) == 1) // expecting 1
// element of size
// BUFFER_SIZE
{
// process buffer
}
if (feof(stream))
{
// hit end of file
}
else
{
// some other error interrupted read
}
Note that the form is the same for all of them: check the result of the read operation; if it failed, then check for EOF. You'll see a lot of examples like:
while(!feof(stream))
{
fscanf(stream, "%s", buffer);
...
}
This form doesn't work the way people think it does, because feof()
won't return true until after you've attempted to read past the end of the file. As a result, the loop executes one time too many, which may or may not cause you some grief.
open read and close a file in 1 line of code
I frequently do something like this when I need to get a few lines surrounding something I've grepped in a log file:
$ grep -n "xlrd" requirements.txt | awk -F ":" '{print $1}'
54
$ python -c "with open('requirements.txt') as file: print ''.join(file.readlines()[52:55])"
wsgiref==0.1.2
xlrd==0.9.2
xlwt==0.7.5
List comprehension vs map
I tried the code by @alex-martelli but found some discrepancies
python -mtimeit -s "xs=range(123456)" "map(hex, xs)"
1000000 loops, best of 5: 218 nsec per loop
python -mtimeit -s "xs=range(123456)" "[hex(x) for x in xs]"
10 loops, best of 5: 19.4 msec per loop
map takes the same amount of time even for very large ranges while using list comprehension takes a lot of time as is evident from my code. So apart from being considered "unpythonic", I have not faced any performance issues relating to usage of map.
Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'
If you are using PHPMyAdmin
You can be solved this issue by doing this:
CAUTION: Don't use this solution if you want to maintain existing
records in your table.
Step 1: Select database export method to custom:
Step 2: Please make sure to check truncate table before insert in data creation options:
Now you are able to import this database successfully.
Loop through files in a directory using PowerShell
To get the content of a directory you can use
$files = Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files\"
Then you can loop over this variable as well:
for ($i=0; $i -lt $files.Count; $i++) {
$outfile = $files[$i].FullName + "out"
Get-Content $files[$i].FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}
An even easier way to put this is the foreach
loop (thanks to @Soapy and @MarkSchultheiss):
foreach ($f in $files){
$outfile = $f.FullName + "out"
Get-Content $f.FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}
MYSQL import data from csv using LOAD DATA INFILE
You can use LOAD DATA INFILE command to import csv file into table.
Check this link MySQL - LOAD DATA INFILE.
LOAD DATA LOCAL INFILE 'abc.csv' INTO TABLE abc
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(col1, col2, col3, col4, col5...);
For MySQL 8.0 users:
Using the LOCAL
keyword hold security risks and as of MySQL 8.0 the LOCAL
capability is set to False
by default. You might see the error:
ERROR 1148: The used command is not allowed with this MySQL version
You can overwrite it by following the instructions in the docs.
Beware that such overwrite does not solve the security issue but rather just an acknowledge that you are aware and willing to take the risk.
How to add Action bar options menu in Android Fragments
I am late for the answer but I think this is another solution which is
not mentioned here so posting.
Step 1: Make a xml of menu which you want to add like I have to add a filter action on my action bar so I have created a xml filter.xml. The main line to notice is android:orderInCategory this will show the action icon at first or last wherever you want to show. One more thing to note down is the value, if the value is less then it will show at first and if value is greater then it will show at last.
filter.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="@+id/action_filter"
android:title="@string/filter"
android:orderInCategory="10"
android:icon="@drawable/filter"
app:showAsAction="ifRoom" />
</menu>
Step 2: In onCreate() method of fragment just put the below line as mentioned, which is responsible for calling back onCreateOptionsMenu(Menu menu, MenuInflater inflater) method just like in an Activity.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Step 3: Now add the method onCreateOptionsMenu which will be override as:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.filter, menu); // Use filter.xml from step 1
}
Step 4: Now add onOptionsItemSelected method by which you can implement logic whatever you want to do when you select the added action icon from actionBar:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_filter){
//Do whatever you want to do
return true;
}
return super.onOptionsItemSelected(item);
}
Conversion between UTF-8 ArrayBuffer and String
If you are doing this in browser there are no character encoding libraries built-in, but you can get
by with:
function pad(n) {
return n.length < 2 ? "0" + n : n;
}
var array = new Uint8Array(data);
var str = "";
for( var i = 0, len = array.length; i < len; ++i ) {
str += ( "%" + pad(array[i].toString(16)))
}
str = decodeURIComponent(str);
Here's a demo that decodes a 3-byte UTF-8 unit: http://jsfiddle.net/Z9pQE/
Node.js Logging
The "logger.setLevel('ERROR');" is causing the problem. I do not understand why, but when I set it to anything other than "ALL", nothing gets printed in the file. I poked around a little bit and modified your code. It is working fine for me. I created two files.
logger.js
var log4js = require('log4js');
log4js.clearAppenders()
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('test.log'), 'test');
var logger = log4js.getLogger('test');
logger.setLevel('ERROR');
var getLogger = function() {
return logger;
};
exports.logger = getLogger();
logger.test.js
var logger = require('./logger.js')
var log = logger.logger;
log.error("ERROR message");
log.trace("TRACE message");
When I run "node logger.test.js", I see only "ERROR message" in test.log file. If I change the level to "TRACE" then both lines are printed on test.log.
Android Studio - UNEXPECTED TOP-LEVEL EXCEPTION:
I had similar problem when I tried to build a signed apk for my app.
Strange, it happened only when I wanted to build a release apk, while on debug apk everything worked OK.
Finally, looking on this thread, I checked for support library duplications in build.gradle and removed any duplications but this wasn't enough..
I had to do clean project and only then finally I've got it to work.
Android Overriding onBackPressed()
Best and most generic way to control the music is to create a mother Activity in which you override startActivity(Intent intent)
- in it you put shouldPlay=true
,
and onBackPressed()
- in it you put shouldPlay = true
.
onStop
- in it you put a conditional mediaPlayer.stop with shouldPlay as condition
Then, just extend the mother activity to all other activities, and no code duplicating is needed.
Alternative to a goto statement in Java
The easiest is:
int label = 0;
loop:while(true) {
switch(state) {
case 0:
// Some code
state = 5;
break;
case 2:
// Some code
state = 4;
break;
...
default:
break loop;
}
}
How does one convert a HashMap to a List in Java?
If you wanna maintain the same order in your list, say:
your Map looks like:
map.put(1, "msg1")
map.put(2, "msg2")
map.put(3, "msg3")
and you want your list looks like
["msg1", "msg2", "msg3"] // same order as the map
you will have to iterate through the Map:
// sort your map based on key, otherwise you will get IndexOutofBoundException
Map<String, String> treeMap = new TreeMap<String, String>(map)
List<String> list = new List<String>();
for (treeMap.Entry<Integer, String> entry : treeMap.entrySet()) {
list.add(entry.getKey(), entry.getValue());
}
CSS3 :unchecked pseudo-class
I think you are trying to over complicate things. A simple solution is to just style your checkbox by default with the unchecked styles and then add the checked state styles.
input[type="checkbox"] {
// Unchecked Styles
}
input[type="checkbox"]:checked {
// Checked Styles
}
I apologize for bringing up an old thread but felt like it could have used a better answer.
EDIT (3/3/2016):
W3C Specs state that :not(:checked)
as their example for selecting the unchecked state. However, this is explicitly the unchecked state and will only apply those styles to the unchecked state. This is useful for adding styling that is only needed on the unchecked state and would need removed from the checked state if used on the input[type="checkbox"]
selector. See example below for clarification.
input[type="checkbox"] {
/* Base Styles aka unchecked */
font-weight: 300; // Will be overwritten by :checked
font-size: 16px; // Base styling
}
input[type="checkbox"]:not(:checked) {
/* Explicit Unchecked Styles */
border: 1px solid #FF0000; // Only apply border to unchecked state
}
input[type="checkbox"]:checked {
/* Checked Styles */
font-weight: 900; // Use a bold font when checked
}
Without using :not(:checked)
in the example above the :checked
selector would have needed to use a border: none;
to achieve the same affect.
Use the input[type="checkbox"]
for base styling to reduce duplication.
Use the input[type="checkbox"]:not(:checked)
for explicit unchecked styles that you do not want to apply to the checked state.
Why doesn't the Scanner class have a nextChar method?
The reason is that the Scanner class is designed for reading in whitespace-separated tokens. It's a convenience class that wraps an underlying input stream. Before scanner all you could do was read in single bytes, and that's a big pain if you want to read words or lines. With Scanner you pass in System.in, and it does a number of read() operations to tokenize the input for you. Reading a single character is a more basic operation.
Source
You can use (char) System.in.read();
.
How to move files from one git repo to another (not a clone), preserving history
Having tried various approaches to move a file or folder from one Git repository to another, the only one which seems to work reliably is outlined below.
It involves cloning the repository you want to move the file or folder from, moving that file or folder to the root, rewriting Git history, cloning the target repository and pulling the file or folder with history directly into this target repository.
Stage One
Make a copy of repository A as the following steps make major
changes to this copy which you should not push!
git clone --branch <branch> --origin origin --progress \
-v <git repository A url>
# eg. git clone --branch master --origin origin --progress \
# -v https://username@giturl/scm/projects/myprojects.git
# (assuming myprojects is the repository you want to copy from)
cd into it
cd <git repository A directory>
# eg. cd /c/Working/GIT/myprojects
Delete the link to the original repository to avoid accidentally
making any remote changes (eg. by pushing)
git remote rm origin
Go through your history and files, removing anything that is not in
directory 1. The result is the contents of directory 1 spewed out
into to the base of repository A.
git filter-branch --subdirectory-filter <directory> -- --all
# eg. git filter-branch --subdirectory-filter subfolder1/subfolder2/FOLDER_TO_KEEP -- --all
For single file move only: go through what's left and remove
everything except the desired file. (You may need to delete files
you don't want with the same name and commit.)
git filter-branch -f --index-filter \
'git ls-files -s | grep $'\t'FILE_TO_KEEP$ |
GIT_INDEX_FILE=$GIT_INDEX_FILE.new \
git update-index --index-info && \
mv $GIT_INDEX_FILE.new $GIT_INDEX_FILE || echo "Nothing to do"' --prune-empty -- --all
# eg. FILE_TO_KEEP = pom.xml to keep only the pom.xml file from FOLDER_TO_KEEP
Stage Two
Cleanup step
git reset --hard
Cleanup step
git gc --aggressive
Cleanup step
git prune
You may want to import these files into repository B within a directory not the root:
Make that directory
mkdir <base directory> eg. mkdir FOLDER_TO_KEEP
Move files into that directory
git mv * <base directory> eg. git mv * FOLDER_TO_KEEP
Add files to that directory
git add .
Commit your changes and we’re ready to merge these files into the
new repository
git commit
Stage Three
Make a copy of repository B if you don’t have one already
git clone <git repository B url>
# eg. git clone https://username@giturl/scm/projects/FOLDER_TO_KEEP.git
(assuming FOLDER_TO_KEEP is the name of the new repository you are copying to)
cd into it
cd <git repository B directory>
# eg. cd /c/Working/GIT/FOLDER_TO_KEEP
Create a remote connection to repository A as a branch in repository
B
git remote add repo-A-branch <git repository A directory>
# (repo-A-branch can be anything - it's just an arbitrary name)
# eg. git remote add repo-A-branch /c/Working/GIT/myprojects
Pull from this branch (containing only the directory you want to
move) into repository B.
git pull repo-A-branch master --allow-unrelated-histories
The pull copies both files and history. Note: You can use a merge instead of a pull, but pull works better.
Finally, you probably want to clean up a bit by removing the remote
connection to repository A
git remote rm repo-A-branch
Push and you’re all set.
git push
Fastest way to count number of occurrences in a Python list
By the use of Counter dictionary counting the occurrences of all element as well as most common element in python list with its occurrence value in most efficient way.
If our python list is:-
l=['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
To find occurrence of every items in the python list use following:-
\>>from collections import Counter
\>>c=Counter(l)
\>>print c
Counter({'1': 6, '2': 4, '7': 3, '10': 2})
To find most/highest occurrence of items in the python list:-
\>>k=c.most_common()
\>>k
[('1', 6), ('2', 4), ('7', 3), ('10', 2)]
For Highest one:-
\>>k[0][1]
6
For the item just use k[0][0]
\>>k[0][0]
'1'
For nth highest item and its no of occurrence in the list use follow:-
**for n=2 **
\>>print k[n-1][0] # For item
2
\>>print k[n-1][1] # For value
4
Set value to currency in <input type="number" />
You guys are completely right numbers can only go in the numeric field. I use the exact same thing as already listed with a bit of css styling on a span tag:
<span>$</span><input type="number" min="0.01" step="0.01" max="2500" value="25.67">
Then add a bit of styling magic:
span{
position:relative;
margin-right:-20px
}
input[type='number']{
padding-left:20px;
text-align:left;
}
CSS Background image not loading
I'd like to share my debugging process because I was stuck on this issue for at least an hour. Image could not be found when running local host. To add some context, I am styling within a rails app in the following directory:
apps/assets/stylesheets/main.scss
I wanted to render background image in header tag. The following was my original implementation.
header {
text-align: center;
background: linear-gradient(90deg, #d4eece, #d4eece, #d4eece),
url('../images/header.jpg') no-repeat;
background-blend-mode: multiply;
background-size: cover;
}
...as a result I was getting the following error in rails server and the console in Chrome dev tools, respectively:
ActionController::RoutingError (No route matches [GET] "/images/header.jpg")
GET http://localhost:3000/images/header.jpg 404 (Not Found)
I tried different variations of the url:
url('../images/header.jpg') # DID NOT WORK
url('/../images/header.jpg') # DID NOT WORK
url('./../images/header.jpg') # DID NOT WORK
and it still did not work. At that point, I was very confused...I decided to move the image folder from the assets directory (which is the default) to within the stylesheets directory, and tried the following variations of the url:
url('/images/header.jpg') # DID NOT WORK
url('./images/header.jpg') # WORKED
url('images/header.jpg') # WORKED
I no longer got the console and rails server error. But the image still was not showing for some reason. After temporarily giving up, I found out the solution to this was to add a height property in order for the image to be shown...
header {
text-align: center;
height: 390px;
background: linear-gradient(90deg, #d4eece, #d4eece, #d4eece),
url('images/header.jpg') no-repeat;
background-blend-mode: multiply;
background-size: cover;
}
Unfortunately, I am still not sure why the 3 initial url attempts with "../images/header.jpg" did not work on localhost, or when I should or shouldn't be adding a period at the beginning of the url.
It might have something to do with how the default link tag is setup in application.html.erb, or maybe it's a .scss vs .css thing. Or, maybe that's just how the background property with url() works (the image needs to be within same directory as the css file)? Anyhow, this is how I solved the issue with CSS background image not loading on localhost.
How to rotate a div using jQuery
EDIT: Updated for jQuery 1.8
Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: Added code to make it a jQuery function.
For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.
Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.
Here is a jsFiddle.
If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.
HTML
<div class="rotate">
<h1>Rotatey text</h1>
</div>
CSS
/* Totally for style */
.rotate {
background: #F02311;
color: #FFF;
width: 200px;
height: 200px;
text-align: center;
font: normal 1em Arial;
position: relative;
top: 50px;
left: 50px;
}
/* The real code */
.rotated {
-webkit-transform: rotate(45deg); /* Chrome, Safari 3.1+ */
-moz-transform: rotate(45deg); /* Firefox 3.5-15 */
-ms-transform: rotate(45deg); /* IE 9 */
-o-transform: rotate(45deg); /* Opera 10.50-12.00 */
transform: rotate(45deg); /* Firefox 16+, IE 10+, Opera 12.10+ */
}
jQuery
Make sure these are wrapped in $(document).ready
$('.rotate').click(function() {
$(this).toggleClass('rotated');
});
Custom intervals
var rotation = 0;
$('.rotate').click(function() {
rotation += 5;
$(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
'-moz-transform' : 'rotate('+ rotation +'deg)',
'-ms-transform' : 'rotate('+ rotation +'deg)',
'transform' : 'rotate('+ rotation +'deg)'});
});
How do I change the language of moment.js?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MomentJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type="text/javascript" src="moment.js"></script>
<script type="text/javascript" src="locale/ne.js"></script>
</head>
<body>
<script>
jQuery(document).ready(function($) {
moment.locale('en'); // default the locale to English
var localLocale = moment();
moment.locale('ne'); // change the global locale to Nepalese
var ne1 = localLocale.format('LLLL');
var ne2 = moment().format('LLLL');
$('.ne1').text(ne1);
$('.ne2').text(ne2);
});
</script>
<p class="ne1"></p>
<p class="ne2"></p>
</body>
</html>
Demo
Setting up JUnit with IntelliJ IDEA
- Create and setup a "tests" folder
- In the Project sidebar on the left, right-click your project and do New > Directory. Name it "test" or whatever you like.
- Right-click the folder and choose "Mark Directory As > Test Source Root".
- Adding JUnit library
- Right-click your project and choose "Open Module Settings" or hit F4. (Alternatively, File > Project Structure, Ctrl-Alt-Shift-S is probably the "right" way to do this)
- Go to the "Libraries" group, click the little green plus (look up), and choose "From Maven...".
- Search for "junit" -- you're looking for something like "junit:junit:4.11".
- Check whichever boxes you want (Sources, JavaDocs) then hit OK.
- Keep hitting OK until you're back to the code.
Write your first unit test
- Run your tests
- Right-click on your test folder and choose "Run 'All Tests'". Presto, testo.
- To run again, you can either hit the green "Play"-style button that appeared in the new section that popped on the bottom of your window, or you can hit the green "Play"-style button in the top bar.
Android webview & localStorage
A solution that works on my Android 4.2.2, compiled with build target Android 4.4W:
WebSettings settings = webView.getSettings();
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
File databasePath = getDatabasePath("yourDbName");
settings.setDatabasePath(databasePath.getPath());
}
jQuery Force set src attribute for iframe
Use attr
$('#abc_frame').attr('src', url)
This way you can get and set every HTML tag attribute. Note that there is also .prop()
. See .prop() vs .attr() about the differences. Short version: .attr()
is used for attributes as they are written in HTML source code and .prop()
is for all that JavaScript attached to the DOM element.
Remove empty space before cells in UITableView
In 2017, what is working for me is simply this one line
navigationController?.navigationBar.isTranslucent = false
I have no idea why that would even affect it. Perhaps someone could explain. But I'm pretty sure this is the answer most people would look for.
scp or sftp copy multiple files with single command
In my case, I am restricted to only using the sftp command.
So, I had to use a batchfile with sftp. I created a script such as the following. This assumes you are working in the /tmp directory, and you want to put the files in the destdir_on_remote_system on the remote system. This also only works with a noninteractive login. You need to set up public/private keys so you can login without entering a password. Change as needed.
#!/bin/bash
cd /tmp
# start script with list of files to transfer
ls -1 fileset1* > batchfile1
ls -1 fileset2* >> batchfile1
sed -i -e 's/^/put /' batchfile1
echo "cd destdir_on_remote_system" > batchfile
cat batchfile1 >> batchfile
rm batchfile1
sftp -b batchfile user@host
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
What is an .inc and why use it?
It's just a way for the developer to be able to easily identify files which are meant to be used as includes. It's a popular convention. It does not have any special meaning to PHP, and won't change the behaviour of PHP or the script itself.
How to specify test directory for mocha?
Edit : This option is deprecated : https://mochajs.org/#mochaopts
If you want to do it by still just running mocha
on the command line, but wanted to run the tests in a folder ./server-tests
instead of ./test
, create a file at ./test/mocha.opts
with just this in the file:
server-tests
If you wanted to run everything in that folder and subdirectories, put this into test/mocha.opts
server-tests
--recursive
mocha.opts
are the arguments passed in via the command line, so making the first line just the directory you want to change the tests too will redirect from ./test/
Get current clipboard content?
Following will give you the selected content as well as updating the clipboard.
Bind the element id with copy event and then get the selected text. You could replace or modify the text. Get the clipboard and set the new text. To get the exact formatting you need to set the type as "text/hmtl". You may also bind it to the document instead of element.
document.querySelector('element').bind('copy', function(event) {
var selectedText = window.getSelection().toString();
selectedText = selectedText.replace(/\u200B/g, "");
clipboardData = event.clipboardData || window.clipboardData || event.originalEvent.clipboardData;
clipboardData.setData('text/html', selectedText);
event.preventDefault();
});
WebSockets vs. Server-Sent events/EventSource
According to caniuse.com:
You can use a client-only polyfill to extend support of SSE to many other browsers. This is less likely with WebSockets. Some EventSource polyfills:
If you need to support all the browsers, consider using a library like web-socket-js, SignalR or socket.io which support multiple transports such as WebSockets, SSE, Forever Frame and AJAX long polling. These often require modifications to the server side as well.
Learn more about SSE from:
Learn more about WebSockets from:
Other differences:
- WebSockets supports arbitrary binary data, SSE only uses UTF-8
Copying one structure to another
If the structures are of compatible types, yes, you can, with something like:
memcpy (dest_struct, source_struct, sizeof (*dest_struct));
The only thing you need to be aware of is that this is a shallow copy. In other words, if you have a char *
pointing to a specific string, both structures will point to the same string.
And changing the contents of one of those string fields (the data that the char *
points to, not the char *
itself) will change the other as well.
If you want a easy copy without having to manually do each field but with the added bonus of non-shallow string copies, use strdup
:
memcpy (dest_struct, source_struct, sizeof (*dest_struct));
dest_struct->strptr = strdup (source_struct->strptr);
This will copy the entire contents of the structure, then deep-copy the string, effectively giving a separate string to each structure.
And, if your C implementation doesn't have a strdup
(it's not part of the ISO standard), get one from here.
Checking for NULL pointer in C/C++
In my experience, tests of the form if (ptr)
or if (!ptr)
are preferred. They do not depend on the definition of the symbol NULL
. They do not expose the opportunity for the accidental assignment. And they are clear and succinct.
Edit: As SoapBox points out in a comment, they are compatible with C++ classes such as auto_ptr
that are objects that act as pointers and which provide a conversion to bool
to enable exactly this idiom. For these objects, an explicit comparison to NULL
would have to invoke a conversion to pointer which may have other semantic side effects or be more expensive than the simple existence check that the bool
conversion implies.
I have a preference for code that says what it means without unneeded text. if (ptr != NULL)
has the same meaning as if (ptr)
but at the cost of redundant specificity. The next logical thing is to write if ((ptr != NULL) == TRUE)
and that way lies madness. The C language is clear that a boolean tested by if
, while
or the like has a specific meaning of non-zero value is true and zero is false. Redundancy does not make it clearer.
How to use conditional breakpoint in Eclipse?
1. Create a class
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s[] = {"app","amm","abb","akk","all"};
doForAllTabs(s);
}
public static void doForAllTabs(String[] tablist){
for(int i = 0; i<tablist.length;i++){
System.out.println(tablist[i]);
}
}
}
2. Right click on left side of System.out.println(tablist[i]); in Eclipse
--> select Toggle Breakpoint
3. Right click on toggle point --> select Breakpoint properties
4. Check the Conditional Check Box --> write tablist[i].equalsIgnoreCase("amm") in text field --> Click on OK
5. Right click on class --> Debug As --> Java Application
Executing a stored procedure within a stored procedure
Inline Stored procedure we using as per our need.
Example like different Same parameter with different values we have to use in queries..
Create Proc SP1
(
@ID int,
@Name varchar(40)
-- etc parameter list, If you don't have any parameter then no need to pass.
)
AS
BEGIN
-- Here we have some opereations
-- If there is any Error Before Executing SP2 then SP will stop executing.
Exec SP2 @ID,@Name,@SomeID OUTPUT
-- ,etc some other parameter also we can use OutPut parameters like
-- @SomeID is useful for some other operations for condition checking insertion etc.
-- If you have any Error in you SP2 then also it will stop executing.
-- If you want to do any other operation after executing SP2 that we can do here.
END
Excel - Button to go to a certain sheet
Alternately, if you are using a Macro Enabled workbook:
Add any control at all from the Developer -> Insert (Probably a button)
When it asks what Macro to assign, choose New. For the code for the generated module enter something like:
Thisworkbook.Sheets("Sheet Name").Activate
However, if you are not using Macros in your work book. Ooo's approach is definitely surperior as hyperlinks will work with no need to trust the document.
Difference Between Schema / Database in MySQL
in MySQL schema is synonym of database.
Its quite confusing for beginner people who jump to MySQL and very first day find the word schema, so guys nothing to worry as both are same.
When you are starting MySQL for the first time you need to create a database (like any other database system) to work with so you can CREATE SCHEMA which is nothing but CREATE DATABASE
In some other database system schema represents a part of database or a collection of Tables, and collection of schema is a database.
Finding elements not in a list
>>> item = set([0,1,2,3,4,5,6,7,8,9])
>>> z = set([2,3,4])
>>> print item - z
set([0, 1, 5, 6, 7, 8, 9])
Can a class member function template be virtual?
No they can't. But:
template<typename T>
class Foo {
public:
template<typename P>
void f(const P& p) {
((T*)this)->f<P>(p);
}
};
class Bar : public Foo<Bar> {
public:
template<typename P>
void f(const P& p) {
std::cout << p << std::endl;
}
};
int main() {
Bar bar;
Bar *pbar = &bar;
pbar -> f(1);
Foo<Bar> *pfoo = &bar;
pfoo -> f(1);
};
has much the same effect if all you want to do is have a common interface and defer implementation to subclasses.
Check if ADODB connection is open
This topic is old but if other people like me search a solution, this is a solution that I have found:
Public Function DBStats() As Boolean
On Error GoTo errorHandler
If Not IsNull(myBase.Version) Then
DBStats = True
End If
Exit Function
errorHandler:
DBStats = False
End Function
So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":
Dim BaseAccess As New myClass
BaseAccess.DBOpen 'I open connection
Debug.Print BaseAccess.DBStats ' I test and that tell me true
BaseAccess.DBClose ' I close the connection
Debug.Print BaseAccess.DBStats ' I test and tell me false
Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing"
Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false
Oracle client and networking components were not found
In my case this was because a file named ociw32.dll had been placed in c:\windows\system32. This is however only allowed to exist in c:\oracle\11.2.0.3\bin.
Deleting the file from system32, which had been placed there by an installation of Crystal Reports, fixed this issue
How to convert hex strings to byte values in Java
Looking at the sample I guess you mean that a string array is actually an array of HEX representation of bytes, don't you?
If yes, then for each string item I would do the following:
- check that a string consists only of 2 characters
- these chars are in '0'..'9' or 'a'..'f' interval (take their case into account
as well)
- convert each character to a corresponding number, subtracting code value of '0' or 'a'
build a byte value, where first char is higher bits and second char is lower ones. E.g.
int byteVal = (firstCharNumber << 4) | secondCharNumber;
Matrix Transpose in Python
To complete J.F. Sebastian's answer, if you have a list of lists with different lengths, check out this great post from ActiveState. In short:
The built-in function zip does a similar job, but truncates the result
to the length of the shortest list, so some elements from the original
data may be lost afterwards.
To handle list of lists with different lengths, use:
def transposed(lists):
if not lists: return []
return map(lambda *row: list(row), *lists)
def transposed2(lists, defval=0):
if not lists: return []
return map(lambda *row: [elem or defval for elem in row], *lists)
"R cannot be resolved to a variable"?
Check if the package name in the AndroidManifest.xml file is the same than the package name of your java class.
Eg.
AndroidManifest.xml
package="com.example.de.vogella.android.widget.example"
In your class MyWidgetProvider.java
package com.example.de.vogella.android.widget.example;
It was the cause of my error in this example.
Regular Expression to match valid dates
If you're going to insist on doing this with a regular expression, I'd recommend something like:
( (0?1|0?3| <...> |10|11|12) / (0?1| <...> |30|31) |
0?2 / (0?1| <...> |28|29) )
/ (19|20)[0-9]{2}
This might make it possible to read and understand.
MySQL user DB does not have password columns - Installing MySQL on OSX
In MySQL 5.7, the password field in mysql.user table field was removed, now the field name is 'authentication_string'.
First choose the database:
mysql>use mysql;
And then show the tables:
mysql>show tables;
You will find the user table, now let's see its fields:
mysql> describe user;
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host | char(60) | NO | PRI | | |
| User | char(16) | NO | PRI | | |
| Select_priv | enum('N','Y') | NO | | N | |
| Insert_priv | enum('N','Y') | NO | | N | |
| Update_priv | enum('N','Y') | NO | | N | |
| Delete_priv | enum('N','Y') | NO | | N | |
| Create_priv | enum('N','Y') | NO | | N | |
| Drop_priv | enum('N','Y') | NO | | N | |
| Reload_priv | enum('N','Y') | NO | | N | |
| Shutdown_priv | enum('N','Y') | NO | | N | |
| Process_priv | enum('N','Y') | NO | | N | |
| File_priv | enum('N','Y') | NO | | N | |
| Grant_priv | enum('N','Y') | NO | | N | |
| References_priv | enum('N','Y') | NO | | N | |
| Index_priv | enum('N','Y') | NO | | N | |
| Alter_priv | enum('N','Y') | NO | | N | |
| Show_db_priv | enum('N','Y') | NO | | N | |
| Super_priv | enum('N','Y') | NO | | N | |
| Create_tmp_table_priv | enum('N','Y') | NO | | N | |
| Lock_tables_priv | enum('N','Y') | NO | | N | |
| Execute_priv | enum('N','Y') | NO | | N | |
| Repl_slave_priv | enum('N','Y') | NO | | N | |
| Repl_client_priv | enum('N','Y') | NO | | N | |
| Create_view_priv | enum('N','Y') | NO | | N | |
| Show_view_priv | enum('N','Y') | NO | | N | |
| Create_routine_priv | enum('N','Y') | NO | | N | |
| Alter_routine_priv | enum('N','Y') | NO | | N | |
| Create_user_priv | enum('N','Y') | NO | | N | |
| Event_priv | enum('N','Y') | NO | | N | |
| Trigger_priv | enum('N','Y') | NO | | N | |
| Create_tablespace_priv | enum('N','Y') | NO | | N | |
| ssl_type | enum('','ANY','X509','SPECIFIED') | NO | | | |
| ssl_cipher | blob | NO | | NULL | |
| x509_issuer | blob | NO | | NULL | |
| x509_subject | blob | NO | | NULL | |
| max_questions | int(11) unsigned | NO | | 0 | |
| max_updates | int(11) unsigned | NO | | 0 | |
| max_connections | int(11) unsigned | NO | | 0 | |
| max_user_connections | int(11) unsigned | NO | | 0 | |
| plugin | char(64) | NO | | mysql_native_password | |
| authentication_string | text | YES | | NULL | |
| password_expired | enum('N','Y') | NO | | N | |
| password_last_changed | timestamp | YES | | NULL | |
| password_lifetime | smallint(5) unsigned | YES | | NULL | |
| account_locked | enum('N','Y') | NO | | N | |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
45 rows in set (0.00 sec)
Surprise!There is no field named 'password', the password field is named ' authentication_string'. So, just do this:
update user set authentication_string=password('1111') where user='root';
Now, everything will be ok.
Compared to MySQL 5.6, the changes are quite extensive: What’s New in MySQL 5.7
How to hide soft keyboard on android after clicking outside EditText?
This may be old but I got this working by implenting a custom class
public class DismissKeyboardListener implements OnClickListener {
Activity mAct;
public DismissKeyboardListener(Activity act) {
this.mAct = act;
}
@Override
public void onClick(View v) {
if ( v instanceof ViewGroup ) {
hideSoftKeyboard( this.mAct );
}
}
}
public void hideSoftKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager)
getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
the best practice here is to create a Helper class and every container Relative / Linear Layouts should implement this.
**** Take note only the main Container should implement this class (For optimization) ****
and implement it like this :
Parent.setOnClickListener( new DismissKeyboardListener(this) );
the keyword this is for Activity. so if you are on fragment you use like getActivity();
---thumbs up if it help you...
--- cheers Ralph ---
How to fix .pch file missing on build?
Fix:
Make sure you have xxxxx.cpp in your project
Compile xxxxx.cpp with /Yc flag (Create Precompiled Header)
(right click on xxxxx.cpp -> properties -> Precompiled Headers -> create)
Compile all other files with /Yu flag (Use Precompiled Header)
(right click on project -> properties -> Precompiled Headers -> use)
NuGet behind a proxy
Maybe you could try this to your devenv.exe.config
<system.net>
<defaultProxy useDefaultCredentials="true" enabled="true">
<proxy proxyaddress="http://proxyaddress" />
</defaultProxy>
<settings>
<servicePointManager expect100Continue="false" />
<ipv6 enabled="true"/>
</settings>
</system.net>
I found it from the NuGet Issue tracker
There are also other valuable comments about NuGet + network issues.
Java TreeMap Comparator
You can not sort TreeMap on values.
A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used
You will need to provide comparator
for Comparator<? super K>
so your comparator should compare on keys.
To provide sort on values you will need SortedSet. Use
SortedSet<Map.Entry<String, Double>> sortedset = new TreeSet<Map.Entry<String, Double>>(
new Comparator<Map.Entry<String, Double>>() {
@Override
public int compare(Map.Entry<String, Double> e1,
Map.Entry<String, Double> e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
sortedset.addAll(myMap.entrySet());
To give you an example
SortedMap<String, Double> myMap = new TreeMap<String, Double>();
myMap.put("a", 10.0);
myMap.put("b", 9.0);
myMap.put("c", 11.0);
myMap.put("d", 2.0);
sortedset.addAll(myMap.entrySet());
System.out.println(sortedset);
Output:
[d=2.0, b=9.0, a=10.0, c=11.0]
multiple figure in latex with captions
Below is an example of multiple figures that I used recently in Latex.
You need to call these packages
\usepackage{graphicx}
\usepackage{subfig})
\begin{figure}[H]%
\centering
\subfloat[Row1]{{\includegraphics[scale=.36]{1.png} }}%
\subfloat[Row2]{{\includegraphics[scale=.36]{2.png} }}%
\subfloat[Row3]{{\includegraphics[scale=.36]{3.png} }}%
\hfill
\subfloat[Row4]{{\includegraphics[scale=0.37]{4.png} }}%
\subfloat[Row5]{{\includegraphics[scale=0.37]{5.png} }}%
\caption{Multiple figures in latex.}%
\label{fig:MFL}%
\end{figure}
HTML Input Box - Disable
<input type="text" required="true" value="" readonly>
Not the.
<input type="text" required="true" value="" readonly="true">
Running multiple async tasks and waiting for them all to complete
You can use WhenAll
which will return an awaitable Task
or WaitAll
which has no return type and will block further code execution simular to Thread.Sleep
until all tasks are completed, canceled or faulted.
Example
var tasks = new Task[] {
TaskOperationOne(),
TaskOperationTwo()
};
Task.WaitAll(tasks);
// or
await Task.WhenAll(tasks);
If you want to run the tasks in a praticular order you can get inspiration form this anwser.
Read tab-separated file line into array
If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1
, column2
, column3
like in this code snippet
while IFS=$'\t' read -r column1 column2 column3 ; do
printf "%b\n" "column1<${column1}>"
printf "%b\n" "column2<${column2}>"
printf "%b\n" "column3<${column3}>"
done < "myfile"
to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN
is not a good idea to do so).
Why is synchronized block better than synchronized method?
One classic difference between Synchronized block and Synchronized method is that Synchronized method locks the entire object. Synchronized block just locks the code within the block.
Synchronized method: Basically these 2 sync methods disable multithreading. So one thread completes the method1() and the another thread waits for the Thread1 completion.
class SyncExerciseWithSyncMethod {
public synchronized void method1() {
try {
System.out.println("In Method 1");
Thread.sleep(5000);
} catch (Exception e) {
System.out.println("Catch of method 1");
} finally {
System.out.println("Finally of method 1");
}
}
public synchronized void method2() {
try {
for (int i = 1; i < 10; i++) {
System.out.println("Method 2 " + i);
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println("Catch of method 2");
} finally {
System.out.println("Finally of method 2");
}
}
}
Output
In Method 1
Finally of method 1
Method 2 1
Method 2 2
Method 2 3
Method 2 4
Method 2 5
Method 2 6
Method 2 7
Method 2 8
Method 2 9
Finally of method 2
Synchronized block: Enables multiple threads to access the same object at same time [Enables multi-threading].
class SyncExerciseWithSyncBlock {
public Object lock1 = new Object();
public Object lock2 = new Object();
public void method1() {
synchronized (lock1) {
try {
System.out.println("In Method 1");
Thread.sleep(5000);
} catch (Exception e) {
System.out.println("Catch of method 1");
} finally {
System.out.println("Finally of method 1");
}
}
}
public void method2() {
synchronized (lock2) {
try {
for (int i = 1; i < 10; i++) {
System.out.println("Method 2 " + i);
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println("Catch of method 2");
} finally {
System.out.println("Finally of method 2");
}
}
}
}
Output
In Method 1
Method 2 1
Method 2 2
Method 2 3
Method 2 4
Method 2 5
Finally of method 1
Method 2 6
Method 2 7
Method 2 8
Method 2 9
Finally of method 2
Bind class toggle to window scroll event
This is my solution, it's not that tricky and allow you to use it for several markup throught a simple ng-class directive.
Like so you can choose the class and the scrollPos for each case.
Your App.js :
angular.module('myApp',[])
.controller('mainCtrl',function($window, $scope){
$scope.scrollPos = 0;
$window.onscroll = function(){
$scope.scrollPos = document.body.scrollTop || document.documentElement.scrollTop || 0;
$scope.$apply(); //or simply $scope.$digest();
};
});
Your index.html :
<html ng-app="myApp">
<head></head>
<body>
<section ng-controller="mainCtrl">
<p class="red" ng-class="{fix:scrollPos >= 100}">fix me when scroll is equals to 100</p>
<p class="blue" ng-class="{fix:scrollPos >= 150}">fix me when scroll is equals to 150</p>
</section>
</body>
</html>
working JSFiddle here
EDIT :
As $apply()
is actually calling $rootScope.$digest()
you can
directly use $scope.$digest()
instead of $scope.$apply()
for
better performance depending on context.
Long story short : $apply()
will always work but force the $digest
on all scopes that may cause
perfomance issue.
rake assets:precompile RAILS_ENV=production not working as required
Replace
rake assets:precompile RAILS_ENV=production
with
rake assets:precompile
(RAILS_ENV=production bundle exec rake assets:precompile
is the exact rake task)
Since precompilation is done in production mode only, no need to explicitly specify the environment.
Update:
Try adding the below line to your Gemfile:
group :assets do
gem 'therubyracer'
gem 'sass-rails', " ~> 3.1.0"
gem 'coffee-rails', "~> 3.1.0"
gem 'uglifier'
end
Then run bundle install
.
Hope it will work :)
Deactivate or remove the scrollbar on HTML
What I would try in this case is put this in the stylesheet
html, body{overflow:hidden;}
this way one disables the scrollbar, and as a cumulative effect they disable scrolling with the keyboard
How do I cast a JSON Object to a TypeScript class?
Assuming the json has the same properties as your typescript class, you don't have to copy your Json properties to your typescript object. You will just have to construct your Typescript object passing the json data in the constructor.
In your ajax callback, you receive a company:
onReceiveCompany( jsonCompany : any )
{
let newCompany = new Company( jsonCompany );
// call the methods on your newCompany object ...
}
In in order to to make that work:
1) Add a constructor in your Typescript class that takes the json data as parameter. In that constructor you extend your json object with jQuery, like this: $.extend( this, jsonData)
. $.extend allows keeping the javascript prototypes while adding the json object's properties.
2) Note you will have to do the same for linked objects. In the case of Employees in the example, you also create a constructor taking the portion of the json data for employees. You call $.map to translate json employees to typescript Employee objects.
export class Company
{
Employees : Employee[];
constructor( jsonData: any )
{
$.extend( this, jsonData);
if ( jsonData.Employees )
this.Employees = $.map( jsonData.Employees , (emp) => {
return new Employee ( emp ); });
}
}
export class Employee
{
name: string;
salary: number;
constructor( jsonData: any )
{
$.extend( this, jsonData);
}
}
This is the best solution I found when dealing with Typescript classes and json objects.
How to skip the OPTIONS preflight request?
Preflight is a web security feature implemented by the browser. For Chrome you can disable all web security by adding the --disable-web-security flag.
For example: "C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\newChromeSettingsWithoutSecurity" . You can first create a new shortcut of chrome, go to its properties and change the target as above. This should help!
Get Multiple Values in SQL Server Cursor
Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:
declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for
select
row_number() over (order by(select null)) as RowNum
,Data -- you fields
from YourIntTable
open @cur
begin try
fetch last from @cur into @lastNum, @data
fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value
while @i < @lastNum
begin
set @i += 1
--Do your job here
print @data
fetch next from @cur into @rowNum, @data
end
end try
begin catch
close @cur --|
deallocate @cur --|-remove this 3 lines if you do not throw
;throw --|
end catch
close @cur
deallocate @cur
JQuery Event for user pressing enter in a textbox?
Another subtle variation.
I went for a slight separation of powers, so I have a plugin to enable catching the enter key, then I just bind to events normally:
(function($) { $.fn.catchEnter = function(sel) {
return this.each(function() {
$(this).on('keyup',sel,function(e){
if(e.keyCode == 13)
$(this).trigger("enterkey");
})
});
};
})(jQuery);
And then in use:
$('.input[type="text"]').catchEnter().on('enterkey',function(ev) { });
This variation allows you to use event delegation (to bind to elements you haven't created yet).
$('body').catchEnter('.onelineInput').on('enterkey',function(ev) { /*process input */ });
Can't connect to MySQL server error 111
If all the previous answers didn't give any solution,
you should check your user privileges.
If you could login as root
to mysql
then you should add this:
CREATE USER 'root'@'192.168.1.100' IDENTIFIED BY '***';
GRANT ALL PRIVILEGES ON * . * TO 'root'@'192.168.1.100' IDENTIFIED BY '***' WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;
Then try to connect again using mysql -ubeer -pbeer -h192.168.1.100
. It should work.
Importing text file into excel sheet
I think my answer to my own question here is the simplest solution to what you are trying to do:
Select the cell where the first line of text from the file should be.
Use the Data
/Get External Data
/From File
dialog to select the text file to import.
Format the imported text as required.
In the Import Data
dialog that opens, click on Properties...
Uncheck the Prompt for file name on refresh
box.
Whenever the external file changes, click the Data
/Get External Data
/Refresh All
button.
Note: in your case, you should probably want to skip step #5.
Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction
Using REQUIRES_NEW
is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED
- it will create a new transaction.
That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional
, it will create a new transaction.
So, with that in mind, if using REQUIRES_NEW
makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.
On rollback - using REQUIRES_NEW
will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations.
Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.
EditText non editable
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
Replacing column values in a pandas DataFrame
You can also use apply
with .get
i.e.
w['female'] = w['female'].apply({'male':0, 'female':1}.get)
:
w = pd.DataFrame({'female':['female','male','female']})
print(w)
Dataframe w
:
female
0 female
1 male
2 female
Using apply
to replace values from the dictionary:
w['female'] = w['female'].apply({'male':0, 'female':1}.get)
print(w)
Result:
female
0 1
1 0
2 1
Note: apply
with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.
PHP Array to JSON Array using json_encode();
json_encode() function will help you to encode array to JSON in php.
if you will use just json_encode function directly without any specific option, it will return an array.
Like mention above question
$array = array(
2 => array("Afghanistan",32,13),
4 => array("Albania",32,12)
);
$out = array_values($array);
json_encode($out);
// [["Afghanistan",32,13],["Albania",32,12]]
Since you are trying to convert Array to JSON, Then I would suggest to use JSON_FORCE_OBJECT as additional option(parameters) in json_encode, Like below
<?php
$array=['apple','orange','banana','strawberry'];
echo json_encode($array, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"}
?>
PHP convert XML to JSON
This is better solution
$fileContents= file_get_contents("https://www.feedforall.com/sample.xml");
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
$array = json_decode($json,TRUE);
return $array;
jQuery Validate Plugin - Trigger validation of single field
Use Validator.element()
:
Validates a single element, returns true if it is valid, false
otherwise.
Here is the example shown in the API:
var validator = $( "#myform" ).validate();
validator.element( "#myselect" );
.valid()
validates the entire form, as others have pointed out. The API says:
Checks whether the selected form is valid or whether all selected
elements are valid.
javascript node.js next()
It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send
in your each REST block...
So you can do something like this as a simple next()
example:
app.get("/", (req, res, next) => {
console.log("req:", req, "res:", res);
res.send(["data": "whatever"]);
next();
},(req, res) =>
console.log("it's all done!");
);
It's also very useful when you'd like to have a middleware in your app...
To load the middleware function, call app.use(), specifying the
middleware function. For example, the following code loads the
myLogger middleware function before the route to the root path (/).
var express = require('express');
var app = express();
var myLogger = function (req, res, next) {
console.log('LOGGED');
next();
}
app.use(myLogger);
app.get('/', function (req, res) {
res.send('Hello World!');
})
app.listen(3000);
Mockito How to mock only the call of a method of the superclass
Maybe the easiest option if inheritance makes sense is to create a new method (package private??) to call the super (lets call it superFindall), spy the real instance and then mock the superFindAll() method in the way you wanted to mock the parent class one. It's not the perfect solution in terms of coverage and visibility but it should do the job and it's easy to apply.
public Childservice extends BaseService {
public void save(){
//some code
superSave();
}
void superSave(){
super.save();
}
}
Python get current time in right timezone
To get the current time in the local timezone as a naive datetime object:
from datetime import datetime
naive_dt = datetime.now()
If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).
To get the current time in UTC as a naive datetime object:
naive_utc_dt = datetime.utcnow()
To get the current time as an aware datetime object in Python 3.3+:
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time
To get the current time in the given time zone from the tz database:
import pytz
tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)
It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.
Using DataContractSerializer to serialize, but can't deserialize back
I ended up doing the following and it works.
public static string Serialize(object obj)
{
using (MemoryStream memoryStream = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
serializer.WriteObject(memoryStream, obj);
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
public static object Deserialize(string xml, Type toType)
{
using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
DataContractSerializer serializer = new DataContractSerializer(toType);
return serializer.ReadObject(reader);
}
}
It seems that the major problem was in the Serialize function when calling stream.GetBuffer(). Calling stream.ToArray() appears to work.