xcode-select active developer directory error
I was able to solve this error without installing the full Xcode application. You must, however, have xcode command line tools installed.
From here:
$ cd /usr/bin
$ sudo mv xcodebuild xcodebuild.orig
(A backup just in case)
$ vim xcodebuild
- Paste the following:
#!/bin/bash
if [[ $1 == '-version' ]]; then
echo "Xcode 10.2.1"
echo "Build version 10E1001"
else
/usr/bin/xcodebuild.bak $@
fi
$ sudo chmod +x xcodebuild
What are all the differences between src and data-src attributes?
The attributes src
and data-src
have nothing in common, except that they are both allowed by HTML5 CR and they both contain the letters src
. Everything else is different.
The src
attribute is defined in HTML specs, and it has a functional meaning.
The data-src
attribute is just one of the infinite set of data-*
attributes, which have no defined meaning but can be used to include invisible data in an element, for use in scripting (or styling).
How to split a string in Java
I used a string called stringValue
and is in the form of something like this "Those who had coins, enjoyed in the rain, those who had notes were busy looking for the shelter".
I will split up the stringValue
using the "," as the colon.
And then I would simply like to SetText() of three different TextViews to display that string.
String stringValue = "Those who had coins, enjoyed in the rain, those who had notes were busy looking for the shelter";
String ValueSplitByColon[] = stringValue.split(",");
String firstValue = ValueSplitByColon[0];
String secondValue = ValueSplitByColon[1];
String thirdValue = ValueSplitByColon[2];
txtV1.setText(firstValue);
txtV2.setText(secondValue;
txtV3.setText(thirdValue;
It gives the output as:
The txtV1 value is: Those who had coins
The txtV2 value is: enjoyed in the rain
The txtV3 value is: those who had notes were busy looking for the shelter
Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate
I know the answers were correct at the time of asking the question - but since people (like me this minute) still happen to find them wondering why their WildFly 10 was behaving differently, I'd like to give an update for the current Hibernate 5.x version:
In the Hibernate 5.2 User Guide it is stated in chapter 11.2. Applying fetch strategies:
The Hibernate recommendation is to statically mark all associations
lazy and to use dynamic fetching strategies for eagerness. This is
unfortunately at odds with the JPA specification which defines that
all one-to-one and many-to-one associations should be eagerly fetched
by default. Hibernate, as a JPA provider, honors that default.
So Hibernate as well behaves like Ashish Agarwal stated above for JPA:
OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER
(see JPA 2.1 Spec)
How to convert a Map to List in Java?
If you want to ensure the values in the resultant List<Value>
are in the key-ordering of the input Map<Key, Value>
, you need to "go via" SortedMap
somehow.
Either start with a concrete SortedMap
implementation (Such as TreeMap
) or insert your input Map
into a SortedMap
before converting that to List
. e.g.:
Map<Key,Value> map;
List<Value> list = new ArrayList<Value>( new TreeMap<Key Value>( map ));
Otherwise you'll get whatever native ordering the Map
implementation provides, which can often be something other than the natural key ordering (Try Hashtable
or ConcurrentHashMap
, for variety).
Android 6.0 multiple permissions
Small code :
public static final int MULTIPLE_PERMISSIONS = 10; // code you want.
String[] permissions= new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION};
if (checkPermissions())
// permissions granted.
}
private boolean checkPermissions() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(getActivity(),p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),MULTIPLE_PERMISSIONS );
return false;
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissionsList[], int[] grantResults) {
switch (requestCode) {
case MULTIPLE_PERMISSIONS:{
if (grantResults.length > 0) {
String permissionsDenied = "";
for (String per : permissionsList) {
if(grantResults[0] == PackageManager.PERMISSION_DENIED){
permissionsDenied += "\n" + per;
}
}
// Show permissionsDenied
updateViews();
}
return;
}
}
}
List of Android permissions normal permissions and dangerous permissions in API 23
Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?
I just fund another way to do the same workaround. Because of I hadn' t the possibility to click on the yellow triangle (even if I have admin role), when you go inside testflight, then iOS (under "Build") instead of yellow triangle click the version number, another page will open and you will find on top right something like add compliance information (sorry if I am not totally accurate but I have the italian version but it would be really easy to find). Then you can do the same even if you, like me, are not able to click on yellow triangle.
Combine two OR-queries with AND in Mongoose
It's probably easiest to create your query object directly as:
Test.find({
$and: [
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
]
}, function (err, results) {
...
}
But you can also use the Query#and
helper that's available in recent 3.x Mongoose releases:
Test.find()
.and([
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
])
.exec(function (err, results) {
...
});
How to Refresh a Component in Angular
Just change the routeReuseStrategy from the angular Router:
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
Set the routerproperty "navigated" to false:
this._router.navigated = false;
Then navigate to your component:
this._router.navigate(['routeToYourComponent'])
After that reinstate the old/default routeReuseStrategy:
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
You can also make a service out of this:
@Injectable({
providedIn: 'root'
})
export class RouterService {
constructor(
private _activatedRoute: ActivatedRoute,
private _router: Router
) { }
reuseRoutes(reuse: boolean) {
if (!reuse) {
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
}
if (reuse) {
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
};
}
}
async refreshPage(url?: string) {
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
this._router.navigated = false;
url ? await this._router.navigate([url]) : await this._router.navigate([], { relativeTo: this._activatedRoute });
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
};
}
}
View contents of database file in Android Studio
The easiest way is to use Android Debug Database library (7.7k stars on GitHub).
Advantages:
- Fast implementation
- See all the databases and shared preferences
- Directly edit, delete, create the database values
- Run any SQLite query on the given database
- Search in your data
- Download database
- Adding custom database files
- No need to root device
How to use:
- Add
debugImplementation 'com.amitshekhar.android:debug-db:1.0.6'
to build.gradle (module)
;
- Launch app;
- Find the debugging link in logs (in LogCat) (i.e.
D/DebugDB: Open http://192.168.232.2:8080 in your browser
, the link will be different) and open it in the browser;
- Enjoy the powerful debugging tool!
Important:
- Unfortunately doesn't work with emulators
- If you are using it over USB, run
adb forward tcp:8080 tcp:8080
- Your Android phone and laptop should be connected to the same Network (Wifi or LAN)
For more information go to the library page on GitHub.
Command to open file with git
You can create an alias to open a file in your default editor by appending the following line to your .gitconfig file:
edit = "!f() { $(git config core.editor) -- $@; }; f"
Then, git edit foo.txt
will open the file foo.txt
for editing.
It's much easier to open .gitconfig with git config --global --edit
and paste the line, rather than figure out how to escape all the characters to enter the alias directly from the command line with git config alias.edit "..."
How it works
!
starts a bash command, not an internal git command
f() {...};
starts a function
$(git config core.editor)
will get the name of your editor, from the local config, or the global if the local is not set. Unfortunately it will not look in $VISUAL
or $EDITOR
for this, if none is set.
--
separates the editor command with the file list. This works for most command line editors, so is safer to put in. If skipped and the core.editor
is not set then it is possible that an executable file is executed instead of being edited. With it here, the command will just fail.
$@
will add the files entered at the command line.
f
will execute the function after it is defined.
Use case
The other answers express doubt as to why you would want this. My use case is that I want to edit files as part of other git functions that I am building, and I want to edit them in the same editor that the user has configured. For example, the following is one of my aliases:
reedit = "!f() { $(git config core.editor) -- $(git diff --name-only $1); }; f"
Then, git reedit
will open all the files that I have already started modifying, and git reedit --cached
will open all the staged files.
Ng-model does not update controller value
"If you use ng-model, you have to have a dot in there."
Make your model point to an object.property and you'll be good to go.
Controller
$scope.formData = {};
$scope.check = function () {
console.log($scope.formData.searchText.$modelValue); //works
}
Template
<input ng-model="formData.searchText"/>
<button ng-click="check()">Check!</button>
This happens when child scopes are in play - like child routes or ng-repeats.
The child-scope creates it's own value and a name conflict is born as illustrated here:
See this video clip for more: https://www.youtube.com/watch?v=SBwoFkRjZvE&t=3m15s
When to use React setState callback
Consider setState call
this.setState({ counter: this.state.counter + 1 })
IDEA
setState may be called in async function
So you cannot rely on this
. If the above call was made inside a async function this
will refer to state of component at that point of time but we expected this to refer to property inside state at time setState calling or beginning of async task. And as task was async call thus that property may have changed in time being. Thus it is unreliable to use this
keyword to refer to some property of state thus we use callback function whose arguments are previousState and props which means when async task was done and it was time to update state using setState call prevState will refer to state now when setState has not started yet. Ensuring reliability that nextState would not be corrupted.
Wrong Code: would lead to corruption of data
this.setState(
{counter:this.state.counter+1}
);
Correct Code with setState having call back function:
this.setState(
(prevState,props)=>{
return {counter:prevState.counter+1};
}
);
Thus whenever we need to update our current state to next state based on value possed by property just now and all this is happening in async fashion it is good idea to use setState as callback function.
I have tried to explain it in codepen here CODE PEN
What is the difference between range and xrange functions in Python 2.X?
range :-range will populate everything at once.which means every number of the range will occupy the memory.
xrange :-xrange is something like generator ,it will comes into picture when you want the range of numbers but you dont want them to be stored,like when you want to use in for loop.so memory efficient.
Better way to find last used row
You should use a with statement to qualify both your Rows
and Columns
counts. This will prevent any errors while working with older pre 2007 and newer 2007 Excel Workbooks.
Last Column
With Sheets("Sheet2")
.Cells(1, .Columns.Count).End(xlToLeft).Column
End With
Last Row
With Sheets("Sheet2")
.Range("A" & .Rows.Count).End(xlUp).Row
End With
Or
With Sheets("Sheet2")
.Cells(.Rows.Count, 1).End(xlUp).Row
End With
Detect if user is scrolling
window.addEventListener("scroll",function(){
window.lastScrollTime = new Date().getTime()
});
function is_scrolling() {
return window.lastScrollTime && new Date().getTime() < window.lastScrollTime + 500
}
Change the 500 to the number of milliseconds after the last scroll event at which you consider the user to be "no longer scrolling".
(addEventListener
is better than onScroll
because the former can coexist nicely with any other code that uses onScroll
.)
not-null property references a null or transient value
Check the unsaved values for your primary key/Object ID in your hbm files. If you have automated ID creation by hibernate framework and you are setting the ID somewhere it will throw this error.By default the unsaved value is 0, so if you set the ID to 0 you will see this error.
Round to 2 decimal places
Just use Math.round()
double mkm = ((((amountdrug/fluidvol)*1000f)/60f)*infrate)/ptwt;
mkm= (double)(Math.round(mkm*100))/100;
ASP.NET MVC5/IIS Express unable to debug - Code Not Running
None of the above answers worked for me but I finally found what my issue was. Hopefully this will help someone down the line.
First run IIS Express from command prompt to validate that the site can or cannot be run
https://docs.microsoft.com/en-us/iis/extensions/using-iis-express/running-iis-express-from-the-command-line
Im my case, i got an error saying that C:\Windows\Microsoft.NET\Framework64\v4.0.30319\CONFIG\web.config had malformed xml on line 14. Looking at that line in the file it just said null null null null null etc.
The fix for me was to replace the web.config file with one from my coworkers. IMPORTANT you must get the file from someone running the same version ie if you are VS2015 get a copy from someone running VS2015. If you get it from someone running a different version you will see an error saying it could not load an assembly from the manifest.
Hopefully this helps someone that has tried all the suggestions above. I think the cause of this for me was updating from trial mode and adding a product key within VS2017
Automatically size JPanel inside JFrame
You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);
This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.
Creating executable files in Linux
No need to hack your editor, or switch editors.
Instead we can come up with a script to watch your development directories and chmod files as they're created. This is what I've done in the attached bash script. You probably want to read through the comments and edit the 'config' section as fits your needs, then I would suggest putting it in your $HOME/bin/ directory and adding its execution to your $HOME/.login or similar file. Or you can just run it from the terminal.
This script does require inotifywait, which comes in the inotify-tools package on Ubuntu,
sudo apt-get install inotify-tools
Suggestions/edits/improvements are welcome.
#!/usr/bin/env bash
# --- usage --- #
# Depends: 'inotifywait' available in inotify-tools on Ubuntu
#
# Edit the 'config' section below to reflect your working directory, WORK_DIR,
# and your watched directories, WATCH_DIR. Each directory in WATCH_DIR will
# be logged by inotify and this script will 'chmod +x' any new files created
# therein. If SUBDIRS is 'TRUE' this script will watch WATCH_DIRS recursively.
# I recommend adding this script to your $HOME/.login or similar to have it
# run whenever you log into a shell, eg 'echo "watchdirs.sh &" >> ~/.login'.
# This script will only allow one instance of itself to run at a time.
# --- config --- #
WORK_DIR="$HOME/path/to/devel" # top working directory (for cleanliness?)
WATCH_DIRS=" \
$WORK_DIR/dirA \
$WORK_DIR/dirC \
" # list of directories to watch
SUBDIRS="TRUE" # watch subdirectories too
NOTIFY_ARGS="-e create -q" # watch for create events, non-verbose
# --- script starts here --- #
# probably don't need to edit beyond this point
# kill all previous instances of myself
SCRIPT="bash.*`basename $0`"
MATCHES=`ps ax | egrep $SCRIPT | grep -v grep | awk '{print $1}' | grep -v $$`
kill $MATCHES >& /dev/null
# set recursive notifications (for subdirectories)
if [ "$SUBDIRS" = "TRUE" ] ; then
RECURSE="-r"
else
RECURSE=""
fi
while true ; do
# grab an event
EVENT=`inotifywait $RECURSE $NOTIFY_ARGS $WATCH_DIRS`
# parse the event into DIR, TAGS, FILE
OLDIFS=$IFS ; IFS=" " ; set -- $EVENT
E_DIR=$1
E_TAGS=$2
E_FILE=$3
IFS=$OLDIFS
# skip if it's not a file event or already executable (unlikely)
if [ ! -f "$E_DIR$E_FILE" ] || [ -x "$E_DIR$E_FILE" ] ; then
continue
fi
# set file executable
chmod +x $E_DIR$E_FILE
done
How can I debug git/git-shell related problems?
Git 2.9.x/2.10 (Q3 2016) adds another debug option: GIT_TRACE_CURL
.
See commit 73e57aa, commit 74c682d (23 May 2016) by Elia Pinto (devzero2000
).
Helped-by: Torsten Bögershausen (tboegi
), Ramsay Jones , Junio C Hamano (gitster
), Eric Sunshine (sunshineco
), and Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 2f84df2, 06 Jul 2016)
http.c
: implement the GIT_TRACE_CURL
environment variable
Implement the GIT_TRACE_CURL
environment variable to allow a greater degree of detail of GIT_CURL_VERBOSE
, in particular the complete transport header and all the data payload exchanged.
It might be useful if a particular situation could require a more thorough debugging analysis.
The documentation will state:
GIT_TRACE_CURL
Enables a curl full trace dump of all incoming and outgoing data, including descriptive information, of the git transport protocol.
This is similar to doing curl --trace-ascii
on the command line.
This option overrides setting the GIT_CURL_VERBOSE
environment variable.
You can see that new option used in this answer, but also in the Git 2.11 (Q4 2016) tests:
See commit 14e2411, commit 81590bf, commit 4527aa1, commit 4eee6c6 (07 Sep 2016) by Elia Pinto (devzero2000
).
(Merged by Junio C Hamano -- gitster
-- in commit 930b67e, 12 Sep 2016)
Use the new GIT_TRACE_CURL
environment variable instead
of the deprecated GIT_CURL_VERBOSE
.
GIT_TRACE_CURL=true git clone --quiet $HTTPD_URL/smart/repo.git
How to delete a stash created with git stash create?
To delete a normal stash created with git stash
, you want git stash drop
or git stash drop stash@{n}
. See below for more details.
You don't need to delete a stash created with git stash create
. From the docs:
Create a stash entry (which is a regular commit object) and return its object name, without storing it anywhere in the ref namespace. This is intended to be useful for scripts. It is probably not the command you want to use; see "save" above.
Since nothing references the stash commit, it will get garbage collected eventually.
A stash created with git stash
or git stash save
is saved to refs/stash
, and can be deleted with git stash drop
. As with all Git objects, the actual stash contents aren't deleted from your computer until a gc
prunes those objects after they expire (default is 2 weeks later).
Older stashes are saved in the refs/stash
reflog (try cat .git/logs/refs/stash
), and can be deleted with git stash drop stash@{n}
, where n
is the number shown by git stash list
.
Adding a legend to PyPlot in Matplotlib in the simplest manner possible
Add a label=
to each of your plot()
calls, and then call legend(loc='upper left')
.
Consider this sample (tested with Python 3.8.0):
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, "-b", label="sine")
plt.plot(x, y2, "-r", label="cosine")
plt.legend(loc="upper left")
plt.ylim(-1.5, 2.0)
plt.show()
Slightly modified from this tutorial: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html
Matching a Forward Slash with a regex
You can also work around special JS handling of the forward slash by enclosing it in a character group, like so:
const start = /[/]/g;
"/dev/null".match(start) // => ["/", "/"]
const word = /[/](\w+)/ig;
"/dev/null".match(word) // => ["/dev", "/null"]
Smart way to truncate long strings
c_harm's answer is in my opinion the best. Please note that if you want to use
"My string".truncate(n)
you will have to use a regexp object constructor rather than a literal. Also you'll have to escape the \S
when converting it.
String.prototype.truncate =
function(n){
var p = new RegExp("^.{0," + n + "}[\\S]*", 'g');
var re = this.match(p);
var l = re[0].length;
var re = re[0].replace(/\s$/,'');
if (l < this.length) return re + '…';
};
Can I add color to bootstrap icons only using CSS?
The accepted answer (using font awesome) is the right one. But since I just wanted the red variant to show on validation errors, I ended using an addon package, kindly offered on this site.
Just edited the url paths in css files since they are absolute (start with /) and I prefer to be relative. Like this:
.icon-red {background-image: url("../img/glyphicons-halflings-red.png") !important;}
.icon-purple {background-image: url("../img/glyphicons-halflings-purple.png") !important;}
.icon-blue {background-image: url("../img/glyphicons-halflings-blue.png") !important;}
.icon-lightblue {background-image: url("../img/glyphicons-halflings-lightblue.png") !important;}
.icon-green {background-image: url("../img/glyphicons-halflings-green.png") !important;}
.icon-yellow {background-image: url("../img/glyphicons-halflings-yellow.png") !important;}
.icon-orange {background-image: url("../img/glyphicons-halflings-orange.png") !important;}
Has anyone ever got a remote JMX JConsole to work?
I am running JConsole/JVisualVm on windows hooking to tomcat running Linux Redhat ES3.
Disabling packet filtering using the following command did the trick for me:
/usr/sbin/iptables -I INPUT -s jconsole-host -p tcp --destination-port jmxremote-port -j ACCEPT
where jconsole-host is either the hostname or the host address on which JConsole runs on and jmxremote-port is the port number set for com.sun.management.jmxremote.port for remote management.
Find element's index in pandas Series
In [92]: (myseries==7).argmax()
Out[92]: 3
This works if you know 7 is there in advance. You can check this with
(myseries==7).any()
Another approach (very similar to the first answer) that also accounts for multiple 7's (or none) is
In [122]: myseries = pd.Series([1,7,0,7,5], index=['a','b','c','d','e'])
In [123]: list(myseries[myseries==7].index)
Out[123]: ['b', 'd']
What is the difference between "screen" and "only screen" in media queries?
@media screen and (max-width:480px) { … }
screen
here is to set the screen size of the media query. E.g the maximum width of the display area is 480px. So it is specifying the screen as opposed to the other available media types.
@media only screen and (max-width: 480px;) { … }
only screen
here is used to prevent older browsers that do not support media queries with media features from applying the specified styles.
Error pushing to GitHub - insufficient permission for adding an object to repository database
Oddly enough, I had this issue on one clone of the repo I had, but not another I had. Aside from re-cloning the repo (which a coworker did to successfully get around this issue), I managed to do a "git reset" to the commit I had before the failures started. Then I re-committed the changes, and I was able to push successfully after that. So despite all the indications there was a problem on the server, in this case it apparently was indicative of some oddity in the local repo.
How to run a Command Prompt command with Visual Basic code?
Here is an example:
Process.Start("CMD", "/C Pause")
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
And here is a extended function:
(Notice the comment-lines using CMD commands.)
#Region " Run Process Function "
' [ Run Process Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' MsgBox(Run_Process("Process.exe"))
' MsgBox(Run_Process("Process.exe", "Arguments"))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B", True))
' MsgBox(Run_Process("CMD.exe", "/C @Echo OFF & For /L %X in (0,1,50000) Do (Echo %X)", False, False))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B /S %SYSTEMDRIVE%\*", , False, 500))
' If Run_Process("CMD.exe", "/C Dir /B", True).Contains("File.txt") Then MsgBox("File found")
Private Function Run_Process(ByVal Process_Name As String, _
Optional Process_Arguments As String = Nothing, _
Optional Read_Output As Boolean = False, _
Optional Process_Hide As Boolean = False, _
Optional Process_TimeOut As Integer = 999999999)
' Returns True if "Read_Output" argument is False and Process was finished OK
' Returns False if ExitCode is not "0"
' Returns Nothing if process can't be found or can't be started
' Returns "ErrorOutput" or "StandardOutput" (In that priority) if Read_Output argument is set to True.
Try
Dim My_Process As New Process()
Dim My_Process_Info As New ProcessStartInfo()
My_Process_Info.FileName = Process_Name ' Process filename
My_Process_Info.Arguments = Process_Arguments ' Process arguments
My_Process_Info.CreateNoWindow = Process_Hide ' Show or hide the process Window
My_Process_Info.UseShellExecute = False ' Don't use system shell to execute the process
My_Process_Info.RedirectStandardOutput = Read_Output ' Redirect (1) Output
My_Process_Info.RedirectStandardError = Read_Output ' Redirect non (1) Output
My_Process.EnableRaisingEvents = True ' Raise events
My_Process.StartInfo = My_Process_Info
My_Process.Start() ' Run the process NOW
My_Process.WaitForExit(Process_TimeOut) ' Wait X ms to kill the process (Default value is 999999999 ms which is 277 Hours)
Dim ERRORLEVEL = My_Process.ExitCode ' Stores the ExitCode of the process
If Not ERRORLEVEL = 0 Then Return False ' Returns the Exitcode if is not 0
If Read_Output = True Then
Dim Process_ErrorOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Error Output (If any)
Dim Process_StandardOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Standard Output (If any)
' Return output by priority
If Process_ErrorOutput IsNot Nothing Then Return Process_ErrorOutput ' Returns the ErrorOutput (if any)
If Process_StandardOutput IsNot Nothing Then Return Process_StandardOutput ' Returns the StandardOutput (if any)
End If
Catch ex As Exception
'MsgBox(ex.Message)
Return Nothing ' Returns nothing if the process can't be found or started.
End Try
Return True ' Returns True if Read_Output argument is set to False and the process finished without errors.
End Function
#End Region
How to remove specific elements in a numpy array
Remove specific index(i removed 16 and 21 from matrix)
import numpy as np
mat = np.arange(12,26)
a = [4,9]
del_map = np.delete(mat, a)
del_map.reshape(3,4)
Output:
array([[12, 13, 14, 15],
[17, 18, 19, 20],
[22, 23, 24, 25]])
Git fast forward VS no fast forward merge
The --no-ff
option is useful when you want to have a clear notion of your feature branch. So even if in the meantime no commits were made, FF is possible - you still want sometimes to have each commit in the mainline correspond to one feature. So you treat a feature branch with a bunch of commits as a single unit, and merge them as a single unit. It is clear from your history when you do feature branch merging with --no-ff
.
If you do not care about such thing - you could probably get away with FF whenever it is possible. Thus you will have more svn-like feeling of workflow.
For example, the author of this article thinks that --no-ff
option should be default and his reasoning is close to that I outlined above:
Consider the situation where a series of minor commits on the "feature" branch collectively make up one new feature: If you just do "git merge feature_branch" without --no-ff
, "it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache [if --no-ff
is not used], whereas it is easily done if the --no-ff
flag was used [because it's just one commit]."
Custom li list-style with font-awesome icon
I'd like to provide an alternate, easier solution that is specific to FontAwesome. If you're using a different iconic font, JOPLOmacedo's answer is still perfectly fine for use.
FontAwesome now handles list styles internally with CSS classes.
Here's the official example:
<ul class="fa-ul">
<li><span class="fa-li"><i class="fas fa-check-square"></i></span>List icons can</li>
<li><span class="fa-li"><i class="fas fa-check-square"></i></span>be used to</li>
<li><span class="fa-li"><i class="fas fa-spinner fa-pulse"></i></span>replace bullets</li>
<li><span class="fa-li"><i class="far fa-square"></i></span>in lists</li>
</ul>
How to evaluate a boolean variable in an if block in bash?
bash doesn't know boolean variables, nor does test
(which is what gets called when you use [
).
A solution would be:
if $myVar ; then ... ; fi
because true
and false
are commands that return 0
or 1
respectively which is what if
expects.
Note that the values are "swapped". The command after if
must return 0
on success while 0
means "false" in most programming languages.
SECURITY WARNING: This works because BASH expands the variable, then tries to execute the result as a command! Make sure the variable can't contain malicious code like rm -rf /
Catching exceptions from Guzzle
I want to update the answer for exception handling in Psr-7 Guzzle, Guzzle7 and HTTPClient(expressive, minimal API around the Guzzle HTTP client provided by laravel).
Guzzle7 (same works for Guzzle 6 as well)
Using RequestException, RequestException catches any exception that can be thrown while transferring requests.
try{
$client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer ' . $token]]);
$guzzleResponse = $client->get('/foobar');
// or can use
// $guzzleResponse = $client->request('GET', '/foobar')
if ($guzzleResponse->getStatusCode() == 200) {
$response = json_decode($guzzleResponse->getBody(),true);
//perform your action with $response
}
}
catch(\GuzzleHttp\Exception\RequestException $e){
// you can catch here 400 response errors and 500 response errors
// You can either use logs here use Illuminate\Support\Facades\Log;
$error['error'] = $e->getMessage();
$error['request'] = $e->getRequest();
if($e->hasResponse()){
if ($e->getResponse()->getStatusCode() == '400'){
$error['response'] = $e->getResponse();
}
}
Log::error('Error occurred in get request.', ['error' => $error]);
}catch(Exception $e){
//other errors
}
Psr7 Guzzle
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;
try {
$client->request('GET', '/foo');
} catch (RequestException $e) {
$error['error'] = $e->getMessage();
$error['request'] = Psr7\Message::toString($e->getRequest());
if ($e->hasResponse()) {
$error['response'] = Psr7\Message::toString($e->getResponse());
}
Log::error('Error occurred in get request.', ['error' => $error]);
}
For HTTPClient
use Illuminate\Support\Facades\Http;
try{
$response = Http::get('http://api.foo.com');
if($response->successful()){
$reply = $response->json();
}
if($response->failed()){
if($response->clientError()){
//catch all 400 exceptions
Log::debug('client Error occurred in get request.');
$response->throw();
}
if($response->serverError()){
//catch all 500 exceptions
Log::debug('server Error occurred in get request.');
$response->throw();
}
}
}catch(Exception $e){
//catch the exception here
}
How to generate XML from an Excel VBA macro?
Credit to: curiousmind.jlion.com/exceltotextfile (Link no longer exists)
Script:
Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFileName As String)
Dim Q As String
Q = Chr$(34)
Dim sXML As String
sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
sXML = sXML & "<rows>"
''--determine count of columns
Dim iColCount As Integer
iColCount = 1
While Trim$(Cells(iCaptionRow, iColCount)) > ""
iColCount = iColCount + 1
Wend
Dim iRow As Integer
iRow = iDataStartRow
While Cells(iRow, 1) > ""
sXML = sXML & "<row id=" & Q & iRow & Q & ">"
For icol = 1 To iColCount - 1
sXML = sXML & "<" & Trim$(Cells(iCaptionRow, icol)) & ">"
sXML = sXML & Trim$(Cells(iRow, icol))
sXML = sXML & "</" & Trim$(Cells(iCaptionRow, icol)) & ">"
Next
sXML = sXML & "</row>"
iRow = iRow + 1
Wend
sXML = sXML & "</rows>"
Dim nDestFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nDestFile = FreeFile
''Write the entire file to sText
Open sOutputFileName For Output As #nDestFile
Print #nDestFile, sXML
Close
End Sub
Sub test()
MakeXML 1, 2, "C:\Users\jlynds\output2.xml"
End Sub
How to terminate process from Python using pid?
I wanted to do the same thing as, but I wanted to do it in the one file.
So the logic would be:
- if a script with my name is running, kill it, then exit
- if a script with my name is not running, do stuff
I modified the answer by Bakuriu and came up with this:
from os import getpid
from sys import argv, exit
import psutil ## pip install psutil
myname = argv[0]
mypid = getpid()
for process in psutil.process_iter():
if process.pid != mypid:
for path in process.cmdline():
if myname in path:
print "process found"
process.terminate()
exit()
## your program starts here...
Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.
I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.
Generic deep diff between two objects
I know I'm late to the party, but I needed something similar that the above answers didn't help.
I was using Angular's $watch function to detect changes in a variable. Not only did I need to know whether a property had changed on the variable, but I also wanted to make sure that the property that changed was not a temporary, calculated field. In other words, I wanted to ignore certain properties.
Here's the code: https://jsfiddle.net/rv01x6jo/
Here's how to use it:
// To only return the difference
var difference = diff(newValue, oldValue);
// To exclude certain properties
var difference = diff(newValue, oldValue, [newValue.prop1, newValue.prop2, newValue.prop3]);
Hope this helps someone.
How to ssh from within a bash script?
If you want the password prompt to go away then use key based authentication (described here).
To run commands remotely over ssh you have to give them as an argument to ssh, like the following:
root@host:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'
ASP.NET postback with JavaScript
Here is a complete solution
Entire form tag of the asp.net page
<form id="form1" runat="server">
<asp:LinkButton ID="LinkButton1" runat="server" /> <%-- included to force __doPostBack javascript function to be rendered --%>
<input type="button" id="Button45" name="Button45" onclick="javascript:__doPostBack('ButtonA','')" value="clicking this will run ButtonA.Click Event Handler" /><br /><br />
<input type="button" id="Button46" name="Button46" onclick="javascript:__doPostBack('ButtonB','')" value="clicking this will run ButtonB.Click Event Handler" /><br /><br />
<asp:Button runat="server" ID="ButtonA" ClientIDMode="Static" Text="ButtonA" /><br /><br />
<asp:Button runat="server" ID="ButtonB" ClientIDMode="Static" Text="ButtonB" />
</form>
Entire Contents of the Page's Code-Behind Class
Private Sub ButtonA_Click(sender As Object, e As System.EventArgs) Handles ButtonA.Click
Response.Write("You ran the ButtonA click event")
End Sub
Private Sub ButtonB_Click(sender As Object, e As System.EventArgs) Handles ButtonB.Click
Response.Write("You ran the ButtonB click event")
End Sub
- The LinkButton is included to ensure that the __doPostBack javascript function is rendered to the client. Simply having Button controls will not cause this __doPostBack function to be rendered. This function will be rendered by virtue of having a variety of controls on most ASP.NET pages, so an empty link button is typically not needed
What's going on?
Two input controls are rendered to the client:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
__EVENTTARGET
receives argument 1 of __doPostBack
__EVENTARGUMENT
receives argument 2 of __doPostBack
The __doPostBack function is rendered out like this:
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
- As you can see, it assigns the values to the hidden inputs.
When the form submits / postback occurs:
- If you provided the UniqueID of the Server-Control Button whose button-click-handler you want to run (
javascript:__doPostBack('ButtonB','')
, then the button click handler for that button will be run.
What if I don't want to run a click handler, but want to do something else instead?
You can pass whatever you want as arguments to __doPostBack
You can then analyze the hidden input values and run specific code accordingly:
If Request.Form("__EVENTTARGET") = "DoSomethingElse" Then
Response.Write("Do Something else")
End If
Other Notes
- What if I don't know the ID of the control whose click handler I want to run?
- If it is not acceptable to set
ClientIDMode="Static"
, then you can do something like this: __doPostBack('<%= myclientid.UniqueID %>', '')
.
- Or:
__doPostBack('<%= MYBUTTON.UniqueID %>','')
- This will inject the unique id of the control into the javascript, should you wish it
How to print multiple variable lines in Java
You can create Class Person
with fields firstName
and lastName
and define method toString()
. Here I created a util method which returns String presentation of a Person
object.
This is a sample
Main
public class Main {
public static void main(String[] args) {
Person person = generatePerson();
String personStr = personToString(person);
System.out.println(personStr);
}
private static Person generatePerson() {
String firstName = "firstName";//generateFirstName();
String lastName = "lastName";//generateLastName;
return new Person(firstName, lastName);
}
/*
You can even put this method into a separate util class.
*/
private static String personToString(Person person) {
return person.getFirstName() + "\n" + person.getLastName();
}
}
Person
public class Person {
private String firstName;
private String lastName;
//getters, setters, constructors.
}
I prefer a separate util method to toString()
, because toString()
is used for debug.
https://stackoverflow.com/a/3615741/4587961
I had experience writing programs with many outputs: HTML UI, excel or txt file, console. They may need different object presentation, so I created a util class which builds a String depending on the output.
Check if input value is empty and display an alert
Check empty input with removing space(if user enter space) from input using trim
$(document).ready(function(){
$('#button').click(function(){
if($.trim($('#fname').val()) == '')
{
$('#fname').css("border-color", "red");
alert("Empty");
}
});
});
To the power of in C?
You need pow();
function from math.h
header.
syntax
#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
Here x is base and y is exponent. result is x^y
.
usage
pow(2,4);
result is 2^4 = 16. //this is math notation only
// In c ^ is a bitwise operator
And make sure you include math.h
to avoid warning ("incompatible implicit declaration of built in function 'pow'
").
Link math library by using -lm
while compiling. This is dependent on Your environment.
For example if you use Windows it's not required to do so, but it is in UNIX based systems.
Creating Accordion Table with Bootstrap
For anyone who came here looking for how to get the true accordion effect and only allow one row to be expanded at a time, you can add an event handler for show.bs.collapse like so:
$('.collapse').on('show.bs.collapse', function () {
$('.collapse.in').collapse('hide');
});
I modified this example to do so here: http://jsfiddle.net/QLfMU/116/
How to find where gem files are installed
You can check it from your command prompt by running gem help commands
and then selecting the proper command:
kirti@kirti-Aspire-5733Z:~$ gem help commands
GEM commands are:
build Build a gem from a gemspec
cert Manage RubyGems certificates and signing settings
check Check a gem repository for added or missing files
cleanup Clean up old versions of installed gems in the local
repository
contents Display the contents of the installed gems
dependency Show the dependencies of an installed gem
environment Display information about the RubyGems environment
fetch Download a gem and place it in the current directory
generate_index Generates the index files for a gem server directory
help Provide help on the 'gem' command
install Install a gem into the local repository
list Display gems whose name starts with STRING
lock Generate a lockdown list of gems
mirror Mirror all gem files (requires rubygems-mirror)
outdated Display all gems that need updates
owner Manage gem owners on RubyGems.org.
pristine Restores installed gems to pristine condition from
files located in the gem cache
push Push a gem up to RubyGems.org
query Query gem information in local or remote repositories
rdoc Generates RDoc for pre-installed gems
regenerate_binstubs Re run generation of executable wrappers for gems.
search Display all gems whose name contains STRING
server Documentation and gem repository HTTP server
sources Manage the sources and cache file RubyGems uses to
search for gems
specification Display gem specification (in yaml)
stale List gems along with access times
uninstall Uninstall gems from the local repository
unpack Unpack an installed gem to the current directory
update Update installed gems to the latest version
which Find the location of a library file you can require
yank Remove a specific gem version release from
RubyGems.org
For help on a particular command, use 'gem help COMMAND'.
Commands may be abbreviated, so long as they are unambiguous.
e.g. 'gem i rake' is short for 'gem install rake'.
kirti@kirti-Aspire-5733Z:~$
Now from the above I can see the command environment
is helpful. So I would do:
kirti@kirti-Aspire-5733Z:~$ gem help environment
Usage: gem environment [arg] [options]
Common Options:
-h, --help Get help on this command
-V, --[no-]verbose Set the verbose level of output
-q, --quiet Silence commands
--config-file FILE Use this config file instead of default
--backtrace Show stack backtrace on errors
--debug Turn on Ruby debugging
Arguments:
packageversion display the package version
gemdir display the path where gems are installed
gempath display path used to search for gems
version display the gem format version
remotesources display the remote gem servers
platform display the supported gem platforms
<omitted> display everything
Summary:
Display information about the RubyGems environment
Description:
The RubyGems environment can be controlled through command line arguments,
gemrc files, environment variables and built-in defaults.
Command line argument defaults and some RubyGems defaults can be set in a
~/.gemrc file for individual users and a /etc/gemrc for all users. These
files are YAML files with the following YAML keys:
:sources: A YAML array of remote gem repositories to install gems from
:verbose: Verbosity of the gem command. false, true, and :really are the
levels
:update_sources: Enable/disable automatic updating of repository metadata
:backtrace: Print backtrace when RubyGems encounters an error
:gempath: The paths in which to look for gems
:disable_default_gem_server: Force specification of gem server host on
push
<gem_command>: A string containing arguments for the specified gem command
Example:
:verbose: false
install: --no-wrappers
update: --no-wrappers
:disable_default_gem_server: true
RubyGems' default local repository can be overridden with the GEM_PATH and
GEM_HOME environment variables. GEM_HOME sets the default repository to
install into. GEM_PATH allows multiple local repositories to be searched for
gems.
If you are behind a proxy server, RubyGems uses the HTTP_PROXY,
HTTP_PROXY_USER and HTTP_PROXY_PASS environment variables to discover the
proxy server.
If you would like to push gems to a private gem server the RUBYGEMS_HOST
environment variable can be set to the URI for that server.
If you are packaging RubyGems all of RubyGems' defaults are in
lib/rubygems/defaults.rb. You may override these in
lib/rubygems/defaults/operating_system.rb
kirti@kirti-Aspire-5733Z:~$
Finally to show you what you asked, I would do:
kirti@kirti-Aspire-5733Z:~$ gem environment gemdir
/home/kirti/.rvm/gems/ruby-2.0.0-p0
kirti@kirti-Aspire-5733Z:~$ gem environment gempath
/home/kirti/.rvm/gems/ruby-2.0.0-p0:/home/kirti/.rvm/gems/ruby-2.0.0-p0@global
kirti@kirti-Aspire-5733Z:~$
number several equations with only one number
First of all, you probably don't want the align
environment if you have only one column of equations. In fact, your example is probably best with the cases
environment. But to answer your question directly, used the aligned
environment within equation
- this way the outside environment gives the number:
\begin{equation}
\begin{aligned}
w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1, \\
w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
\end{aligned}
\end{equation}
The documentation of the amsmath
package explains this and more.
Rewrite all requests to index.php with nginx
If you want to pass just the index.php ( no other php file will be passed to fastcgi ) to fastcgi in case you have routes like this in a framework like codeigniter
$route["/download.php"] = "controller/method";
location ~ index\.php$ {
fastcgi_pass 127.0.0.1:9000;
include fastcgi.conf;
}
How to remove the Flutter debug banner?
On your MaterialApp
set debugShowCheckedModeBanner
to false
.
MaterialApp(
debugShowCheckedModeBanner: false,
)
The debug banner will also automatically be removed on release build.
PL/SQL block problem: No data found error
Your SELECT
statement isn't finding the data you're looking for. That is, there is no record in the ENROLLMENT
table with the given STUDENT_ID
and SECTION_ID
. You may want to try putting some DBMS_OUTPUT.PUT_LINE
statements before you run the query, printing the values of v_student_id
and v_section_id
. They may not be containing what you expect them to contain.
Set type for function parameters?
You can implement a system that handles the type checks automatically, using a wrapper in your function.
With this approach, you can build a complete declarative type check system
that will manage for you the type checks .
If you are interested in taking a more in depth look at this concept, check the Functyped library
The following implementation illustrates the main idea, in a simplistic, but operative way :
_x000D_
_x000D_
/*_x000D_
* checkType() : Test the type of the value. If succeds return true, _x000D_
* if fails, throw an Error_x000D_
*/_x000D_
function checkType(value,type, i){_x000D_
// perform the appropiate test to the passed _x000D_
// value according to the provided type_x000D_
switch(type){_x000D_
case Boolean : _x000D_
if(typeof value === 'boolean') return true;_x000D_
break;_x000D_
case String : _x000D_
if(typeof value === 'string') return true;_x000D_
break;_x000D_
case Number : _x000D_
if(typeof value === 'number') return true;_x000D_
break;_x000D_
default :_x000D_
throw new Error(`TypeError : Unknown type provided in argument ${i+1}`);_x000D_
}_x000D_
// test didn't succeed , throw error_x000D_
throw new Error(`TypeError : Expecting a ${type.name} in argument ${i+1}`);_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
* typedFunction() : Constructor that returns a wrapper_x000D_
* to handle each function call, performing automatic _x000D_
* arguments type checking_x000D_
*/_x000D_
function typedFunction( parameterTypes, func ){_x000D_
// types definitions and function parameters _x000D_
// count must match_x000D_
if(parameterTypes.length !== func.length) throw new Error(`Function has ${func.length} arguments, but type definition has ${parameterTypes.length}`);_x000D_
// return the wrapper..._x000D_
return function(...args){_x000D_
// provided arguments count must match types_x000D_
// definitions count_x000D_
if(parameterTypes.length !== args.length) throw new Error(`Function expects ${func.length} arguments, instead ${args.length} found.`);_x000D_
// iterate each argument value, and perform a_x000D_
// type check against it, using the type definitions_x000D_
// provided in the construction stage_x000D_
for(let i=0; i<args.length;i++) checkType( args[i], parameterTypes[i] , i)_x000D_
// if no error has been thrown, type check succeed_x000D_
// execute function!_x000D_
return func(...args);_x000D_
}_x000D_
}_x000D_
_x000D_
// Play time! _x000D_
// Declare a function that expects 2 Numbers_x000D_
let myFunc = typedFunction( [ Number, Number ], (a,b)=>{_x000D_
return a+b;_x000D_
});_x000D_
_x000D_
// call the function, with an invalid second argument_x000D_
myFunc(123, '456')_x000D_
// ERROR! Uncaught Error: TypeError : Expecting a Number in argument 2
_x000D_
_x000D_
_x000D_
Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type
I encounted this error and found that it was because the "strict" parameter was set to true in the tsconfig.json file. Just set it "false" (obviously). In my case I had generated the tsconfig file from the cmd prompt and simply missed the "strict" parameter, which was located further down in the file.
This could be due to the service endpoint binding not using the HTTP protocol
I struggled with this for a couple of days and tried every answer from this post and many others and share my solution because symptoms were the same but the problem was different.
The problem was that the app pool was configured with a memory limit and it just get recycled after a variable period of time.
Hope this helps somebody else!
Greetings,
How to animate button in android?
Class.Java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_with_the_button);
final Animation myAnim = AnimationUtils.loadAnimation(this, R.anim.milkshake);
Button myButton = (Button) findViewById(R.id.new_game_btn);
myButton.setAnimation(myAnim);
}
For onClick of the Button
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.startAnimation(myAnim);
}
});
Create the anim folder in res directory
Right click on, res -> New -> Directory
Name the new Directory anim
create a new xml file name it milkshake
milkshake.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="100"
android:fromDegrees="-5"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="10"
android:repeatMode="reverse"
android:toDegrees="5" />
Wampserver icon not going green fully, mysql services not starting up?
simplest this to do is find what other service is using the same service id as mysql does in windows.
When i looked through the list of services running on my pc (even after a restart...i still had the problem)
I quickly realised i had webmatrix installed on my computer previous to wamp server...webmatrix installed its own copy of mysql and set it to automatically startup another instance each time i logged in.
As soon as the other instance of mysql associated with web matrix was stopped (and changed from automatic startup to manual) my problem with WAMP mysql was solved.
Which browsers support <script async="async" />?
The async support as specified by google is achieved using two parts:
using script on your page (the script is supplied by google) to write out a <script> tag to the DOM.
that script has async="true" attribute to signal to compatible browsers that it can continue rendering the page.
The first part works on browsers without support for <script async..
tags, allowing them to load async with a "hack" (although a pretty solid one), and also allows rendering the page without waiting for ga.js to be retrieved.
The second part only affects compatible browsers that understand the async html attribute
- FF 3.6+
- FF for Android All Versions
- IE 10+ (starting with preview 2)
- Chrome 8+
- Chrome For Android All versions
- Safari 5.0+
- iOS Safari 5.0+
- Android Browser 3.0+ (honeycomb on up)
- Opera 15.0+
- Opera Mobile 16.0+
- Opera Mini None (as of 8.0)
The "html5 proper" way to specify async is with a <script async src="..."
, not <script async="true"
. However, initially browsers did not support this syntax, nor did they support setting the script property on referenced elements. If you want this, the list changes:
- FF 4+
- IE 10+ (preview 2 and up)
- Chrome 12+
- Chrome For Android 32+
- Safari 5.1+
- No android versions
How do you round UP a number in Python?
Without importing math // using basic envionment:
a) method / class method
def ceil(fl):
return int(fl) + (1 if fl-int(fl) else 0)
def ceil(self, fl):
return int(fl) + (1 if fl-int(fl) else 0)
b) lambda:
ceil = lambda fl:int(fl)+(1 if fl-int(fl) else 0)
Authentication versus Authorization
Definitions
Authentication - Are you the person you claim to be?
Authorization - Are you authorized to do whatever it is you're trying to do?
Example
A web app uses Google Sign-In. After a user successfully signs in, Google sends back:
- A JWT token. This can be validated and decoded to get authentication information. Is the token signed by Google? What is the user's name and email?
- An access token. This authorizes the web app to access Google APIs on behalf of the user. For example, can the app access the user's Google Calendar events? These permissions depend on the scopes that were requested, and whether or not the user allowed it.
Additionally:
The company may have an admin dashboard that allows customer support to manage the company's users. Instead of providing a custom signup solution that would allow customer support to access this dashboard, the company uses Google Sign-In.
The JWT token (received from the Google sign in process) is sent to the company's authorization server to figure out if the user has a G Suite account with the organization's hosted domain ([email protected])? And if they do, are they a member of the company's Google Group that was created for customer support? If yes to all of the above, we can consider them authenticated.
The company's authorization server then sends the dashboard app an access token. This access token can be used to make authorized requests to the company's resource server (e.g. ability to make a GET request to an endpoint that sends back all of the company's users).
macOS on VMware doesn't recognize iOS device
I am running an Iphone 8+ and VMWare macOS High Sierra on a Windows 10 machine.
I went through dozens of troubleshooting posts, and the none of them, excluding setting your VMs USBs to 2.0, helped. Through trial and error, and a decent amount of liquor, I have figured it out.
SOLUTION:
Do these things, in this order:
With the VM off, go to your settings for whichever machine you're using, and change the USBs to 2.0. You can find this in the same menu that you allocated your ram and cores
Make sure your phone is plugged in, and turned off.
Boot up the VM, macOS.
Turn Phone on when mac is booted
Open Xcode
Razor view engine - How can I add Partial Views
If you don't want to duplicate code, and like me you just want to show stats, in your view model, you could just pass in the models you want to get data from like so:
public class GameViewModel
{
public virtual Ship Ship { get; set; }
public virtual GamePlayer GamePlayer { get; set; }
}
Then, in your controller just run your queries on the respective models, pass them to the view model and return it, example:
GameViewModel PlayerStats = new GameViewModel();
GamePlayer currentPlayer = (from c in db.GamePlayer [more queries]).FirstOrDefault();
[code to check if results]
//pass current player into custom view model
PlayerStats.GamePlayer = currentPlayer;
Like I said, you should only really do this if you want to display stats from the relevant tables, and there's no other part of the CRUD process happening, for security reasons other people have mentioned above.
.NET Format a string with fixed spaces
The first and the last, at least, are possible using the following syntax:
String.Format("{0,20}", "String goes here");
String.Format("{0,-20}", "String goes here");
Need a row count after SELECT statement: what's the optimal SQL approach?
Approach 2 will always return a count that matches your result set.
I suggest you link the sub-query to your outer query though, to guarantee that the condition on your count matches the condition on the dataset.
SELECT
mt.my_row,
(SELECT COUNT(mt2.my_row) FROM my_table mt2 WHERE mt2.foo = mt.foo) as cnt
FROM my_table mt
WHERE mt.foo = 'bar';
Undo a Git merge that hasn't been pushed yet
Lately, I've been using git reflog
to help with this. This mostly only works if the merge JUST happened, and it was on your machine.
git reflog
might return something like:
fbb0c0f HEAD@{0}: commit (merge): Merge branch 'master' into my-branch
43b6032 HEAD@{1}: checkout: moving from master to my-branch
e3753a7 HEAD@{2}: rebase finished: returning to refs/heads/master
e3753a7 HEAD@{3}: pull --rebase: checkout e3753a71d92b032034dcb299d2df2edc09b5830e
b41ea52 HEAD@{4}: reset: moving to HEAD^
8400a0f HEAD@{5}: rebase: aborting
The first line indicates that a merge occurred. The 2nd line is the time before my merge. I simply git reset --hard 43b6032
to force this branch to track from before the merge, and carry-on.
How to remove a Gitlab project?
- Open project
- Setting (In the left sidebar)
- General
- Advanced Setting (Click on Expand)
- Remove Project (Bottom of the Page)
- Confirm (By typing project name and press Confirm button)
Laravel: PDOException: could not find driver
On Windows, I followed the same path as the previous answers. The difference is that the path to php.ini is usually different from the traditional ones, usually in Apache.
To find php.ini, I used the following path: C:\tools\php80\php.ini
After that, I uncommented the pdo extension files
and the migration worked.
What is define([ , function ]) in JavaScript?
That's probably a requireJS module definition
Check here for more details
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
The module was expected to contain an assembly manifest
First try to open the file with a decompiler such as ILSpy, your dll might be corrupt. I had this error on an online web site, when I downloaded the dll and tried to open it, it was corrupt, probably some error occurred while uploading it via ftp.
Finding modified date of a file/folder
Here's what worked for me:
$a = Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-7)}
if ($a = (Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}
#Im using the -gt switch instead of -ge
{}
Else
{
'STORE XXX HAS NOT RECEIVED ANY ORDERS IN THE PAST 7 DAYS'
}
$b = Get-ChildItem \\COMP NAME\Folder\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-1)}
if ($b = (Get-ChildItem \\COMP NAME\TFolder\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-1)))}
{}
Else
{
'STORE XXX DID NOT RUN ITS BACKUP LAST NIGHT'
}
HTML Button Close Window
When in the onclick
attribute you do not need to specify that it is Javascript.
<button type="button"
onclick="window.open('', '_self', ''); window.close();">Discard</button>
This should do it. In order to close it your page needs to be opened by the script, hence the window.open. Here is an article explaining this in detail:
Click Here
If all else fails, you should also add a message asking the user to manually close the window, as there is no cross-browser solution for this, especially with older browsers such as IE 8.
Post to another page within a PHP script
index.php
$url = 'http://[host]/test.php';
$json = json_encode(['name' => 'Jhonn', 'phone' => '128000000000']);
$options = ['http' => [
'method' => 'POST',
'header' => 'Content-type:application/json',
'content' => $json
]];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
test.php
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
echo $data['name']; // Jhonn
Zabbix server is not running: the information displayed may not be current
On RHEL/CentOS/OEL 6
and add the following lines
-A INPUT -m state --state NEW -m tcp -p tcp --dport 10051 -j ACCEPT
restart iptables
# service iptables restart
If you have disabled IPV6, you need to also edit the hosts file and remove IPV6 line for "localhost"
# vi /etc/hosts
remove or comment out "#" the ipv6 line for localhost
::1 localhost6.localdomain6 localhost6
restart the zabbix-server and check if the error message is gone.
Format date and time in a Windows batch script
I usually do it this way whenever I need a date/time string:
set dt=%DATE:~6,4%_%DATE:~3,2%_%DATE:~0,2%__%TIME:~0,2%_%TIME:~3,2%_%TIME:~6,2%
set dt=%dt: =0%
This is for the German date/time format (dd.mm.yyyy hh:mm:ss). Basically I concatenate the substrings and finally replace all spaces with zeros.
Short explanation of how substrings work:
%VARIABLE:~num_chars_to_skip,num_chars_to_keep%
So to get just the year from a date like "29.03.2018" use:
%DATE:~6,4%
^-----skip 6 characters
^---keep 4 characters
Loading inline content using FancyBox
The way I figured this out was going through the example index.html/style.css that comes packaged with the Fancybox installation.
If you view the code that is used for the demo website and basically copy/paste, you'll be fine.
To get an inline Fancybox working, you will need to have this code present in your index.html file:
<head>
<link href="./fancybox/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" media="screen" />
<script>!window.jQuery && document.write('<script src="jquery-1.4.3.min.js"><\/script>');</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="./fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#various1").fancybox({
'titlePosition' : 'inside',
'transitionIn' : 'none',
'transitionOut' : 'none'
});
});
</script>
</head>
<body>
<a id="various1" href="#inline1" title="Put a title here">Name of Link Here</a>
<div style="display: none;">
<div id="inline1" style="width:400px;height:100px;overflow:auto;">
Write whatever text you want right here!!
</div>
</div>
</body>
Remember to be precise about what folders your script files are placed in and where you are pointing to in the Head tag; they must correspond.
What is the difference between background and background-color
background
will supercede all previous background-color
, background-image
, etc. specifications. It's basically a shorthand, but a reset as well.
I will sometimes use it to overwrite previous background
specifications in template customizations, where I would want the following:
background: white url(images/image1.jpg) top left repeat;
to be the following:
background: black;
So, all parameters (background-image
, background-position
, background-repeat
) will reset to their default values.
Float and double datatype in Java
Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. For example, calculations such as square root, or transcendentals such as sine and cosine, result in a value whose precision requires a floating-point type. Java implements the standard (IEEE–754) set of floatingpoint types and operators. There are two kinds of floating-point types, float and double, which represent single- and double-precision numbers, respectively. Their width and ranges are shown here:
Name Width in Bits Range
double 64 1 .7e–308 to 1.7e+308
float 32 3 .4e–038 to 3.4e+038
float
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors and takes half as much space as double precision, but will become imprecise when the values are either very large or very small. Variables of type float are useful when you need a fractional component, but don't require a large degree of precision.
Here are some example float variable declarations:
float hightemp, lowtemp;
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued numbers, double is the best choice.
Undefined reference to 'vtable for xxx'
One or more of your .cpp files is not being linked in, or some non-inline functions in some class are not defined. In particular, takeaway::textualGame()
's implementation can't be found. Note that you've defined a textualGame()
at toplevel, but this is distinct from a takeaway::textualGame()
implementation - probably you just forgot the takeaway::
there.
What the error means is that the linker can't find the "vtable" for a class - every class with virtual functions has a "vtable" data structure associated with it. In GCC, this vtable is generated in the same .cpp file as the first listed non-inline member of the class; if there's no non-inline members, it will be generated wherever you instantiate the class, I believe. So you're probably failing to link the .cpp file with that first-listed non-inline member, or never defining that member in the first place.
matrix multiplication algorithm time complexity
The naive algorithm, which is what you've got once you correct it as noted in comments, is O(n^3).
There do exist algorithms that reduce this somewhat, but you're not likely to find an O(n^2) implementation. I believe the question of the most efficient implementation is still open.
See this wikipedia article on Matrix Multiplication for more information.
Rails: Adding an index after adding column
You can use this, just think Job is the name of the model to which you are adding index cader_id:
class AddCaderIdToJob < ActiveRecord::Migration[5.2]
def change
change_table :jobs do |t|
t.integer :cader_id
t.index :cader_id
end
end
end
Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa
This is the full onClick handler for the Image/Button to show/hide the password.
new OnClickListener() {
@Override
public void onClick(View v) {
// current ursor position
int cursorPosition = edtPassword.getSelectionStart();
// toggles the control variable
isPassworsVisible = !isPassworsVisible;
// sets the image toggler inside edit text
passwordVisible.setImageDrawable(getResources().getDrawable(isPassworsVisible ? R.drawable.ic_eye_checked : R.drawable.ic_eye_unchecked));
// apply input type
edtPassword.setInputType(isPassworsVisible ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
// returns cursor to position
edtPassword.setSelection(cursorPosition);
}
};
What does -z mean in Bash?
-z
string is null, that is, has zero length
String='' # Zero-length ("null") string variable.
if [ -z "$String" ]
then
echo "\$String is null."
else
echo "\$String is NOT null."
fi # $String is null.
python-How to set global variables in Flask?
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
How to retrieve a user environment variable in CMake (Windows)
You can also invoke cmake itself to do this in a cross-platform way:
cmake -E env EnvironmentVariableName="Hello World" cmake ..
env [--unset=NAME]... [NAME=VALUE]... COMMAND [ARG]...
Run command in a modified environment.
Just be aware that this may only work the first time. If CMake re-configures with one of the consecutive builds (you just call e.g. make
, one CMakeLists.txt
was changed and CMake runs through the generation process again), the user defined environment variable may not be there anymore (in comparison to system wide environment variables).
So I transfer those user defined environment variables in my projects into a CMake cached variable:
cmake_minimum_required(VERSION 2.6)
project(PrintEnv NONE)
if (NOT "$ENV{EnvironmentVariableName}" STREQUAL "")
set(EnvironmentVariableName "$ENV{EnvironmentVariableName}" CACHE INTERNAL "Copied from environment variable")
endif()
message("EnvironmentVariableName = ${EnvironmentVariableName}")
Reference
How to have multiple CSS transitions on an element?
EDIT: I'm torn on whether to delete this post. As a matter of understanding the CSS syntax, it's good that people know all
exists, and it may at times be preferable to a million individual declarations, depending on the structure of your CSS. On the other hand, it may have a performance penalty, although I've yet to see any data supporting that hypothesis. For now, I'll leave it, but I want people to be aware it's a mixed bag.
Original post:
You can also simply significantly with:
.nav a {
transition: all .2s;
}
FWIW: all
is implied if not specified, so transition: .2s;
will get you to the same place.
Position last flex item at the end of container
Flexible Box Layout Module - 8.1. Aligning with auto margins
Auto margins on flex items have an effect very similar to auto margins in block flow:
During calculations of flex bases and flexible lengths, auto margins are treated as 0.
Prior to alignment via justify-content
and align-self
, any positive free space is distributed to auto margins in that dimension.
Therefore you could use margin-top: auto
to distribute the space between the other elements and the last element.
This will position the last element at the bottom.
p:last-of-type {
margin-top: auto;
}
_x000D_
_x000D_
.container {
display: flex;
flex-direction: column;
border: 1px solid #000;
min-height: 200px;
width: 100px;
}
p {
height: 30px;
background-color: blue;
margin: 5px;
}
p:last-of-type {
margin-top: auto;
}
_x000D_
<div class="container">
<p></p>
<p></p>
<p></p>
</div>
_x000D_
_x000D_
_x000D_
Likewise, you can also use margin-left: auto
or margin-right: auto
for the same alignment horizontally.
p:last-of-type {
margin-left: auto;
}
_x000D_
_x000D_
.container {
display: flex;
width: 100%;
border: 1px solid #000;
}
p {
height: 50px;
width: 50px;
background-color: blue;
margin: 5px;
}
p:last-of-type {
margin-left: auto;
}
_x000D_
<div class="container">
<p></p>
<p></p>
<p></p>
<p></p>
</div>
_x000D_
_x000D_
_x000D_
MySQL Error 1215: Cannot add foreign key constraint
In my case, I had deleted a table using SET FOREIGN_KEY_CHECKS=0
, then SET FOREIGN_KEY_CHECKS=1
after. When I went to reload the table, I got error 1215
. The problem was there was another table in the database that had a foreign key to the table I had deleted and was reloading. Part of the reloading process involved changing a data type for one of the fields, which made the foreign key from the other table invalid, thus triggering error 1215
. I resolved the problem by dropping and then reloading the other table with the new data type for the involved field.
php search array key and get value
Here is an example straight from PHP.net
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}
in the foreach you can do a comparison of each key to something that you are looking for
Regular Expression with wildcards to match any character
The following should work:
ABC: *\([a-zA-Z]+\) *(.+)
Explanation:
ABC: # match literal characters 'ABC:'
* # zero or more spaces
\([a-zA-Z]+\) # one or more letters inside of parentheses
* # zero or more spaces
(.+) # capture one or more of any character (except newlines)
To get your desired grouping based on the comments below, you can use the following:
(ABC:) *(\([a-zA-Z]+\).+)
How to get the file path from HTML input form in Firefox 3
This is an alternate solution/fix... In FF3, You can retrieve file's full path in a textbox instead of file browse box. And that too... By drag/dropping the file!
You can drag drop your file into a text box in your html page. and it will display the file's complete path. This data can transferred to your server easily or manipulate them.
All you have to do is to use the extension DragDropUpload
http://www.teslacore.it/wiki/index.php?title=DragDropUpload
This extension will helps you in drag dropping files into your File Browse (Input file) box. But still you wont able to get the file full path, If you try to retrieve.
So, I tweaked this extension a little. In the way I can drag drop a file on to any "Text Input" box and get the file full path. And thus I can able to get the file full path in FF3 Firefox 3.
d3.select("#element") not working when code above the html element
<script>$(function(){var svg = d3.select("#chart").append("svg:svg");});</script>
<div id="chart"></div>
In other words, it's not happening because you can't query against something that doesn't exist yet-- so just do it after the page loads (here via jquery).
Btw, its recommended that you place your JS files before the close of your body tag.
When do I use the PHP constant "PHP_EOL"?
I am using WebCalendar and found that Mac iCal barfs on importing a generated ics file because the end-of-line is hardcoded in xcal.php as "\r\n". I went in and replaced all occurrences with PHP_EOL and now iCal is happy!
I also tested it on Vista and Outlook was able to import the file as well, even though the end of line character is "\n".
Difference between string and char[] types in C++
Well, string type is a completely managed class for character strings, while char[] is still what it was in C, a byte array representing a character string for you.
In terms of API and standard library everything is implemented in terms of strings and not char[], but there are still lots of functions from the libc that receive char[] so you may need to use it for those, apart from that I would always use std::string.
In terms of efficiency of course a raw buffer of unmanaged memory will almost always be faster for lots of things, but take in account comparing strings for example, std::string has always the size to check it first, while with char[] you need to compare character by character.
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
If Else If In a Sql Server Function
You'll need to create local variables for those columns, assign them during the select and use them for your conditional tests.
declare @yes_ans int,
@no_ans int,
@na_ans int
SELECT @yes_ans = yes_ans, @no_ans = no_ans, @na_ans = na_ans
from dbo.qrc_maintally
where school_id = @SchoolId
If @yes_ans > @no_ans and @yes_ans > @na_ans
begin
Set @Final = 'Yes'
end
-- etc.
Selecting multiple items in ListView
To "update" the Toast message after unchecking some items, just put this line inside the for loop:
if (sp.valueAt(i))
so it results:
for(int i=0;i<sp.size();i++)
{
if (sp.valueAt(i))
str+=names[sp.keyAt(i)]+",";
}
How to get my Android device Internal Download Folder path
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4
Just ran into this problem. I don't know if it's the same thing that hit your code, but for me the root cause was because I forgot to put name=
on the last argument of the url
(or path
in Django 2.0+) function call.
For instance, the following functions throw the error from the question:
url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), 'foo')
path('foo/{slug:bar}/', views.FooBar, 'foo')
But these actually work:
url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), name='foo')
path('foo/{slug:bar}/', views.FooBar, name='foo')
The reason why the traceback is unhelpful is because internally, Django wants to parse the given positional argument as the keyword argument kwargs
, and since a string is an iterable, an atypical code path begins to unfold. Always use name=
on your urls!
Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()
add async in main()
and await before
follow my code
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
var fsconnect = FirebaseFirestore.instance;
myget() async {
var d = await fsconnect.collection("students").get();
// print(d.docs[0].data());
for (var i in d.docs) {
print(i.data());
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Firebase Firestore App'),
),
body: Column(
children: <Widget>[
RaisedButton(
child: Text('send data'),
onPressed: () {
fsconnect.collection("students").add({
'name': 'sarah',
'title': 'xyz',
'email': '[email protected]',
});
print("send ..");
},
),
RaisedButton(
child: Text('get data'),
onPressed: () {
myget();
print("get data ...");
},
)
],
),
));
}
}
Comparison between Corona, Phonegap, Titanium
You should learn objective c and program native apps. Do not rely on these things you think will make life easier. Apple has made sure the easiest way is using their native tools and language. For your 100 lines of javascript I can do the same in 3 lines of code or no code at all depending on the element. Watch some tutorials - if you understand javascript then objective c is not hard. Workarounds are miserable and apple can pull the plug on you anytime they want.
How to display an activity indicator with text on iOS 8 with Swift?
This code work in SWIFT 2.0.
Must Declare a variable for initialize UIActivityIndicatorView
let actInd: UIActivityIndicatorView = UIActivityIndicatorView()
After initialize put this code in your controller.
actInd.center = ImageView.center
actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
view.addSubview(actInd)
actInd.startAnimating()
after your download process complete then hide a animation.
self.actInd.stopAnimating()
".addEventListener is not a function" why does this error occur?
Try this one:
var comment = document.querySelector("button");
function showComment() {
var place = document.querySelector('#textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
}
comment.addEventListener('click', showComment, false);
Use querySelector
instead of className
Query comparing dates in SQL
If You are comparing only with the date vale, then converting it to date (not datetime) will work
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= convert(date,'2013-04-12',102)
This conversion is also applicable during using GetDate() function
How can I find and run the keytool
keytool
comes with the JDK. If you are using cygwin then this is probably on your path already. Otherwise, you might dig around in your JDK's bin folder.
You'll probably need to use cygwin anyways for the shell pipes (|
) to work.
Validating URL in Java
There is a way to perform URL validation in strict accordance to standards in Java without resorting to third-party libraries:
boolean isValidURL(String url) {
try {
new URI(url).parseServerAuthority();
return true;
} catch (URISyntaxException e) {
return false;
}
}
The constructor of URI
checks that url
is a valid URI, and the call to parseServerAuthority
ensures that it is a URL (absolute or relative) and not a URN.
REACT - toggle class onclick
Just wanted to add my approach. Using hooks and context provider.
Nav.js
function NavBar() {
const filterDispatch = useDispatchFilter()
const {filter} = useStateFilter()
const activeRef = useRef(null)
const completeRef = useRef(null)
const cancelRef = useRef(null)
useEffect(() => {
let activeClass = '';
let completeClass = '';
let cancelClass = '';
if(filter === ACTIVE_ORDERS){
activeClass='is-active'
}else if ( filter === COMPLETE_ORDERS ){
completeClass='is-active'
}else if(filter === CANCEL_ORDERS ) {
cancelClass='is-active'
}
activeRef.current.className = activeClass
completeRef.current.className = completeClass
cancelRef.current.className = cancelClass
}, [filter])
return (
<div className="tabs is-centered">
<ul>
<li ref={activeRef}>
<button
className="button-base"
onClick={() => filterDispatch({type: 'FILTER_ACTIVE'})}
>
Active
</button>
</li>
<li ref={completeRef}>
<button
className="button-base"
onClick={() => filterDispatch({type: 'FILTER_COMPLETE'})}
>
Complete
</button>
</li>
<li ref={cancelRef}>
<button
className={'button-base'}
onClick={() => filterDispatch({type: 'FILTER_CANCEL'})}
>
Cancel
</button>
</li>
</ul>
</div>
)
}
export default NavBar
filterContext.js
export const ACTIVE_ORDERS = [
"pending",
"assigned",
"pickup",
"warning",
"arrived",
]
export const COMPLETE_ORDERS = ["complete"]
export const CANCEL_ORDERS = ["cancel"]
const FilterStateContext = createContext()
const FilterDispatchContext = createContext()
export const FilterProvider = ({ children }) => {
const [state, dispatch] = useReducer(FilterReducer, { filter: ACTIVE_ORDERS })
return (
<FilterStateContext.Provider value={state}>
<FilterDispatchContext.Provider value={dispatch}>
{children}
</FilterDispatchContext.Provider>
</FilterStateContext.Provider>
)
}
export const useStateFilter = () => {
const context = useContext(FilterStateContext)
if (context === undefined) {
throw new Error("place useStateMap within FilterProvider")
}
return context
}
export const useDispatchFilter = () => {
const context = useContext(FilterDispatchContext)
if (context === undefined) {
throw new Error("place useDispatchMap within FilterProvider")
}
return context
}
export const FilterReducer = (state, action) => {
switch (action.type) {
case "FILTER_ACTIVE":
return {
...state,
filter: ACTIVE_ORDERS,
}
case "FILTER_COMPLETE":
return {
...state,
filter: COMPLETE_ORDERS,
}
case "FILTER_CANCEL":
return {
...state,
filter: CANCEL_ORDERS,
}
}
return state
}
Works fast, and replaces redux.
How to let an ASMX file output JSON
Are you calling the web service from client script or on the server side?
You may find sending a content type header to the server will help, e.g.
'application/json; charset=utf-8'
On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.
How to parse XML to R data frame
You can try the code below:
# Load the packages required to read XML files.
library("XML")
library("methods")
# Convert the input xml file to a data frame.
xmldataframe <- xmlToDataFrame("input.xml")
print(xmldataframe)
Can I have H2 autocreate a schema in an in-memory database?
What Thomas has written is correct, in addition to that, if you want to initialize multiple schemas you can use the following. Note there is a \\;
separating the two create statements.
EmbeddedDatabase db = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.setName("testDb;DB_CLOSE_ON_EXIT=FALSE;MODE=Oracle;INIT=create " +
"schema if not exists " +
"schema_a\\;create schema if not exists schema_b;" +
"DB_CLOSE_DELAY=-1;")
.addScript("sql/provPlan/createTable.sql")
.addScript("sql/provPlan/insertData.sql")
.addScript("sql/provPlan/insertSpecRel.sql")
.build();
ref : http://www.h2database.com/html/features.html#execute_sql_on_connection
how to set "camera position" for 3d plots using python/matplotlib?
What would be handy would be to apply the Camera position to a new plot.
So I plot, then move the plot around with the mouse changing the distance. Then try to replicate the view including the distance on another plot.
I find that axx.ax.get_axes() gets me an object with the old .azim and .elev.
IN PYTHON...
axx=ax1.get_axes()
azm=axx.azim
ele=axx.elev
dst=axx.dist # ALWAYS GIVES 10
#dst=ax1.axes.dist # ALWAYS GIVES 10
#dst=ax1.dist # ALWAYS GIVES 10
Later 3d graph...
ax2.view_init(elev=ele, azim=azm) #Works!
ax2.dist=dst # works but always 10 from axx
EDIT 1...
OK, Camera position is the wrong way of thinking concerning the .dist value. It rides on top of everything as a kind of hackey scalar multiplier for the whole graph.
This works for the magnification/zoom of the view:
xlm=ax1.get_xlim3d() #These are two tupples
ylm=ax1.get_ylim3d() #we use them in the next
zlm=ax1.get_zlim3d() #graph to reproduce the magnification from mousing
axx=ax1.get_axes()
azm=axx.azim
ele=axx.elev
Later Graph...
ax2.view_init(elev=ele, azim=azm) #Reproduce view
ax2.set_xlim3d(xlm[0],xlm[1]) #Reproduce magnification
ax2.set_ylim3d(ylm[0],ylm[1]) #...
ax2.set_zlim3d(zlm[0],zlm[1]) #...
Google MAP API v3: Center & Zoom on displayed markers
I've also find this fix that zooms to fit all markers
LatLngList: an array of instances of latLng, for example:
// "map" is an instance of GMap3
var LatLngList = [
new google.maps.LatLng (52.537,-2.061),
new google.maps.LatLng (52.564,-2.017)
],
latlngbounds = new google.maps.LatLngBounds();
LatLngList.forEach(function(latLng){
latlngbounds.extend(latLng);
});
// or with ES6:
// for( var latLng of LatLngList)
// latlngbounds.extend(latLng);
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
How to run iPhone emulator WITHOUT starting Xcode?
In case you were trying to open multiple distinct simulators at once:
Open the Simulator app, not Xcode.
Then File >> Open Device >> Select iOS version >> select device.
The location of the 'open device' has changed in different Xcode versions so it may be at a different place
Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID
Create openssl.conf
file:
[req]
default_bits = 2048
default_keyfile = oats.key
encrypt_key = no
utf8 = yes
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = US
ST = Cary
L = Cary
O = BigCompany
CN = *.myserver.net
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = myserver.net
DNS.2 = *.myserver.net
Run this comand:
openssl req -x509 -sha256 -nodes -days 3650 -newkey rsa:2048 -keyout app.key -out app.crt -config openssl.conf
Output files app.crt
and app.key
work for me.
Deleting a SQL row ignoring all foreign keys and constraints
Do not under any circumstances disable the constraints. This is an extremely stupid practice. You cannot maintain data integrity if you do things like this. Data integrity is the first consideration of a database because without it, you have nothing.
The correct method is to delete from the child tables before trying to delete the parent record. You are probably timing out because you have set up cascading deltes which is another bad practice in a large database.
Searching multiple files for multiple words
If you are using Notepad++ editor
Goto ctrl + F choose tab 3 find in files and enter:
- Find What = text1*.*text2
- Filters : .
- Search mode = Regular Expression
- Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.
Query-string encoding of a Javascript Object
It seems that till now nobody mention another popular library qs. You can add it
$ yarn add qs
And then use it like that
import qs from 'qs'
const array = { a: { b: 'c' } }
const stringified = qs.stringify(array, { encode: false })
console.log(stringified) //-- outputs a[b]=c
Update just one gem with bundler
bundler update --source gem-name
will update the revision hash in Gemfile.lock which you can compare with the last commit hash of that git branch (master by default).
GIT
remote: [email protected]:organization/repo-name.git
revision: c810f4a29547b60ca8106b7a6b9a9532c392c954
can be found at github.com/organization/repo-name/commits/c810f4a2
(I used shorthand 8 character commit hash for the url)
Returning boolean if set is empty
If c
is a set then you can check whether it's empty by doing: return not c
.
If c
is empty then not c
will be True
.
Otherwise, if c
contains any elements not c
will be False
.
Delete commit on gitlab
Supose you have the following scenario:
* 1bd2200 (HEAD, master) another commit
* d258546 bad commit
* 0f1efa9 3rd commit
* bd8aa13 2nd commit
* 34c4f95 1st commit
Where you want to remove d258546 i.e. "bad commit".
You shall try an interactive rebase to remove it: git rebase -i 34c4f95
then your default editor will pop with something like this:
pick bd8aa13 2nd commit
pick 0f1efa9 3rd commit
pick d258546 bad commit
pick 1bd2200 another commit
# Rebase 34c4f95..1bd2200 onto 34c4f95
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
just remove the line with the commit you want to strip and save+exit the editor:
pick bd8aa13 2nd commit
pick 0f1efa9 3rd commit
pick 1bd2200 another commit
...
git will proceed to remove this commit from your history leaving something like this (mind the hash change in the commits descendant from the removed commit):
* 34fa994 (HEAD, master) another commit
* 0f1efa9 3rd commit
* bd8aa13 2nd commit
* 34c4f95 1st commit
Now, since I suppose that you already pushed the bad commit to gitlab, you'll need to repush your graph to the repository (but with the -f
option to prevent it from being rejected due to a non fastforwardeable history i.e. git push -f <your remote> <your branch>
)
Please be extra careful and make sure that none coworker is already using the history containing the "bad commit" in their branches.
Alternative option:
Instead of rewrite the history, you may simply create a new commit which negates the changes introduced by your bad commit, to do this just type git revert <your bad commit hash>
. This option is maybe not as clean, but is far more safe (in case you are not fully aware of what are you doing with an interactive rebase).
selenium get current url after loading a page
Like you said since the xpath for the next button is the same on every page it won't work. It's working as coded in that it does wait for the element to be displayed but since it's already displayed then the implicit wait doesn't apply because it doesn't need to wait at all. Why don't you use the fact that the url changes since from your code it appears to change when the next button is clicked. I do C# but I guess in Java it would be something like:
WebDriver driver = new FirefoxDriver();
String startURL = //a starting url;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);
foo(driver,startURL);
/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
String previousURL = driver.getCurrentUrl();
driver.findElement(By.xpath("//*[@id='someID']")).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
ExpectedCondition e = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return (d.getCurrentUrl() != previousURL);
}
};
wait.until(e);
currentURL = driver.getCurrentUrl();
System.out.println(currentURL);
}
What is the meaning of "__attribute__((packed, aligned(4))) "
The attribute packed
means that the compiler will not add padding between fields of the struct
. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.
aligned(4)
means that the struct should be aligned to an address that is divisible by 4.
How can we programmatically detect which iOS version is device running on?
Update
From iOS 8 we can use the new isOperatingSystemAtLeastVersion
method on NSProcessInfo
NSOperatingSystemVersion ios8_0_1 = (NSOperatingSystemVersion){8, 0, 1};
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:ios8_0_1]) {
// iOS 8.0.1 and above logic
} else {
// iOS 8.0.0 and below logic
}
Beware that this will crash on iOS 7, as the API didn't exist prior to iOS 8. If you're supporting iOS 7 and below, you can safely perform the check with
if ([NSProcessInfo instancesRespondToSelector:@selector(isOperatingSystemAtLeastVersion:)]) {
// conditionally check for any version >= iOS 8 using 'isOperatingSystemAtLeastVersion'
} else {
// we're on iOS 7 or below
}
Original answer iOS < 8
For the sake of completeness, here's an alternative approach proposed by Apple itself in the iOS 7 UI Transition Guide, which involves checking the Foundation Framework version.
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
// Load resources for iOS 6.1 or earlier
} else {
// Load resources for iOS 7 or later
}
Deleting an object in java?
You don't need to delete objects in java. When there is no reference to an object, it will be collected by the garbage collector automatically.
How to force remounting on React components?
What's probably happening is that React thinks that only one MyInput
(unemployment-duration
) is added between the renders. As such, the job-title
never gets replaced with the unemployment-reason
, which is also why the predefined values are swapped.
When React does the diff, it will determine which components are new and which are old based on their key
property. If no such key is provided in the code, it will generate its own.
The reason why the last code snippet you provide works is because React essentially needs to change the hierarchy of all elements under the parent div
and I believe that would trigger a re-render of all children (which is why it works). Had you added the span
to the bottom instead of the top, the hierarchy of the preceding elements wouldn't change, and those element's wouldn't re-render (and the problem would persist).
Here's what the official React documentation says:
The situation gets more complicated when the children are shuffled around (as in search results) or if new components are added onto the front of the list (as in streams). In these cases where the identity and state of each child must be maintained across render passes, you can uniquely identify each child by assigning it a key.
When React reconciles the keyed children, it will ensure that any child with key will be reordered (instead of clobbered) or destroyed (instead of reused).
You should be able to fix this by providing a unique key
element yourself to either the parent div
or to all MyInput
elements.
For example:
render(){
if (this.state.employed) {
return (
<div key="employed">
<MyInput ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div key="notEmployed">
<MyInput ref="unemployment-reason" name="unemployment-reason" />
<MyInput ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
OR
render(){
if (this.state.employed) {
return (
<div>
<MyInput key="title" ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div>
<MyInput key="reason" ref="unemployment-reason" name="unemployment-reason" />
<MyInput key="duration" ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
Now, when React does the diff, it will see that the divs
are different and will re-render it including all of its' children (1st example). In the 2nd example, the diff will be a success on job-title
and unemployment-reason
since they now have different keys.
You can of course use any keys you want, as long as they are unique.
Update August 2017
For a better insight into how keys work in React, I strongly recommend reading my answer to Understanding unique keys in React.js.
Update November 2017
This update should've been posted a while ago, but using string literals in ref
is now deprecated. For example ref="job-title"
should now instead be ref={(el) => this.jobTitleRef = el}
(for example). See my answer to Deprecation warning using this.refs for more info.
How to get the class of the clicked element?
I saw this question so I thought I might expand on it a little more. This is an expansion of the idea that @SteveFenton had. Instead of binding a click
event to each li
element, it would be more efficient to delegate the events from the ul
down.
For jQuery 1.7 and higher
$("ul.tabs").on('click', 'li', function(e) {
alert($(this).attr("class"));
});
Documentation: .on()
For jQuery 1.4.2 - 1.7
$("ul.tabs").delegate('li', 'click', function(e) {
alert($(this).attr("class"));
});
Documentation: .delegate()
As a last resort for jQuery 1.3 - 1.4
$("ul.tabs").children('li').live('click', function(e) {
alert($(this).attr("class"));
});
or
$("ul.tabs > li").live('click', function(e) {
alert($(this).attr("class"));
});
Documentation: .live()
Looping over elements in jQuery
This is the simplest way to loop through a form accessing only the form elements. Inside the each function you can check and build whatever you want. When building objects note that you will want to declare it outside of the each function.
EDIT
JSFIDDLE
The below will work
$('form[name=formName]').find('input, textarea, select').each(function() {
alert($(this).attr('name'));
});
How do you change the text in the Titlebar in Windows Forms?
If you want to update it later, once "this" no longer references it, I had some luck with assigning a variable to point to the main form.
static Form f0;
public OrdUpdate()
{
InitializeComponent();
f0=this;
}
// then later you can say
f0.Text="New text";
How do you create nested dict in Python?
A nested dict is a dictionary within a dictionary. A very simple thing.
>>> d = {}
>>> d['dict1'] = {}
>>> d['dict1']['innerkey'] = 'value'
>>> d
{'dict1': {'innerkey': 'value'}}
You can also use a defaultdict
from the collections
package to facilitate creating nested dictionaries.
>>> import collections
>>> d = collections.defaultdict(dict)
>>> d['dict1']['innerkey'] = 'value'
>>> d # currently a defaultdict type
defaultdict(<type 'dict'>, {'dict1': {'innerkey': 'value'}})
>>> dict(d) # but is exactly like a normal dictionary.
{'dict1': {'innerkey': 'value'}}
You can populate that however you want.
I would recommend in your code something like the following:
d = {} # can use defaultdict(dict) instead
for row in file_map:
# derive row key from something
# when using defaultdict, we can skip the next step creating a dictionary on row_key
d[row_key] = {}
for idx, col in enumerate(row):
d[row_key][idx] = col
According to your comment:
may be above code is confusing the question. My problem in nutshell: I
have 2 files a.csv b.csv, a.csv has 4 columns i j k l, b.csv also has
these columns. i is kind of key columns for these csvs'. j k l column
is empty in a.csv but populated in b.csv. I want to map values of j k
l columns using 'i` as key column from b.csv to a.csv file
My suggestion would be something like this (without using defaultdict):
a_file = "path/to/a.csv"
b_file = "path/to/b.csv"
# read from file a.csv
with open(a_file) as f:
# skip headers
f.next()
# get first colum as keys
keys = (line.split(',')[0] for line in f)
# create empty dictionary:
d = {}
# read from file b.csv
with open(b_file) as f:
# gather headers except first key header
headers = f.next().split(',')[1:]
# iterate lines
for line in f:
# gather the colums
cols = line.strip().split(',')
# check to make sure this key should be mapped.
if cols[0] not in keys:
continue
# add key to dict
d[cols[0]] = dict(
# inner keys are the header names, values are columns
(headers[idx], v) for idx, v in enumerate(cols[1:]))
Please note though, that for parsing csv files there is a csv module.
How Should I Set Default Python Version In Windows?
The Python installer installs Python Launcher for Windows. This program (py.exe
) is associated with the Python file extensions and looks for a "shebang" comment to specify the python version to run. This allows many versions of Python to co-exist and allows Python scripts to explicitly specify which version to use, if desired. If it is not specified, the default is to use the latest Python version for the current architecture (x86 or x64). This default can be customized through a py.ini
file or PY_PYTHON
environment variable. See the docs for more details.
Newer versions of Python update the launcher. The latest version has a py -0
option to list the installed Pythons and indicate the current default.
Here's how to check if the launcher is registered correctly from the console:
C:\>assoc .py
.py=Python.File
C:\>ftype Python.File
Python.File="C:\Windows\py.exe" "%1" %*
Above, .py
files are associated with the Python.File
type. The command line for Python.File
is the Python Launcher, which is installed in the Windows directory since it is always in the PATH.
For the association to work, run scripts from the command line with script.py
, not "python script.py", otherwise python
will be run instead of py
. If fact it's best to remove Python directories from the PATH, so "python" won't run anything and enforce using py
.
py.exe
can also be run with switches to force a Python version:
py -3 script.py # select latest Python 3.X version to be used.
py -3.6 script.py # select version 3.6 specifically.
py -3.9-32 script.py # select version 3.9 32-bit specifically.
py -0 # list installed Python versions (latest PyLauncher).
Additionally, add .py;.pyw;.pyc;.pyo
to the PATHEXT
environment variable and then the command line can just be script
with no extension.
saving a file (from stream) to disk using c#
If you are using .NET 4.0 or newer you can use this method:
public static void CopyStream(Stream input, Stream output)
{
input.CopyTo(output);
}
If not, use this one:
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
And here how to use it:
using (FileStream output = File.OpenWrite(path))
{
CopyStream(input, output);
}