On a Mac, you need to use this command:
STATIC_DEPS=true sudo pip install lxml
Remember to include System.Diagnostics
ProcessStartInfo startInfo = new ProcessStartInfo("myfile.exe"); // exe file
startInfo.WorkingDirectory = @"C:\..\MyFile\bin\Debug\netcoreapp3.1\"; // exe folder
//here you add your arguments
startInfo.ArgumentList.Add("arg0"); // First argument
startInfo.ArgumentList.Add("arg2"); // second argument
startInfo.ArgumentList.Add("arg3"); // third argument
Process.Start(startInfo);
Open preferences windows (Command key + "," on Mac):
1.Tools
2.Python Integrated Tools
3.Default test runner
If you already have the xml, and comes more than one attribute, you can handle it as follows:
String output = "<ciudads><ciudad><idCiudad>1</idCiudad>
<nomCiudad>BOGOTA</nomCiudad></ciudad><ciudad><idCiudad>6</idCiudad>
<nomCiudad>Pereira</nomCiudad></ciudads>";
DocumentBuilder db = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));
Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
.getElementsByTagName("ciudad");
for (int i = 0; i < nodes.getLength(); i++) {
Ciudad ciudad = new Ciudad();
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("idCiudad");
Element element2 = (Element) name.item(0);
ciudad.setIdCiudad(Integer
.valueOf(getCharacterDataFromElement(element2)));
NodeList title = element.getElementsByTagName("nomCiudad");
element2 = (Element) title.item(0);
ciudad.setNombre(getCharacterDataFromElement(element2));
ciudades.getPartnerAccount().add(ciudad);
}
}
for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}
the method getCharacterDataFromElement is
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
edit2, I figured out a new solution without the need of setting index
newdf=pd.concat([df1,df2]).drop_duplicates(keep=False)
Okay i found the answer of highest vote already contain what I have figured out. Yes, we can only use this code on condition that there are no duplicates in each two dfs.
I have a tricky method. First we set ’Name’ as the index of two dataframe given by the question. Since we have same ’Name’ in two dfs, we can just drop the ’smaller’ df’s index from the ‘bigger’ df. Here is the code.
df1.set_index('Name',inplace=True)
df2.set_index('Name',inplace=True)
newdf=df1.drop(df2.index)
Have a look at json_encode
(http://php.net/manual/en/function.json-encode.php). It is available as of PHP 5.2. Use the parameter dataType: 'json'
to have it parsed for you. You'll have the Object as the first argument in success then. For further information have a look at the jQuery-documentation: http://api.jquery.com/jQuery.ajax/
A backslash needs to be escaped with another backslash.
print('\\')
Here's what's working for me
on windows
1) Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net (cause browser have issues with 'localhost' (for cross origin scripting)
Windows Vista and Windows 7 Vista and Windows 7 use User Account Control (UAC) so Notepad must be run as Administrator.
Click Start -> All Programs -> Accessories
Right click Notepad and select Run as administrator
Click Continue on the "Windows needs your permission" UAC window.
When Notepad opens Click File -> Open
In the filename field type C:\Windows\System32\Drivers\etc\hosts
Click Open
Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net
Save
Close and restart browsers
On Mac or Linux:
su
permission127.0.0.1 localdev.YOURSITE.net
When developing you use localdev.YOURSITE.net instead of localhost so if you are using run/debug configurations in your ide be sure to update it.
Use ".YOURSITE.net" as cookiedomain (with a dot in the beginning) when creating the cookiem then it should work with all subdomains.
2) create the certificate using that localdev.url
TIP: If you have issues generating certificates on windows, use a VirtualBox or Vmware machine instead.
3) import the certificate as outlined on http://www.charlesproxy.com/documentation/using-charles/ssl-certificates/
The full command would be something like below, notice the quotes
icacls "c:\inetpub\wwwroot\tmp" /grant "IIS AppPool\DefaultAppPool:F"
I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:
My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.
private void startCreation(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
Uri startDir = Uri.fromFile(new File("/sdcard"));
intent.setDataAndType(startDir,
"vnd.android.cursor.dir/lysesoft.andexplorer.file");
intent.putExtra("browser_filter_extension_whitelist", "*.csv");
intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
intent.putExtra("browser_title_background_color",
getText(R.string.browser_title_background_color));
intent.putExtra("browser_title_foreground_color",
getText(R.string.browser_title_foreground_color));
intent.putExtra("browser_list_background_color",
getText(R.string.browser_list_background_color));
intent.putExtra("browser_list_fontscale", "120%");
intent.putExtra("browser_list_layout", "2");
try{
ApplicationInfo info = getPackageManager()
.getApplicationInfo("lysesoft.andexplorer", 0 );
startActivityForResult(intent, PICK_REQUEST_CODE);
} catch( PackageManager.NameNotFoundException e ){
showInstallResultMessage(R.string.error_install_andexplorer);
} catch (Exception e) {
Log.w(TAG, e.getMessage());
}
}
This methos is just pick up a dialog and if user wants install the external application from market
private void showInstallResultMessage(int msg_id) {
AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setMessage(getText(msg_id));
dialog.setButton(getText(R.string.button_ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.setButton2(getText(R.string.button_install),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
startActivity(intent);
finish();
}
});
dialog.show();
}
you can do this by
date("F j, Y", time() - 60 * 60 * 24);
or by
date("F j, Y", strtotime("yesterday"));
This error can occur if you are using a software update server which doesn't host the required package.
You can check this by running
defaults read /Library/Preferences/com.apple.SoftwareUpdate
and seeing if you have an entry called CatalogURL or AppleCatalogURL
You can point back at the Apple software update server by either removing this entry or using the command
sudo softwareupdate --clear-catalog
And then run the command line tools install again.
My experience with MATMUL and DOT
I was constantly getting "ValueError: Shape of passed values is (200, 1), indices imply (200, 3)" when trying to use MATMUL. I wanted a quick workaround and found DOT to deliver the same functionality. I don't get any error using DOT. I get the correct answer
with MATMUL
X.shape
>>>(200, 3)
type(X)
>>>pandas.core.frame.DataFrame
w
>>>array([0.37454012, 0.95071431, 0.73199394])
YY = np.matmul(X,w)
>>> ValueError: Shape of passed values is (200, 1), indices imply (200, 3)"
with DOT
YY = np.dot(X,w)
# no error message
YY
>>>array([ 2.59206877, 1.06842193, 2.18533396, 2.11366346, 0.28505879, …
YY.shape
>>> (200, )
In this
var div = '<div>top div</div>';
"div" is not a DOM object,is just a string,and string has no string.appendChild.
Here are some references that may help you on appendChild method:
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>
results.show(20,false)
did the trick for me in Scala.
Edit the file xampp/mysql/bin/my.ini
Add
skip-grant-tables
under [mysqld]
Portland group have a commercial product called CUDA x86, it is hybrid compiler which creates CUDA C/ C++ code which can either run on GPU or use SIMD on CPU, this is done fully automated without any intervention for the developer. Hope this helps.
You can use date
to get time and date of a day:
[pengyu@GLaDOS ~]$date
Tue Aug 27 15:01:27 CST 2013
Also hwclock
would do:
[pengyu@GLaDOS ~]$hwclock
Tue 27 Aug 2013 03:01:29 PM CST -0.516080 seconds
For customized output, you can either redirect the output of date
to something like awk
, or write your own program to do that.
Remember to put your own executable scripts/binary into your PATH
(e.g. /usr/bin) to make it invokable anywhere.
In jQuery e
short for event
, the current event object. It's usually passed as a parameter for the event function to be fired.
Demo: jQuery Events
In the demo I used e
$("img").on("click dblclick mouseover mouseout",function(e){
$("h1").html("Event: " + e.type);
});
I may as well have used event
$("img").on("click dblclick mouseover mouseout",function(event){
$("h1").html("Event: " + event.type);
});
Same thing!
Programmers are lazy we use a lot of shorthand, partly it decreases our work, partly is helps with readability. Understanding that will help you understand the mentality of writing code.
Use apt to uninstall and remove all MySQL packages:
$ sudo apt-get remove --purge mysql-server mysql-client mysql-common -y
$ sudo apt-get autoremove -y
$ sudo apt-get autoclean
Remove the MySQL folder:
$ rm -rf /etc/mysql
Delete all MySQL files on your server:
$ sudo find / -iname 'mysql*' -exec rm -rf {} \;
Your system should no longer contain default MySQL related files.
$("#myform input:checkbox").change(function() {
$("#myform input:checkbox").attr("checked", false);
$(this).attr("checked", true);
});
This should work for any number of checkboxes in the form. If you have others that aren't part of the group, set up the selectors the applicable inputs.
Pragma directives specify operating system or machine specific (x86 or x64 etc) compiler options. There are several options available. Details can be found in https://msdn.microsoft.com/en-us/library/d9x1s805.aspx
#pragma comment( comment-type [,"commentstring"] )
has this format.
Refer https://msdn.microsoft.com/en-us/library/7f0aews7.aspx for details about different comment-type.
#pragma comment(lib, "kernel32")
#pragma comment(lib, "user32")
The above lines of code includes the library names (or path) that need to be searched by the linker. These details are included as part of the library-search record in the object file.
So, in this case kernel.lib
and user32.lib
are searched by the linker and included in the final executable.
best to use crypt for password storing in DB
example code :
$crypted_pass = crypt($password);
//$pass_from_login is the user entered password
//$crypted_pass is the encryption
if(crypt($pass_from_login,$crypted_pass)) == $crypted_pass)
{
echo("hello user!")
}
documentation :
After installing Free BitDefender AntiVirus the services related to the AntiVirus used about 80 MB of my computer's Memory. I also noticed that after installing BitDefender the service related to windows Presentation Font Cache was also installed: "WPFFontCache_v0300.exe". I disabled the service from stating automatically and now BitDefender Free AntiVirus use only 15-20 MB (!!!) of my computer's Memory! As far as I concern, this service affected negatively the memory usage of my PC inother services. I recommend you to disable it.
The full TypeScript code
public getClassName() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec(this["constructor"].toString());
return (results && results.length > 1) ? results[1] : "";
}
You could try this(this uses a constructor, but I'm sure you can change it around a bit):
function Obj() {
this.subObj = {
// code
}
this.subObj.parent = this;
}
Easiest route is probably upgrading or re-installing the Java Runtime Environment (JRE).
Or this:
C:\Program Files\Java\j2re1.4.2_04\bin\javaw.exe" -jar "%1" %
(Note: the part starting with 'javaw' must be exactly like that; the other part of the path name can vary depending on which version of Java you're using) then press the OK buttons until all the dialogs are closed.Which was stolen from here: http://windowstipoftheday.blogspot.com/2005/10/setting-jar-file-association.html
simply use this in your imagebutton layout
android:background="@null"
using
android:background="@android:color/transparent
or
btn.setBackgroundColor(Color.TRANSPARENT);
doesn't give perfect transparency
I just ran into the same issue for Ubuntu 13.04. These commands removed Postgres 9.1:
sudo apt-get purge postgresql
sudo apt-get autoremove postgresql
It occurs to me that perhaps only the second command is necessary, but from there I was able to install Postgres 9.2 (sudo apt-get install postgresql-9.2).
FileUtils
is class from apache org.apache.commons.io
package, you need to download org.apache.commons.io.jar
and then configure that jar
file in your class path.
Consider refactoring the code from ChildService.save() method to different method and test that new method instead of testing ChildService.save(), this way you will avoid unnecessary call to super method.
Example:
class BaseService {
public void save() {...}
}
public Childservice extends BaseService {
public void save(){
newMethod();
super.save();
}
public void newMethod(){
//some codes
}
}
I have experimented many of the backslash escape characters. \n
which is a new line feed can be put anywhere to bring the effect. One important thing to remember while using this character is that the operating system of the machine we are using might affect the output. As an example, I have printed a bunch of escape character and displayed the result as follow to proof that the OS will affect the output.
Code:
#include <stdio.h>
int main(void){
printf("Hello World!");
printf("Goodbye \a");
printf("Hi \b");
printf("Yo\f");
printf("What? \t");
printf("pewpew");
return 0;
}
In my case it was an issue of the PHP version.
The .phar file I was using was not compatible with PHP 5.3.9. Switching interpreter to PHP 7 did fix it.
Please take a look here:
1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.
2) Step-by-step tutorial how to use serial ports on windows
3) You can use this literally on MinGW
Here's some very, very simple code (without any error handling or settings):
#include <windows.h>
/* ... */
// Open serial port
HANDLE serialHandle;
serialHandle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);
GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);
// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;
SetCommTimeouts(serialHandle, &timeout);
Now you can use WriteFile()
/ ReadFile()
to write / read bytes.
Don't forget to close your connection:
CloseHandle(serialHandle);
The answer depends on what implementation of python is being used. If you are using lets say CPython (The Standard implementation of python) or Jython (Targeted for integration with java programming language)it is first translated into bytecode, and depending on the implementation of python you are using, this bycode is directed to the corresponding virtual machine for interpretation. PVM (Python Virtual Machine) for CPython and JVM (Java Virtual Machine) for Jython.
But lets say you are using PyPy which is another standard CPython implementation. It would use a Just-In-Time Compiler.
If you don't want to copy the whole tree (with subdirs etc), use or glob.glob("path/to/dir/*.*")
to get a list of all the filenames, loop over the list and use shutil.copy
to copy each file.
for filename in glob.glob(os.path.join(source_dir, '*.*')):
shutil.copy(filename, dest_dir)
For MVC5, in case you are building an application from scratch. You need to add a web.config file to the Views folder and paste the following code in it.
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
</configuration>
Note that for MVC 3 you will have to change version to 3.0.0.0 at
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
You may have to close and open the *.cshtml page again to see the changes.
Going back to the Kalman Filters ... I found a C implementation for a Kalman filter for GPS data here: http://github.com/lacker/ikalman I haven't tried it out yet, but it seems promising.
Here is from pandas docs on advanced indexing:
The section will explain exactly what you need! Turns out df.loc
(as .ix has been deprecated -- as many have pointed out below) can be used for cool slicing/dicing of a dataframe. And. It can also be used to set things.
df.loc[selection criteria, columns I want] = value
So Bren's answer is saying 'find me all the places where df.A == 0
, select column B
and set it to np.nan
'
You can use String.Format:
DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
// I got this result: "02/23/2015 16:42:38.234"
Great thing about linux, you're still able to download the source and on most systems have all of the tools to compile the version yourself.
In order to get a python cli from xterm just by typing python
, the python bin directory must be in your system path variable (Red Hat example, Suse example)
Put all the ids into a variable called $ids and separate them with a ",":
$ids = "1,2,3,4,5,6";
Pass them like so:
$url = "?ids={$ids}";
Process them:
$ids = explode(",", $_GET['ids']);
You could use get_defined_vars() to find the name of a variable that has the same value as the one you're trying to find the name of. Obviously this will not always work, since different variables often have the same values, but it's the only way I can think of to do this.
Edit: get_defined_vars() doesn't seem to be working correctly, it returns 'var' because $var is used in the function itself. $GLOBALS seems to work so I've changed it to that.
function print_var_name($var) {
foreach($GLOBALS as $var_name => $value) {
if ($value === $var) {
return $var_name;
}
}
return false;
}
Edit: to be clear, there is no good way to do this in PHP, which is probably because you shouldn't have to do it. There are probably better ways of doing what you're trying to do.
In newer version of git (2.23+) you can use:
git switch -C master origin/master
-C
is same as --force-create
. Related Reference Docs
I'm not 100% sure this is the only difference, but it is the main difference. It is also recommended to have bi-directional associations by the Hibernate docs:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html
Specifically:
Prefer bidirectional associations: Unidirectional associations are more difficult to query. In a large application, almost all associations must be navigable in both directions in queries.
I personally have a slight problem with this blanket recommendation -- it seems to me there are cases where a child doesn't have any practical reason to know about its parent (e.g., why does an order item need to know about the order it is associated with?), but I do see value in it a reasonable portion of the time as well. And since the bi-directionality doesn't really hurt anything, I don't find it too objectionable to adhere to.
I have the same question but cannot ask it because it would be a duplicate.
The accepted answer, using exit, does not work when the script is a bit more complicated. If you use a background process to check for the condition, exit only exits that process, as it runs in a sub-shell. To kill the script, you have to explicitly kill it (at least that is the only way I know).
Here is a little script on how to do it:
#!/bin/bash
boom() {
while true; do sleep 1.2; echo boom; done
}
f() {
echo Hello
N=0
while
((N++ <10))
do
sleep 1
echo $N
# ((N > 5)) && exit 4 # does not work
((N > 5)) && { kill -9 $$; exit 5; } # works
done
}
boom &
f &
while true; do sleep 0.5; echo beep; done
This is a better answer but still incomplete a I really don't know how to get rid of the boom part.
Injection already existed in Java EE 5 with the @Resource, @PersistentUnit or @EJB annotations, for example. But it was limited to certain resources (datasource, EJB . . .) and into certain components (Servlets, EJBs, JSF backing bean . . .). With CDI you can inject nearly anything anywhere thanks to the @Inject annotation.
TylerH made a really good answer, I just had to give that last button a visual update.
.btn {
border-radius: 5px;
padding: 10px 30px;
box-shadow: 1px 1px 1px #000;
background-image: linear-gradient(to bottom, #eee, #ddd);
}
.btn:hover {
background-image: linear-gradient(to top, #adf, #8bf);
}
.btn:active {
margin: 1px 1px 0;
box-shadow: -1px -1px 1px #000;
}
#btnControl {
display: block;
visibility: hidden;
}
_x000D_
<input type="checkbox" id="btnControl"/>
<label class="btn" for="btnControl">Click me!</label>
_x000D_
You can append this line at the end of .bashrc file-
export PATH=$PATH:"/opt/Android/Sdk/platform-tools/"
here /opt/Android/Sdk/platform-tools/ is installation directory of Sdk. .bashrc file is located in home folder
vi ~/.bashrc
or if you have sublime installed
subl ~/.bashrc
This is what worked for me: - I hit the same issue: my service was stuck in 'marked for deletion'. - I opened services.msc My service did show up as running, although it was already uninstalled. - I clicked Stop Received an error message, saying the service is not in a state to receive control messages. Nevertheless, the service was stopped. - Closed services.msc. - Reopened services.msc. - The service was gone (no longer showing in the list of services).
(The environment was Windows 7.)
/**
* get tomorrow's date in the format requested, default to Y-m-d for MySQL (e.g. 2013-01-04)
*
* @param string
*
* @return string
*/
public static function getTomorrowsDate($format = 'Y-m-d')
{
$date = new DateTime();
$date->add(DateInterval::createFromDateString('tomorrow'));
return $date->format($format);
}
You have more static resources that the cache has room for. You can do one of the following:
For more details see the documentation for these configuration options.
There aren't any selector hacks for IE8. The best resource for this issue is http://browserhacks.com/#ie
If you want to target specific IE8 you should do comment in html
<!--[if IE 8]> Internet Explorer 8 <![endif]-->
or you could use attribute hacks like:
/* IE6, IE7, IE8, but also IE9 in some cases :( */
#diecinueve { color: blue\9; }
/* IE7, IE8 */
#veinte { color/*\**/: blue\9; }
/* IE8, IE9 */
#anotherone {color: blue\0/;} /* must go at the END of all rules */
For more info on this one check: http://www.paulirish.com/2009/browser-specific-css-hacks/
There are 3 different ways you may wish to set this up:
Thrower
inside of Catcher
Catcher
inside of Thrower
Thrower
and Catcher
inside of another class in this example Test
THE WORKING GITHUB EXAMPLE I AM CITING Defaults to Option 3, to try the others simply uncomment the "Optional
" code block of the class you want to be main, and set that class as the ${Main-Class}
variable in the build.xml
file:
4 Things needed on throwing side code:
import java.util.*;//import of java.util.event
//Declaration of the event's interface type, OR import of the interface,
//OR declared somewhere else in the package
interface ThrowListener {
public void Catch();
}
/*_____________________________________________________________*/class Thrower {
//list of catchers & corresponding function to add/remove them in the list
List<ThrowListener> listeners = new ArrayList<ThrowListener>();
public void addThrowListener(ThrowListener toAdd){ listeners.add(toAdd); }
//Set of functions that Throw Events.
public void Throw(){ for (ThrowListener hl : listeners) hl.Catch();
System.out.println("Something thrown");
}
////Optional: 2 things to send events to a class that is a member of the current class
. . . go to github link to see this code . . .
}
2 Things needed in a class file to receive events from a class
/*_______________________________________________________________*/class Catcher
implements ThrowListener {//implement added to class
//Set of @Override functions that Catch Events
@Override public void Catch() {
System.out.println("I caught something!!");
}
////Optional: 2 things to receive events from a class that is a member of the current class
. . . go to github link to see this code . . .
}
Here is a working example: http://jsfiddle.net/rVBzt/ (using jQuery)
<img id="tiger" src="https://twimg0-a.akamaihd.net/profile_images/2642324404/46d743534606515238a9a12cfb4b264a.jpeg">
<a id="toggle">click to toggle</a>
img {display: none;}
a {cursor: pointer; color: blue;}
$('#toggle').click(function() {
$('#tiger').toggle();
});
Use the Tortoise SVN copy functionality to revert commited changes:
Hope that helps
It is possible to use super to call the method from mother class, but this would mean you probably have a design problem.
Maybe B.alphaMethod1()
shouldn't override A's method and be called B.betaMethod1()
.
If it depends on the situation, you can put some code logic like :
public void alphaMethod1(){
if (something) {
super.alphaMethod1();
return;
}
// Rest of the code for other situations
}
Like this it will only call A's method when needed and will remain invisible for the class user.
The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.
The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.
The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.
Edit: Also worth a look - kashif's comment about json-streamer
and Henrik Heino's comment about bigjson
.
Using Hooks (React 16.8.0+
)
Create a useWindowDimensions
hook.
import { useState, useEffect } from 'react';
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height
};
}
export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowDimensions;
}
And after that you'll be able to use it in your components like this
const Component = () => {
const { height, width } = useWindowDimensions();
return (
<div>
width: {width} ~ height: {height}
</div>
);
}
Original answer
It's the same in React, you can use window.innerHeight
to get the current viewport's height.
As you can see here
It's easy if you are somewhat constrained.
If you have one thread, you just use uniqueID++; Be sure to store the current uniqueID when you exit.
If you have multiple threads, a common synchronized generateUniqueID method works (Implemented the same as above).
The problem is when you have many CPUs--either in a cluster or some distributed setup like a peer-to-peer game.
In that case, you can generally combine two parts to form a single number. For instance, each process that generates a unique ID can have it's own 2-byte ID number assigned and then combine it with a uniqueID++. Something like:
return (myID << 16) & uniqueID++
It can be tricky distributing the "myID" portion, but there are some ways. You can just grab one out of a centralized database, request a unique ID from a centralized server, ...
If you had a Long instead of an Int, one of the common tricks is to take the device id (UUID) of ETH0, that's guaranteed to be unique to a server--then just add on a serial number.
give on .view-type
class float:left;
or delete the float:right;
of .view-name
edit: Wrap your div <div class="view-row">
with another div for example <div class="table">
and set the following css :
.table {
display:table;
width:100%;}
You have to use the table structure for correct results.
There are a couple ways to do this.
First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:
E:\> openssl x509 -pubkey -noout -in cert.pem > pubkey.pem
If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.
openssl> x509 -pubkey -noout -in cert.pem
Output will look something like this:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-----
your_command_string="..."
output=$(eval "$your_command_string")
echo "$output"
Number of .parent a
elements that have an id
attribute:
$('.parent a[id]').length
You can run using the following command. Here I want to run using spring profile local
:
spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=local"
I.e. for Visual Studio 2013 I would reference this assembly:
Microsoft.VisualStudio.Shell.14.0.dll
You can find it i.e. here:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\BugAid Software\BugAid\1.0
and don't forget to implement:
using Microsoft.VisualStudio;
Not particularly easily- if you've lost the pointer to the tip of a branch, it's rather like finding a needle in a haystack. You can find all the commits that don't appear to be referenced any more- git fsck --unreachable
will do this for you- but that will include commits that you threw away after a git commit --amend
, old commits on branches that you rebased etc etc. So seeing all these commits at once is quite likely far too much information to wade through.
So the flippant answer is, don't lose track of things you're interested in. More seriously, the reflogs will hold references to all the commits you've used for the last 60 days or so by default. More importantly, they will give some context about what those commits are.
The hex values are on the mainpage of http://glyphicons.com/ in the tooltips of the specific icon.
Use setTimeout(drawAll, 20)
instead. That only executes the function once.
To collaborate with the question and show an example of replacing it with an empty Container()
.
Here's the example below:
import "package:flutter/material.dart";
void main() {
runApp(new ControlleApp());
}
class ControlleApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "My App",
home: new HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<HomePage> {
bool visibilityTag = false;
bool visibilityObs = false;
void _changed(bool visibility, String field) {
setState(() {
if (field == "tag"){
visibilityTag = visibility;
}
if (field == "obs"){
visibilityObs = visibility;
}
});
}
@override
Widget build(BuildContext context){
return new Scaffold(
appBar: new AppBar(backgroundColor: new Color(0xFF26C6DA)),
body: new ListView(
children: <Widget>[
new Container(
margin: new EdgeInsets.all(20.0),
child: new FlutterLogo(size: 100.0, colors: Colors.blue),
),
new Container(
margin: new EdgeInsets.only(left: 16.0, right: 16.0),
child: new Column(
children: <Widget>[
visibilityObs ? new Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
new Expanded(
flex: 11,
child: new TextField(
maxLines: 1,
style: Theme.of(context).textTheme.title,
decoration: new InputDecoration(
labelText: "Observation",
isDense: true
),
),
),
new Expanded(
flex: 1,
child: new IconButton(
color: Colors.grey[400],
icon: const Icon(Icons.cancel, size: 22.0,),
onPressed: () {
_changed(false, "obs");
},
),
),
],
) : new Container(),
visibilityTag ? new Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
new Expanded(
flex: 11,
child: new TextField(
maxLines: 1,
style: Theme.of(context).textTheme.title,
decoration: new InputDecoration(
labelText: "Tags",
isDense: true
),
),
),
new Expanded(
flex: 1,
child: new IconButton(
color: Colors.grey[400],
icon: const Icon(Icons.cancel, size: 22.0,),
onPressed: () {
_changed(false, "tag");
},
),
),
],
) : new Container(),
],
)
),
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new InkWell(
onTap: () {
visibilityObs ? null : _changed(true, "obs");
},
child: new Container(
margin: new EdgeInsets.only(top: 16.0),
child: new Column(
children: <Widget>[
new Icon(Icons.comment, color: visibilityObs ? Colors.grey[400] : Colors.grey[600]),
new Container(
margin: const EdgeInsets.only(top: 8.0),
child: new Text(
"Observation",
style: new TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.w400,
color: visibilityObs ? Colors.grey[400] : Colors.grey[600],
),
),
),
],
),
)
),
new SizedBox(width: 24.0),
new InkWell(
onTap: () {
visibilityTag ? null : _changed(true, "tag");
},
child: new Container(
margin: new EdgeInsets.only(top: 16.0),
child: new Column(
children: <Widget>[
new Icon(Icons.local_offer, color: visibilityTag ? Colors.grey[400] : Colors.grey[600]),
new Container(
margin: const EdgeInsets.only(top: 8.0),
child: new Text(
"Tags",
style: new TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.w400,
color: visibilityTag ? Colors.grey[400] : Colors.grey[600],
),
),
),
],
),
)
),
],
)
],
)
);
}
}
You can redirect stdout to /dev/null.
yum install nano > /dev/null
Or you can redirect both stdout and stderr,
yum install nano &> /dev/null
.
But if the program has a quiet option, that's even better.
Saudate, I ran across this looking for a different problem. You most definitely can use the Sql Server Import wizard to import data into a new table. Of course, you do not wish to leave that table in the database, so my suggesting is that you import into a new table, then script the data in query manager to insert into the existing table. You can add a line to drop the temp table created by the import wizard as the last step upon successful completion of the script.
I believe your original issue is in fact related to Sql Server 64 bit and is due to your having a 32 bit Excel and these drivers don't play well together. I did run into a very similar issue when first using 64 bit excel.
$_SERVER['HTTP_REFERER']
will give you incomplete url.
If you want http://bawse.3owl.com/jayz__magna_carta_holy_grail.php
, $_SERVER['HTTP_REFERER']
will give you http://bawse.3owl.com/
only.
try this approach if you know your object client name ( it is not important that it is Button or TextBox )
$('#ButtonName').removeAttr('onclick');
$('#ButtonName').attr('onClick', 'FunctionName(this);');
try this ones if you want add onClick event to a server object with JQuery
$('#' + '<%= ButtonName.ClientID %>').removeAttr('onclick');
$('#' + '<%= ButtonName.ClientID %>').attr('onClick', 'FunctionName(this);');
Here is a component that incorporates much of this by lovasoa: https://github.com/lovasoa/react-contenteditable/blob/master/index.js
He shims the event in the emitChange
emitChange: function(evt){
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
evt.target = { value: html };
this.props.onChange(evt);
}
this.lastHtml = html;
}
I'm using a similar approach successfully
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
If you missed to check the "generate web.xml" option when creating a new project, no worries If it is a Dynamic Web Project in your project right click on "Deployment Descriptor:...." and Click on "Generate Deployment Descriptor Stub" this will create a minimal /webapp/WEB-INF/web.xml.
The following gets you pretty close in IE8 and works in other browsers too.
In your html:
<input type="text"
readonly="readonly" <!-- disallow editting -->
onfocus="this.blur();" <!-- prevent focus -->
tabindex="-1" <!-- disallow tabbing -->
class="disabledInput" <!-- change the color with CSS -->
/>
In your CSS:
.disabledInput {
color: black;
}
In IE8, there is a slight amount of border color change on hover. Some CSS for input.disabledInput:hover could probably take care of this.
For those coming from Ionic or Cordova, you can try the following:
Disconnect your ios devices from the computer before ios cordova build ios --release
(seems to change the targeted device for xcode signing).
I had the same issue, it was resolved by change password to strong password.
I don't have much experience than above users but I faced this same issue and I Solved this with below Solution
<Button
android:id="@+id/btnRemove"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/btnEdit"
android:layout_weight="1"
android:background="@drawable/btn"
android:text="@string/remove"
android:onClick="btnRemoveClick"
/>
btnRemoveClick Click event
public void btnRemoveClick(View v)
{
final int position = listviewItem.getPositionForView((View) v.getParent());
listItem.remove(position);
ItemAdapter.notifyDataSetChanged();
}
Fold All:
0
0
Unfold All:
To see all available shortcuts in the editor:
All shortcuts kept up to date by the Visual Studio Code team: Visual Studio Code Shortcuts
import java.util.List;
import java.util.Arrays;
import java.util.*;
public class Merge
{
public static void main(String[] args) {
// This is normal way
// List<Integer> l1 = new ArrayList<Integer>(); l1.add(2); l1.add(5); l1.add(10); l1.add(22);
// List<Integer> l2 = new ArrayList<Integer>(); l2.add(3); l2.add(8); l2.add(15);
//Array.asList only have the list interface, but ArrayList is inherited from List Interface with few more property like ArrayList.remove()
List<Integer> templ1 = Arrays.asList(2,5,10,22);
List<Integer> templ2 = Arrays.asList(3,8,12);
//So creation of ArrayList with the given list is required, then only ArrayList.remove function works.
List<Integer> l1 = new ArrayList<Integer>(templ1);
List<Integer> l2 = new ArrayList<Integer>(templ2);
List<Integer> l3 = new ArrayList<Integer>();
Iterator itr1 = l1.iterator();
while(itr1.hasNext()){
int x = (Integer) itr1.next();
Iterator itr2 = l2.iterator();
while(itr2.hasNext()) {
int y = (Integer) itr2.next();
if(x < y) {
l3.add(x);
break;
}
else{
l3.add(y);
itr2.remove();
}
}
}
Iterator it = l1.iterator();
while (it.hasNext()){
int k = (Integer) it.next();
if (l3.contains(k)){
continue;
}
else{
l3.add(k);
System.out.println(k);
}
}
Iterator itr2 = l2.iterator();
while (itr2.hasNext()){
int k = (Integer) itr2.next();
l3.add(k);
}
System.out.println(l3);
}
}
in your baseadapter class constructor try to initialize LayoutInflater, normally i preferred this way,
public ClassBaseAdapter(Context context,ArrayList<Integer> listLoanAmount) {
this.context = context;
this.listLoanAmount = listLoanAmount;
this.layoutInflater = LayoutInflater.from(context);
}
at the top of the class create LayoutInflater variable, hope this will help you
An alternative to the answer by @Marco Ponti, and avoiding the checkout:
git diff --name-only <notMainDev> $(git merge-base <notMainDev> <mainDev>)
If your particular shell doesn't understand the $() construct, use back-ticks instead.
This may be an answer (for spring boot 2) and a question at the same time. It seems that in spring boot 2 combined with spring security everything (means every route/antmatcher) is protected by default if you use an individual security mechanism extended from
WebSecurityConfigurerAdapter
If you don´t use an individual security mechanism, everything is as it was?
In older spring boot versions (1.5 and below) as Andy Wilkinson states in his above answer places like public/** or static/**
are permitted by default.
So to sum this question/answer up - if you are using spring boot 2 with spring security and have an individual security mechanism you have to exclusivley permit access to static contents placed on any route. Like so:
@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {
private final ThdAuthenticationProvider thdAuthenticationProvider;
private final ThdAuthenticationDetails thdAuthenticationDetails;
/**
* Overloaded constructor.
* Builds up the needed dependencies.
*
* @param thdAuthenticationProvider a given authentication provider
* @param thdAuthenticationDetails given authentication details
*/
@Autowired
public SpringSecurityConfiguration(@NonNull ThdAuthenticationProvider thdAuthenticationProvider,
@NonNull ThdAuthenticationDetails thdAuthenticationDetails) {
this.thdAuthenticationProvider = thdAuthenticationProvider;
this.thdAuthenticationDetails = thdAuthenticationDetails;
}
/**
* Creates the AuthenticationManager with the given values.
*
* @param auth the AuthenticationManagerBuilder
*/
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(thdAuthenticationProvider);
}
/**
* Configures the http Security.
*
* @param http HttpSecurity
* @throws Exception a given exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
.antMatchers("/management/**").hasAnyAuthority(Role.Role_Engineer.getValue(),
Role.Role_Admin.getValue())
.antMatchers("/settings/**").hasAnyAuthority(Role.Role_Engineer.getValue(),
Role.Role_Admin.getValue())
.anyRequest()
.fullyAuthenticated()
.and()
.formLogin()
.authenticationDetailsSource(thdAuthenticationDetails)
.loginPage("/login").permitAll()
.defaultSuccessUrl("/bundle/index", true)
.failureUrl("/denied")
.and()
.logout()
.invalidateHttpSession(true)
.logoutSuccessUrl("/login")
.logoutUrl("/logout")
.and()
.exceptionHandling()
.accessDeniedHandler(new CustomAccessDeniedHandler());
}
}
Please mind this line of code, which is new:
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
If you use spring boot 1.5 and below you don´t need to permit these locations (static/public/webjars etc.) explicitly.
Here is the official note, what has changed in the new security framework as to old versions of itself:
Security changes in Spring Boot 2.0 M4
I hope this helps someone. Thank you! Have a nice day!
You can use Replace instead of INSERT ... ON DUPLICATE KEY UPDATE.
You can create your own custom auth schemas that use the Authorization:
header - for example, this is how OAuth works.
As a general rule, if servers or proxies don't understand the values of standard headers, they will leave them alone and ignore them. It is creating your own header keys that can often produce unexpected results - many proxies will strip headers with names they don't recognise.
Having said that, it is possibly a better idea to use cookies to transmit the token, rather than the Authorization:
header, for the simple reason that cookies were explicitly designed to carry custom values, whereas the specification for HTTP's built in auth methods does not really say either way - if you want to see exactly what it does say, have a look here.
The other point about this is that many HTTP client libraries have built-in support for Digest and Basic auth but may make life more difficult when trying to set a raw value in the header field, whereas they will all provide easy support for cookies and will allow more or less any value within them.
As RAND
produces a number 0 <= v < 1.0 (see documentation) you need to use ROUND
to ensure that you can get the upper bound (500 in this case) and the lower bound (100 in this case)
So to produce the range you need:
SELECT name, address, ROUND(100.0 + 400.0 * RAND()) AS random_number
FROM users
In Java, List
is an interface. That is, it cannot be instantiated directly.
Instead you can use ArrayList
which is an implementation of that interface that uses an array as its backing store (hence the name).
Since ArrayList
is a kind of List
, you can easily upcast it:
List<T> mylist = new ArrayList<T>();
This is in contrast with .NET, where, since version 2.0, List<T>
is the default implementation of the IList<T>
interface.
Program prints ab
, goes back one character and prints si
overwriting the b
resulting asi
.
Carriage return returns the caret to the first column of the current line. That means the ha
will be printed over as
and the result is hai
The difference between absolute and relative imports come into play only when you import a module from a package and that module imports an other submodule from that package. See the difference:
$ mkdir pkg
$ touch pkg/__init__.py
$ touch pkg/string.py
$ echo 'import string;print(string.ascii_uppercase)' > pkg/main1.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pkg/main1.py", line 1, in <module>
import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
>>>
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/main2.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>>
In particular:
$ python2 pkg/main2.py
Traceback (most recent call last):
File "pkg/main2.py", line 1, in <module>
from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>>
$ python2 -m pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Note that python2 pkg/main2.py
has a different behaviour then launching python2
and then importing pkg.main2
(which is equivalent to using the -m
switch).
If you ever want to run a submodule of a package always use the -m
switch which prevents the interpreter for chaining the sys.path
list and correctly handles the semantics of the submodule.
Also, I much prefer using explicit relative imports for package submodules since they provide more semantics and better error messages in case of failure.
Java 8+ version:
Files.createDirectories(Paths.get("/Your/Path/Here"));
The Files.createDirectories()
creates a new directory and parent directories that do not exist. This method does not throw an exception if the directory already exists.
if ( condition ) {
return;
}
The return
exits the function returning undefined
.
The exit
statement doesn't exist in javascript.
The break
statement allows you to exit a loop, not a function. For example:
var i = 0;
while ( i < 10 ) {
i++;
if ( i === 5 ) {
break;
}
}
This also works with the for
and the switch
loops.
Missing implementation of a function in class
The reason I faced this issue was because I had deleted the function's implementation from the cpp file, but forgotten to delete the declaration from the .h file.
My answer doesn't specifically answer your question, but lets people who come to this thread looking for answer know that this can also one cause.
I personally would use the list of row lists. Because the data for each row is always in the same order, you can easily sort by any of the columns by simply accessing that element in each of the lists. You can also easily count based on a particular column in each list, and make searches as well. It's basically as close as it gets to a 2-d array.
Really the only disadvantage here is that you have to know in what order the data is in, and if you change that ordering, you'll have to change your search/sorting routines to match.
Another thing you can do is have a list of dictionaries.
rows = []
rows.append({"ID":"1", "name":"Cat", "year":"1998", "priority":"1"})
This would avoid needing to know the order of the parameters, so you can look through each "year" field in the list.
$duplicate_query=mysql_query("SELECT * FROM student") or die(mysql_error());
$duplicate=mysql_num_rows($duplicate_query);
if($duplicate==0)
{
while($value=mysql_fetch_array($duplicate_query)
{
if(($value['name']==$name)&& ($value['email']==$email)&& ($value['mobile']==$mobile)&& ($value['resume']==$resume))
{
echo $query="INSERT INTO student(name,email,mobile,resume)VALUES('$name','$email','$mobile','$resume')";
$res=mysql_query($query);
if($query)
{
echo "Success";
}
else
{
echo "Error";
}
else
{
echo "Duplicate Entry";
}
}
}
}
else
{
echo "Records Already Exixts";
}
Try also with '--quit' option, which allows you to abort the current operation and further clear the sequencer state.
--quit Forget about the current operation in progress. Can be used to clear the sequencer state after a failed cherry-pick or revert.
--abort Cancel the operation and return to the pre-sequence state.
use help to see the original doc with more details, $ git help cherry-pick
I would avoid 'git reset --hard HEAD' that is too harsh and you might ended up doing some manual work.
Look here, the operator used is !!
.
I.e. [1,2,3]!!1
gives you 2
, since lists are 0-indexed.
you might want to have a look at NumPy Random sampling distributions
<button type="submit" style="background-color:transparent; border-color:transparent;">
<img src="images/button/masuk.png" height="35"/>
</button>
<button type="reset" style="background-color:transparent; border-color:transparent;">
<img src="images/button/reset.png" height="35"/>
</button>
I hope this helps you.
I've had a similar problem when building Clang from source (but not with sudo apt-get install
. This might depend on the version of Ubuntu which you're running).
It might be worth checking if clang++
can find the correct locations of your C++ libraries:
Compare the results of g++ -v <filename.cpp>
and clang++ -v <filename.cpp>
, under "#include < ... > search starts here:".
f
is an (instance) method. However, you are calling it via fibo.f
, where fibo
is the class object. Hence, f
is unbound (not bound to any class instance).
If you did
a = fibo()
a.f()
then that f
is bound (to the instance a
).
When using the for loop, the value of s is a Map.Entry element, meaning that you can get the key from s.key and the value from s.value
in Javascript already exists constants. You define a constant like this:
const name1 = value;
This cannot change through reassignment.
One point that is missed in a lot of these discussions is how you revert back on the SAME machine on which you shelved your changes. Perhaps obvious to most, but wasn't to me. I believe you perform an Undo Pending Changes - is that right?
I understand the process to be as follows:
So, if you want to start some work which you may need to Shelve, make sure you check-in before you start, as the check-in point is where you'll return to when doing the Undo Pending Changes step above.
I had the exact same error, and like you, installing zlib1g-dev did not fix it. Installing lib32z1-dev got me past it. I have a 64 bit system and it seems like it wanted the 32 bit library.
Try this in your .htaccess:
.htaccess
ErrorDocument 404 http://example.com/404/
ErrorDocument 500 http://example.com/500/
# or map them to one error document:
# ErrorDocument 404 /pages/errors/error_redirect.php
# ErrorDocument 500 /pages/errors/error_redirect.php
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ /pages/errors/404.php [L]
RewriteCond %{REQUEST_URI} ^/500/$
RewriteRule ^(.*)$ /pages/errors/500.php [L]
# or map them to one error document:
#RewriteCond %{REQUEST_URI} ^/404/$ [OR]
#RewriteCond %{REQUEST_URI} ^/500/$
#RewriteRule ^(.*)$ /pages/errors/error_redirect.php [L]
The ErrorDocument
redirects all 404s to a specific URL, all 500s to another url (replace with your domain).
The Rewrite rules map that URL to your actual 404.php script. The RewriteCond regular expressions can be made more generic if you want, but I think you have to explicitly define all ErrorDocument codes you want to override.
Local Redirect:
Change .htaccess ErrorDocument to a file that exists (must exist, or you'll get an error):
ErrorDocument 404 /pages/errors/404_redirect.php
404_redirect.php
<?php
header('Location: /404/');
exit;
?>
Redirect based on error number
Looks like you'll need to specify an ErrorDocument
line in .htaccess for every error you want to redirect (see: Apache ErrorDocument and Apache Custom Error). The .htaccess example above has multiple examples in it. You can use the following as the generic redirect script to replace 404_redirect.php above.
error_redirect.php
<?php
$error_url = $_SERVER["REDIRECT_STATUS"] . '/';
$error_path = $error_url . '.php';
if ( ! file_exists($error_path)) {
// this is the default error if a specific error page is not found
$error_url = '404/';
}
header('Location: ' . $error_url);
exit;
?>
This answer meets the requirements of the OP. specifically it allows the needle to be more than a single character and it does not generate an error when needle is not found in haystack. It seemed to me that most (all?) of the other answers did not handle those edge cases. Beyond that I added the "Starting Position" argument provided by the native MS SQL server CharIndex function. I tried to exactly mirror the specification for CharIndex except to process right to left instead of left to right. eg I return null if either needle or haystack is null and I return zero if needle is not found in haystack. One thing that I could not get around is that with the built in function the third parameter is optional. With SQL Server user defined functions, all parameters must be provided in the call unless the function is called using "EXEC" . While the third parameter must be included in the parameter list, you can provide the keyword "default" as a placeholder for it without having to give it a value (see examples below). Since it is easier to remove the third parameter from this function if not desired than it would be to add it if needed I have included it here as a starting point.
create function dbo.lastCharIndex(
@needle as varchar(max),
@haystack as varchar(max),
@offset as bigint=1
) returns bigint as begin
declare @position as bigint
if @needle is null or @haystack is null return null
set @position=charindex(reverse(@needle),reverse(@haystack),@offset)
if @position=0 return 0
return (len(@haystack)-(@position+len(@needle)-1))+1
end
go
select dbo.lastCharIndex('xyz','SQL SERVER 2000 USES ANSI SQL',default) -- returns 0
select dbo.lastCharIndex('SQL','SQL SERVER 2000 USES ANSI SQL',default) -- returns 27
select dbo.lastCharIndex('SQL','SQL SERVER 2000 USES ANSI SQL',1) -- returns 27
select dbo.lastCharIndex('SQL','SQL SERVER 2000 USES ANSI SQL',11) -- returns 1
Just copied file: org.apache.http.legacy.jar
from Android/Sdk/platforms/android-23/optional
folder into project folder app/libs
.
Worked like charm for 23.1.1.
Use the FIND_IN_SET function:
SELECT t.*
FROM YOUR_TABLE t
WHERE FIND_IN_SET(3, t.ids) > 0
After a lot of trial and error, I found the pattern UQ(rlang::sym("some string here")))
really useful for working with strings and dplyr verbs. It seems to work in a lot of surprising situations.
Here's an example with mutate
. We want to create a function that adds together two columns, where you pass the function both column names as strings. We can use this pattern, together with the assignment operator :=
, to do this.
## Take column `name1`, add it to column `name2`, and call the result `new_name`
mutate_values <- function(new_name, name1, name2){
mtcars %>%
mutate(UQ(rlang::sym(new_name)) := UQ(rlang::sym(name1)) + UQ(rlang::sym(name2)))
}
mutate_values('test', 'mpg', 'cyl')
The pattern works with other dplyr
functions as well. Here's filter
:
## filter a column by a value
filter_values <- function(name, value){
mtcars %>%
filter(UQ(rlang::sym(name)) != value)
}
filter_values('gear', 4)
Or arrange
:
## transform a variable and then sort by it
arrange_values <- function(name, transform){
mtcars %>%
arrange(UQ(rlang::sym(name)) %>% UQ(rlang::sym(transform)))
}
arrange_values('mpg', 'sin')
For select
, you don't need to use the pattern. Instead you can use !!
:
## select a column
select_name <- function(name){
mtcars %>%
select(!!name)
}
select_name('mpg')
This works quite well in my local.py, saves me messing up the regular logging:
from .settings import *
LOGGING['handlers']['console'] = {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
}
LOGGING['loggers']['foo.bar'] = {
'handlers': ['console'],
'propagate': False,
'level': 'DEBUG',
}
Chinese Remainder Theorem comes to mind as an initial point as 221 = 13 * 17. So, break this down into 2 parts that get combined in the end, one for mod 13 and one for mod 17. Second, I believe there is some proof of a^(p-1) = 1 mod p for all non zero a which also helps reduce your problem as 5^55 becomes 5^3 for the mod 13 case as 13*4=52. If you look under the subject of "Finite Fields" you may find some good results on how to solve this.
EDIT: The reason I mention the factors is that this creates a way to factor zero into non-zero elements as if you tried something like 13^2 * 17^4 mod 221, the answer is zero since 13*17=221. A lot of large numbers aren't going to be prime, though there are ways to find large primes as they are used a lot in cryptography and other areas within Mathematics.
@ryenus, You need to loop through the result. This is how I'd do it in vbscript;
Set xmlDoc = CreateObject("Msxml2.DOMDocument")
xmlDoc.setProperty "SelectionLanguage", "XPath"
xmlDoc.load("kids.xml")
'Remove the id=1 attribute on Parent to return all child names for all Parent nodes
For Each c In xmlDoc.selectNodes ("//Parent[@id='1']/Children/child/@name")
Wscript.Echo c.text
Next
To add to the great asnwer by @Krunal https://stackoverflow.com/a/49552326/4697535
In case you are using a UINavigationController
, the preferredStatusBarStyle
will have no effect on the UIViewController
.
Xcode 10 and Swift 4.
Set a custom UINavigationController
Example:
class LightNavigationController: UINavigationController {
open override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
Use an extension for an app level solution:
extension UINavigationController {
open override var preferredStatusBarStyle: UIStatusBarStyle {
guard let index = tabBarController?.selectedIndex else { return .default }
switch index {
case 0, 1, 2: return .lightContent // set lightContent for tabs 0-2
default: return .default // set dark for tab 3
}
}
}
You just need to have a module that exports a history
object. Then you would import that object throughout your project.
// history.js
import { createBrowserHistory } from 'history'
export default createBrowserHistory({
/* pass a configuration object here if needed */
})
Then, instead of using one of the built-in routers, you would use the <Router>
component.
// index.js
import { Router } from 'react-router-dom'
import history from './history'
import App from './App'
ReactDOM.render((
<Router history={history}>
<App />
</Router>
), holder)
// some-other-file.js
import history from './history'
history.push('/go-here')
You can make both arguments lower case, and that way you will always end up with a case insensitive search.
var string1 = "aBc";
var string2 = "AbC";
if (string1.toLowerCase() === string2.toLowerCase())
{
#stuff
}
PATH: Answered long ago, however, it maybe more helpful to think of -p as "Path" (easier to remember), as in this causes mkdir to create every part of the path that isn't already there.
mkdir -p /usr/bin/comm/diff/er/fence
if /usr/bin/comm already exists, it acts like: mkdir /usr/bin/comm/diff mkdir /usr/bin/comm/diff/er mkdir /usr/bin/comm/diff/er/fence
As you can see, it saves you a bit of typing, and thinking, since you don't have to figure out what's already there and what isn't.
Does this work?
display_errors = Off
Also, what version of php are you using?
I believe you're looking for HttpServerUtility.UrlEncode.
System.Web.HttpUtility.UrlEncode(string url)
I had problems due to atom being unable to write its logfile when starting from the commandline. This cured it.
sudo chmod 777 ~/.atom/nohup.out
Simplified for Kotlin:
val widthDp = resources.displayMetrics.run { widthPixels / density }
val heightDp = resources.displayMetrics.run { heightPixels / density }
table.setDefaultEditor(Object.class, null);
Change the content-type to "application/x-www-form-urlencoded", i solved the problem.
If working with data, many times pandas
is the simple key
This particular code will put the raw
into one column, then normalize by column per row. (But we can put it into a row and do it by row per column, too! Just have to change the axis
values where 0 is for row and 1 is for column.)
import pandas as pd
raw = [0.07, 0.14, 0.07]
raw_df = pd.DataFrame(raw)
normed_df = raw_df.div(raw_df.sum(axis=0), axis=1)
normed_df
where normed_df
will display like:
0
0 0.25
1 0.50
2 0.25
and then can keep playing with the data, too!
Try with /debug.1,2 As in :
signtool sign /debug /f mypfxfile.pfx /p <password> (mydllexectuable).exe
It will help you find out what is going on. You should get output like this:
The following certificates were considered:
Issued to: <issuer>
Issued by: <certificate authority> Class 2 Primary Intermediate Server CA
Expires: Sun Mar 01 14:18:23 2015
SHA1 hash: DD0000000000000000000000000000000000D93E
Issued to: <certificate authority> Certification Authority
Issued by: <certificate authority> Certification Authority
Expires: Wed Sep 17 12:46:36 2036
SHA1 hash: 3E0000000000000000000000000000000000000F
After EKU filter, 2 certs were left.
After expiry filter, 2 certs were left.
After Private Key filter, 0 certs were left.
SignTool Error: No certificates were found that met all the given criteria.
You can see what filter is causing your certificate to not work, or if no certificates were considered.
I changed the hashes and other info, but you should get the idea. Hope this helps.
1 Please note: signtool
is particular about where the /debug
option is placed. It needs to go after the sign
statement.
2 Also note: the /debug
option only works with some versions of signtool
. The WDK version has the option, whereas the Windows SDK version does not.
You can use simple jQuery jPut plugin
http://plugins.jquery.com/jput/
<script>
$(document).ready(function(){
var json = [{"name": "name1","email":"[email protected]"},{"name": "name2","link":"[email protected]"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
jsonData:json,
//ajax_url:"youfile.json", if you want to call from a json file
name:"tbody_template",
});
});
</script>
<table jput="t_template">
<tbody jput="tbody_template">
<tr>
<td>{{name}}</td>
<td>{{email}}</td>
</tr>
</tbody>
</table>
<table>
<tbody id="tbody">
</tbody>
</table>
You can see all steps to connect MySQL database from Java application here. For other database, you just need to change the driver in first step only. Please make sure that you provide right path to database and correct username and password.
Visit http://apekshit.com/t/51/Steps-to-connect-Database-using-JAVA
In Python 3,
def filter_nonprintable(text):
import itertools
# Use characters of control category
nonprintable = itertools.chain(range(0x00,0x20),range(0x7f,0xa0))
# Use translate to remove all non-printable characters
return text.translate({character:None for character in nonprintable})
See this StackOverflow post on removing punctuation for how .translate() compares to regex & .replace()
The ranges can be generated via nonprintable = (ord(c) for c in (chr(i) for i in range(sys.maxunicode)) if unicodedata.category(c)=='Cc')
using the Unicode character database categories as shown by @Ants Aasma.
If you want to pack a struct with a value <255 (one byte unsigned, uint8_t) and end up with a string of one character, you're probably looking for the format B instead of c. C converts a character to a string (not too useful by itself) while B converts an integer.
struct.pack('B', 65)
(And yes, 65 is \x41, not \x65.)
The struct class will also conveniently handle endianness for communication or other uses.
Also, if you're performing the query on the Bash command line, I believe the tr
command can be used to substitute the default tabs to arbitrary delimiters.
$ echo "SELECT * FROM Table123" | mysql Database456 | tr "\t" ,
Java converts Integer to int and back automatically (unless you are still with Java 1.4).
You can use ping -a <ip>
or nbtstat -A <ip>
Just use awk, it's much simpler than grep in letting you clearly express compound conditions.
If you want to skip lines that contains both loom
and gloom
:
awk '/loom/ && !/gloom/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)
or if you want to print them:
awk '/(^|[^g])loom/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)
and if the reality is you just want lines where loom
appears as a word by itself:
awk '/\<loom\>/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)
Download the source package, open Terminal.app, navigate to the directory where you currently have the file, and then execute:
R CMD INSTALL RJSONIO_0.2-3.tar.gz
Do note that this will only succeed when either: a) the package does not need compilation or b) the needed system tools for compilation are present. See: https://cran.r-project.org/bin/macosx/tools/
So starting with the answer given and applying the fact that CSS3 allows multiple settings - the below code is useful for creating a complete box:
#border {_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
background: yellow;_x000D_
text-align: center;_x000D_
line-height: 100px;_x000D_
background: linear-gradient(to right, orange 50%, rgba(255, 255, 255, 0) 0%), linear-gradient(blue 50%, rgba(255, 255, 255, 0) 0%), linear-gradient(to right, green 50%, rgba(255, 255, 255, 0) 0%), linear-gradient(red 50%, rgba(255, 255, 255, 0) 0%);_x000D_
background-position: top, right, bottom, left;_x000D_
background-repeat: repeat-x, repeat-y;_x000D_
background-size: 10px 1px, 1px 10px;_x000D_
}
_x000D_
<div id="border">_x000D_
bordered area_x000D_
</div>
_x000D_
Its worth noting that the 10px in the background size gives the area that the dash and gap will cover. The 50% of the background tag is how wide the dash actually is. It is therefore possible to have different length dashes on each border side.
As I said in the comments, a <div>
element does not have a value
attribute. Although (very) bad, it can be accessed as:
console.log(document.getElementById('demo').getAttribute);
I suggest using HTML5 data-*
attributes rather. Something like this:
<div id="demo" data-myValue="1">...</div>
in which case you could access it using:
element.getAttribute('data-myValue');
//Or using jQuery:
$('#demo').data('myValue');
While editing the code (because mild OCD), I noticed that weather is also a list. You should probably consider something like
echo $data[0]->weather[0]->weatherIconUrl[0]->value;
to make sure you are using the weatherIconUrl for the correct date instance.
An ES6 approach to clearing a group of radio buttons:
Array.from( document.querySelectorAll('input[name="group-name"]:checked'), input => input.checked = false );
MERGE INTO OPT
USING
(SELECT 1 "one" FROM dual)
ON
(OPT.email= '[email protected]' and OPT.campaign_id= 100)
WHEN NOT matched THEN
INSERT (email, campaign_id)
VALUES ('[email protected]',100)
;
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
Switch to preg_replace
Docs and update the expression to use preg syntax (PCRE) instead of ereg syntax (POSIX) where there are differencesDocs (just as it says to do in the manual for ereg_replace
Docs).
As someone said (I'm paraphrasing) in another thread "Rules like this should not be broken, until you fully understand the consequences of doing so."
There are times when global variables are necessary, or at least very helpful (Working with system defined call-backs for example). On the other hand, they're also very dangerous for all of the reasons you've been told.
There are many aspects of programming that should probably be left to the experts. Sometimes you NEED a very sharp knife. But you don't get to use one until you're ready...
You can mark properties with readonly
modifier in your declaration:
export class MyClass {
public static readonly MY_PUBLIC_CONSTANT = 10;
private static readonly myPrivateConstant = 5;
}
Your best option here, is to use the Query String to 'send' the value.
how to get query string value using javascript
If this is anything more than a learning exercise you may want to consider the security implications of this though.
Global variables wont help you here as once the page is re-loaded they are destroyed.
You cant have multiple ng-view. Below is my use case where I solved my requirement. I wanted to have tabbed behavior in my model dialog. I was facing issue as click on tabs having hyperlink which will invoke router links. I solved this using button and css for tabs. When user clicks on tab, it actually will not call any hyperlink which will always invoke the ng-router. When user click on tab it will call a method, where I dynamcilly load html. Below is the function on click of tab
self.submit = function(form) {
$templateRequest('resources/items/employee/test_template.html').then(function(template){
var compiledeHTML = $compile(template)($scope);
$("#d").replaceWith(compiledeHTML);
});
User $templateRequest. In test_template.html page add your html content. This html content will be bind to your controller.
Can you place the #ulId in the document prior to the ajax load (with css display: none;), or wrap it in a containing div (with css display: none;), then just load the inner html during ajax page load, that way the scroll event will be linked to the div that is already there prior to the ajax?
Then you can use:
$('#ulId').on('scroll',function(){ console.log('Event Fired'); })
obviously replacing ulId with whatever the actual id of the scrollable div is.
Then set css display: block; on the #ulId (or containing div) upon load?
Tell the correlation to ignore the NAs with use
argument, e.g.:
cor(data$price, data$exprice, use = "complete.obs")
You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file
to debug it.
When it starts up, you can use bt
(for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number
(replacing number with the corresponding number in the stack trace) to select a particular stack frame.
You can then use list
to see code around that function, and info locals
to see the local variables. You can also use print name_of_variable
(replacing "name_of_variable" with a variable name) to see its value.
Typing help
within GDB will give you a prompt that will let you see additional commands.
a=np.array([[1,2,3],[4,5,6]])
a.tolist()
tolist method mentioned above will return the nested Python list
BEGIN TRANSACTION
select top 1 *
from table1
with (tablock, holdlock)
-- You do lots of things here
COMMIT
This will hold the 'table lock' until the end of your current "transaction".
A quick, clean approach using very little JS and CSS padding: http://jsfiddle.net/benjamincharity/ZcTsT/14/
var headerHeight = $('#header').height(),
footerHeight = $('#footer').height();
$('#content').css({
'padding-top': headerHeight,
'padding-bottom': footerHeight
});
A very simple way to get around this is to open the path where pip is installed in File Explorer, and click on the path, then type cmd, this sets the path, allowing you to install way easier.
I ran into the same issue a couple days ago and all the other methods didn't work for me.
I would like to add on to @krlmlr's answer.
Initially, the forked repository has one branch named : master
. If you are working on a new feature or a fix, you would generally create a new branch feature
and make the changes.
If you want the forked repository to be in sync with the parent repository, you could set up a config file(pull.yml
) for the Pull app (in the feature branch), like this:
version: "1"
rules:
- base: feature
upstream: master
mergeMethod: merge
- base: master
upstream: parent_repo:master
mergeMethod: hardreset
This keeps the master
branch of the forked repo up-to-date with the parent repo. It keeps the feature
branch of the forked repo updated via the master
branch of the forked repo by merging the same. This assumes that the feature
branch is the default branch which contains the config file.
Here two mergemethods
are into play, one is hardreset
which helps force sync changes in the master
branch of the forked repo with the parent repo and the other method is merge
. This method is used to merge changes done by you in the feature
branch and changes done due to force sync in the master
branch. In case of merge conflict, the pull app will allow you to choose the next course of action during the pull request.
You can read about basic and advanced configs and various mergemethods
here.
I am currently using this configuration in my forked repo here to make sure an enhancement requested here stays updated.
str[a:b]
tl;dr: use a colon :
instead of a comma in between the two indices a
and b
in str[a:b]
When working with strings and slice notation (a common sequence operation), it can happen that a TypeError
is raised, pointing out that the indices must be integers, even if they obviously are.
>>> my_string = "hello world"
>>> my_string[0,5]
TypeError: string indices must be integers
We obviously passed two integers for the indices to the slice notation, right? So what is the problem here?
This error can be very frustrating - especially at the beginning of learning Python - because the error message is a little bit misleading.
We implicitly passed a tuple of two integers (0 and 5) to the slice notation when we called my_string[0,5]
because 0,5
(even without the parentheses) evaluates to the same tuple as (0,5)
would do.
A comma ,
is actually enough for Python to evaluate something as a tuple:
>>> my_variable = 0,
>>> type(my_variable)
<class 'tuple'>
So what we did there, this time explicitly:
>>> my_string = "hello world"
>>> my_tuple = 0, 5
>>> my_string[my_tuple]
TypeError: string indices must be integers
Now, at least, the error message makes sense.
We need to replace the comma ,
with a colon :
to separate the two integers correctly:
>>> my_string = "hello world"
>>> my_string[0:5]
'hello'
A clearer and more helpful error message could have been something like:
TypeError: string indices must be integers (not tuple)
A good error message shows the user directly what they did wrong and it would have been more obvious how to solve the problem.
[So the next time when you find yourself responsible for writing an error description message, think of this example and add the reason or other useful information to error message to let you and maybe other people understand what went wrong.]
:
to separate its indices (and step range, e.g. str[from:to:step]
),
(e.g. t = 1,
)Cheers and happy programming
winklerrr
[I know this question was already answered and this wasn't exactly the question the thread starter asked, but I came here because of the above problem which leads to the same error message. At least it took me quite some time to find that little typo.
So I hope that this will help someone else who stumbled upon the same error and saves them some time finding that tiny mistake.]
Try this.
var dateAsString = DateTime.Now.ToString("dd/MM/yyyy");
// dateAsString = "09/07/2013"
I used below regex to get that result also when its finished by a \
(\\[^\\]+)\\?$
Simplest way,
If your query is Model.Objects.get():
get() will return single instance so you can direct use __dict__
from your instance
model_dict = Model.Objects.get().__dict__
for filter()/all():
all()/filter() will return list of instances so you can use values()
to get list of objects.
model_values = Model.Objects.all().values()
JSON.stringify
takes more optional arguments.
Try:
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab
From:
How can I beautify JSON programmatically?
Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre>
tag to get newlines to show.
So, There is something I would like to bring up which I think is important and I think that you should consider. runtime and memory. Say you have a list and want to sort it, well you can, there is a built in sort or you could develop your own. Then you say, want to reverse the list. That is the answer which is listed above.
If you are creating that list though, it might be good to use a different datastructure to store it and then just dump it into an array.
Heaps do just this. You filter in data, and it will handle everything, then you can pop everything off of the object and it would be sorted.
Another option would be to understand how maps work. A lot of times, a Map or HashMap as something things are called, have an underlying concept behind it.
For example.... you feed in a bunch of key-value pairs where the key is the long, and when you add all the elements, you can do: .keys
and it would return to you a sorted list automatically.
It depends on how you process the data prior as to how i think you should continue with your sorting and subsequent reverses
VistaFolderBrowserDialog
is the one you want.If you only want the Folder Browser from Ooki Dialogs and nothing else then download the Source, cherry-pick the files you need for the Folder browser (hint: 7 files) and it builds fine in .NET 4.5.2. I had to add a reference to System.Drawing
. Compare the references in the original project to yours.
How do you figure out which files? Open your app and Ookii in different Visual Studio instances. Add VistaFolderBrowserDialog.cs
to your app and keep adding files until the build errors go away. You find the dependencies in the Ookii project - Control-Click the one you want to follow back to its source (pun intended).
Here are the files you need if you're too lazy to do that ...
NativeMethods.cs
SafeHandles.cs
VistaFolderBrowserDialog.cs
\ Interop
COMGuids.cs
ErrorHelper.cs
ShellComInterfaces.cs
ShellWrapperDefinitions.cs
Edit line 197 in VistaFolderBrowserDialog.cs
unless you want to include their Resources.Resx
throw new InvalidOperationException(Properties.Resources.FolderBrowserDialogNoRootFolder);
throw new InvalidOperationException("Unable to retrieve the root folder.");
Add their copyright notice to your app as per their license.txt
The code in \Ookii.Dialogs.Wpf.Sample\MainWindow.xaml.cs
line 160-169 is an example you can use but you will need to remove this,
from MessageBox.Show(this,
for WPF.
Works on My Machine [TM]
Just to phrase things differently from the great answers above, as that has helped me get an intuitive understanding of negative margins:
A negative margin on an element allows it to eat up the space of its parent container.
Adding a (positive) margin on the bottom doesn't allow the element to do that - it only pushes back whatever element is below.
This is how you should do it : ( for google find)
$([
{"name":"Lenovo Thinkpad 41A4298","website":"google222"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"}
])
.filter(function (i,n){
return n.website==='google';
});
Better solution : ( Salman's)
$.grep( [{"name":"Lenovo Thinkpad 41A4298","website":"google"},{"name":"Lenovo Thinkpad 41A2222","website":"google"}], function( n, i ) {
return n.website==='google';
});
use the relative path
main page might be: /index.html
secondary page: /otherFolder/otherpage.html
link would be like so:
<a href="/otherFolder/otherpage.html">otherpage</a>
Label without an onclick will behave as you would expect. It changes the input. What you relly want is to execute selectAll()
when you click on a label, right?
Then only add select all to the label onclick. Or wrap the input into the the label and assign onclick only for the label
<label for="check_all_1" onclick="selectAll(document.wizard_form, this);">
<input type="checkbox" id="check_all_1" name="check_all_1" title="Select All">
Select All
</label>
Web Server: It provides HTTP Request and HTTP response. It handles request from client only through HTTP protocol. It contains Web Container. Web Application mostly deployed on web Server. EX: Servlet JSP
Web Container: it maintains the life cycle for Servlet Object. Calls the service method for that servlet object. pass the HttpServletRequest and HttpServletResponse Object
Application Server: It holds big Enterprise application having big business logic. It is Heavy Weight or it holds Heavy weight Applications. Ex: EJB
A shorter cable did the trick.
It turns out that the wire thickness used inside the cable impacts on the resistance of the cable assembly – this resistance causes energy loss inside the cable when an attached load draws a current, and causes a voltage drop which can reduce the voltage to the end device to a point where it is not possible to charge quickly or completely.
http://goughlui.com/2014/10/01/usb-cable-resistance-why-your-phonetablet-might-be-charging-slow/
If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:
If you're using a shell, the filepath to the Download (no "s") folder is
/storage/emulated/0/Download
var mouseX;
var mouseY;
$(document).mousemove( function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
});
$(".classForHoverEffect").mouseover(function(){
$('#DivToShow').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
});
the function above will make the DIV appear over the link wherever that may be on the page. It will fade in slowly when the link is hovered. You could also use .hover() instead. From there the DIV will stay, so if you would like the DIV to disappear when the mouse moves away, then,
$(".classForHoverEffect").mouseout(function(){
$('#DivToShow').fadeOut('slow');
});
If you DIV is already positioned, you can simply use
$('.classForHoverEffect').hover(function(){
$('#DivToShow').fadeIn('slow');
});
Also, keep in mind, your DIV style needs to be set to display:none;
in order for it to fadeIn or show.
Linux
conda env export --no-builds | grep -v "prefix" > environment.yml
Windows
conda env export --no-builds | findstr -v "prefix" > environment.yml
Rationale: By default, conda env export
includes the build information:
$ conda env export
...
dependencies:
- backcall=0.1.0=py37_0
- blas=1.0=mkl
- boto=2.49.0=py_0
...
You can instead export your environment without build info:
$ conda env export --no-builds
...
dependencies:
- backcall=0.1.0
- blas=1.0
- boto=2.49.0
...
Which unties the environment from the Python version and OS.
I ran into the same issue and couldn't decide between laughing or smashing my head on the table when I read this error...
What git really tries to tell you: "You are already in a merge state and need to resolve the conflicts there first!"
You tried a merge and a conflict occured. Then, git stays in the merge state and if you want to resolve the merge with other commands git thinks you want to execute a new merge and so it tells you you can't do this because of your current unmerged files...
You can leave this state with git merge --abort
and now try to execute other commands.
In my case I tried a pull and wanted to resolve the conflicts by hand when the error occured...
The answer is explained here.
To quote:
A class is free to implement comparison any way it chooses, and it can choose to make comparison against None mean something (which actually makes sense; if someone told you to implement the None object from scratch, how else would you get it to compare True against itself?).
Practically-speaking, there is not much difference since custom comparison operators are rare. But you should use is None
as a general rule.
Very old question here, but I ran into the same error and none of the provided answers solved the issue.
My issue occurred because I manually changed the namespace and assembly names of the project after initial creation. Took me a little bit to notice that the namespace in the Inherits
attribute didn't match the updated namespace.
Updating that namespace in the Global.asax markup to match the apps namespace fixed the error for me.
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
Setup npm
proxy
For HTTP
:
npm config set proxy http://proxy_host:port
For HTTPS
:
use the https proxy address if there is one
npm config set https-proxy https://proxy.company.com:8080
else reuse the http proxy address
npm config set https-proxy http://proxy.company.com:8080
Note: The https-proxy doesn't have https
as the protocol, but http
.
The simple difference between document ready and page event in jQuery-mobile is that:
The document ready event is used for the whole HTML page,
$(document).ready(function(e) {
// Your code
});
When there is a page event, use for handling particular page event:
<div data-role="page" id="second">
<div data-role="header">
<h3>
Page header
</h3>
</div>
<div data-role="content">
Page content
</div> <!--content-->
<div data-role="footer">
Page footer
</div> <!--footer-->
</div><!--page-->
You can also use document for handling the pageinit event:
$(document).on('pageinit', "#mypage", function() {
});
A copy-pastable solution similar to the one of ghostdog:
def get_all_filepaths(root_path, ext):
"""
Search all files which have a given extension within root_path.
This ignores the case of the extension and searches subdirectories, too.
Parameters
----------
root_path : str
ext : str
Returns
-------
list of str
Examples
--------
>>> get_all_filepaths('/run', '.lock')
['/run/unattended-upgrades.lock',
'/run/mlocate.daily.lock',
'/run/xtables.lock',
'/run/mysqld/mysqld.sock.lock',
'/run/postgresql/.s.PGSQL.5432.lock',
'/run/network/.ifstate.lock',
'/run/lock/asound.state.lock']
"""
import os
all_files = []
for root, dirs, files in os.walk(root_path):
for filename in files:
if filename.lower().endswith(ext):
all_files.append(os.path.join(root, filename))
return all_files
Edit: The original link I answered with is now invalid.The newer URL would be https://developers.google.com/web/tools/chrome-devtools/javascript/add-breakpoints#exceptions as of 2016-11-11.
I realize this question has an answer, but it's no longer accurate. Use the link above ^
(link replaced by edited above) - you can now set it to break on all exceptions or just unhandled ones. (Note that you need to be in the Sources tab to see the button.)
Chrome's also added some other really useful breakpoint capabilities now, such as breaking on DOM changes or network events.
Normally I wouldn't re-answer a question, but I had the same question myself, and I found this now-wrong answer, so I figured I'd put this information in here for people who came along later in searching. :)
It's a difference between RDBMS's varchar
(or similar) — those are usually specified with a maximum length, and might be more efficient in terms of performance or storage — and text
(or similar) types — those are usually limited only by hardcoded implementation limits (not a DB schema).
PostgreSQL 9, specifically, states that "There is no performance difference among these three types", but AFAIK there are some differences in e.g. MySQL, so this is something to keep in mind.
A good rule of thumb is that you use CharField
when you need to limit the maximum length, TextField
otherwise.
This is not really Django-specific, also.
So the suggested answer from TheHippo did not work for me, instead I ended up sending the form as a parameter to the function like so:
<form name="loginform" novalidate ng-submit="login.submit(loginForm)" class="css-form">
This makes the form available in the controller method:
$scope.login = {
submit : function(form) {
if(form.$valid)....
}
I looked at existing answers but I also found that setting the button frame is an important first step.
Here is a function that I use that takes care of this:
const CGFloat kImageTopOffset = -15;
const CGFloat kTextBottomOffset = -25;
+ (void) centerButtonImageTopAndTextBottom: (UIButton*) button
frame: (CGRect) buttonFrame
text: (NSString*) textString
textColor: (UIColor*) textColor
font: (UIFont*) textFont
image: (UIImage*) image
forState: (UIControlState) buttonState
{
button.frame = buttonFrame;
[button setTitleColor: (UIColor*) textColor
forState: (UIControlState) buttonState];
[button setTitle: (NSString*) textString
forState: (UIControlState) buttonState ];
[button.titleLabel setFont: (UIFont*) textFont ];
[button setTitleEdgeInsets: UIEdgeInsetsMake( 0.0, -image.size.width, kTextBottomOffset, 0.0)];
[button setImage: (UIImage*) image
forState: (UIControlState) buttonState ];
[button setImageEdgeInsets: UIEdgeInsetsMake( kImageTopOffset, 0.0, 0.0,- button.titleLabel.bounds.size.width)];
}
If you want to refresh previous activity, this solution should work:
In previous activity where you want to refresh:
@Override
public void onRestart()
{
super.onRestart();
// do some stuff here
}
static byte[] SliceMe(byte[] source, int length)
{
byte[] destfoo = new byte[length];
Array.Copy(source, 0, destfoo, 0, length);
return destfoo;
}
//
var myslice = SliceMe(sourcearray,41);
The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher
//Pass results back to the client
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);
By default you use curl without explicitly saying which request method to use. If you just pass in a HTTP URL like curl http://example.com
it will use GET. If you use -d
or -F
curl will use POST, -I
will cause a HEAD and -T
will make it a PUT.
If for whatever reason you're not happy with these default choices that curl does for you, you can override those request methods by specifying -X [WHATEVER]
. This way you can for example send a DELETE by doing curl -X DELETE [URL]
.
It is thus pointless to do curl -X GET [URL]
as GET would be used anyway. In the same vein it is pointless to do curl -X POST -d data [URL]...
But you can make a fun and somewhat rare request that sends a request-body in a GET request with something like curl -X GET -d data [URL]
.
curl -GET
(using a single dash) is just wrong for this purpose. That's the equivalent of specifying the -G
, -E
and -T
options and that will do something completely different.
There's also a curl option called --get
to not confuse matters with either. It is the long form of -G, which is used to convert data specified with -d
into a GET request instead of a POST.
(I subsequently used my own answer here to populate the curl FAQ to cover this.)
Modern versions of curl will inform users about this unnecessary and potentially harmful use of -X when verbose mode is enabled (-v
) - to make users aware. Further explained and motivated in this blog post.
You can ask curl to convert a set of -d
options and instead of sending them in the request body with POST, put them at the end of the URL's query string and issue a GET, with the use of `-G. Like this:
curl -d name=daniel -d grumpy=yes -G https://example.com/
The problem is that your regex is a string, but html
is bytes:
>>> type(html)
<class 'bytes'>
Since python doesn't know how those bytes are encoded, it throws an exception when you try to use a string regex on them.
You can either decode
the bytes to a string:
html = html.decode('ISO-8859-1') # encoding may vary!
title = re.findall(pattern, html) # no more error
Or use a bytes regex:
regex = rb'<title>(,+?)</title>'
# ^
In this particular context, you can get the encoding from the response headers:
with urllib.request.urlopen(url) as response:
encoding = response.info().get_param('charset', 'utf8')
html = response.read().decode(encoding)
See the urlopen
documentation for more details.
It gets revealed when you debug using the debug() function. Suppose you want to see the underlying code in t() transpose function. Just typing 't', doesn't reveal much.
>t
function (x)
UseMethod("t")
<bytecode: 0x000000003085c010>
<environment: namespace:base>
But, Using the 'debug(functionName)', it reveals the underlying code, sans the internals.
> debug(t)
> t(co2)
debugging in: t(co2)
debug: UseMethod("t")
Browse[2]>
debugging in: t.ts(co2)
debug: {
cl <- oldClass(x)
other <- !(cl %in% c("ts", "mts"))
class(x) <- if (any(other))
cl[other]
attr(x, "tsp") <- NULL
t(x)
}
Browse[3]>
debug: cl <- oldClass(x)
Browse[3]>
debug: other <- !(cl %in% c("ts", "mts"))
Browse[3]>
debug: class(x) <- if (any(other)) cl[other]
Browse[3]>
debug: attr(x, "tsp") <- NULL
Browse[3]>
debug: t(x)
EDIT: debugonce() accomplishes the same without having to use undebug()
It is a Generic Type Parameter.
A generic type parameter allows you to specify an arbitrary type T to a method at compile-time, without specifying a concrete type in the method or class declaration.
For example:
public T[] Reverse<T>(T[] array)
{
var result = new T[array.Length];
int j=0;
for(int i=array.Length - 1; i>= 0; i--)
{
result[j] = array[i];
j++;
}
return result;
}
reverses the elements in an array. The key point here is that the array elements can be of any type, and the function will still work. You specify the type in the method call; type safety is still guaranteed.
So, to reverse an array of strings:
string[] array = new string[] { "1", "2", "3", "4", "5" };
var result = reverse(array);
Will produce a string array in result
of { "5", "4", "3", "2", "1" }
This has the same effect as if you had called an ordinary (non-generic) method that looks like this:
public string[] Reverse(string[] array)
{
var result = new string[array.Length];
int j=0;
for(int i=array.Length - 1; i >= 0; i--)
{
result[j] = array[i];
j++;
}
return result;
}
The compiler sees that array
contains strings, so it returns an array of strings. Type string
is substituted for the T
type parameter.
Generic type parameters can also be used to create generic classes. In the example you gave of a SampleCollection<T>
, the T
is a placeholder for an arbitrary type; it means that SampleCollection
can represent a collection of objects, the type of which you specify when you create the collection.
So:
var collection = new SampleCollection<string>();
creates a collection that can hold strings. The Reverse
method illustrated above, in a somewhat different form, can be used to reverse the collection's members.
With Xcode 9.3, this seems to be resolved by cleaning the project, quitting and restarting Xcode, and, after the restart, cleaning the build folder (hold Option and select Product->Clean Build Folder).
During the restart I happened to have the Xcode signing-info panel open on the Project navigator and saw a transient message that Xcode was rebuilding the signing profile. Upon trying to run my project on a device, I got a runtime exception due to a Swift framework file having an invalid signature. The second "Clean Build Folder" cleared that up and all works fine now.
It doesn't matter what you use as a primary key so long as it is UNIQUE. If you care about speed or good database design use the int unless you plan on replicating data, then use a GUID.
If this is an access database or some tiny app then who really cares. I think the reason why most of us developers slap the old int or guid at the front is because projects have a way of growing on us, and you want to leave yourself the option to grow.
You can load jpeg binary data as a file and parse the jpeg headers yourself. The one you are looking for is the 0xFFC0 or Start of Frame header:
Start of frame marker (FFC0)
* the first two bytes, the length, after the marker indicate the number of bytes, including the two length bytes, that this header contains
* P -- one byte: sample precision in bits (usually 8, for baseline JPEG)
* Y -- two bytes
* X -- two bytes
* Nf -- one byte: the number of components in the image
o 3 for color baseline JPEG images
o 1 for grayscale baseline JPEG images
* Nf times:
o Component ID -- one byte
o H and V sampling factors -- one byte: H is first four bits and V is second four bits
o Quantization table number-- one byte
The H and V sampling factors dictate the final size of the component they are associated with. For instance, the color space defaults to YCbCr and the H and V sampling factors for each component, Y, Cb, and Cr, default to 2, 1, and 1, respectively (2 for both H and V of the Y component, etc.) in the Jpeg-6a library by the Independent Jpeg Group. While this does mean that the Y component will be twice the size of the other two components--giving it a higher resolution, the lower resolution components are quartered in size during compression in order to achieve this difference. Thus, the Cb and Cr components must be quadrupled in size during decompression.
For more info about the headers check out wikipedia's jpeg entry or I got the above info here.
I used a method similar to the code below which I got from this post at the sun forums:
import java.awt.Dimension;
import java.io.*;
public class JPEGDim {
public static Dimension getJPEGDimension(File f) throws IOException {
FileInputStream fis = new FileInputStream(f);
// check for SOI marker
if (fis.read() != 255 || fis.read() != 216)
throw new RuntimeException("SOI (Start Of Image) marker 0xff 0xd8 missing");
Dimension d = null;
while (fis.read() == 255) {
int marker = fis.read();
int len = fis.read() << 8 | fis.read();
if (marker == 192) {
fis.skip(1);
int height = fis.read() << 8 | fis.read();
int width = fis.read() << 8 | fis.read();
d = new Dimension(width, height);
break;
}
fis.skip(len - 2);
}
fis.close();
return d;
}
public static void main(String[] args) throws IOException {
System.out.println(getJPEGDimension(new File(args[0])));
}
}
You will have to use something like below
#menu ul{_x000D_
list-style: none;_x000D_
}_x000D_
#menu li{_x000D_
display: inline;_x000D_
}_x000D_
_x000D_
<div id="menu">_x000D_
<ul>_x000D_
<li>First menu item</li>_x000D_
<li>Second menu item</li>_x000D_
<li>Third menu item</li>_x000D_
</ul>_x000D_
</div>
_x000D_
Had this same issue after changing the PHP version from 5.6 to 7.3 (eaphp73). So what I did was I simply changed the version to alt-php74.
So what's the problem? Probably a plugin that relied on a certain PHP extension that wasn't available on eaphp73.
Before you touch any wordpress files, just try changing your site's PHP version. You can do this in the cPanel.
And if that doesn't work, go back into the cPanel and activate every PHP extension there is. And if your site starts working at this stage, then it's probably an extension it couldn't function without. Now slowly work backwards deactivating (one at a time) ONLY the extensions you just activated.
You should be able to figure out which extension was the required feature.
Can it be a plugin that's causing the issue? Certainly. Maybe the rogue plugin just wanted that extra extension.
If changing the PHP version, and juggling with the PHP extensions didn't work, then try renaming (which automatically deactivates) one plugin folder at a time.
YouTube resolutions and images
http://img.youtube.com/vi/<video-id>/<resolution><image>.jpg
Resolution
- lowest resolution
sd - Standard Definition
mq - Medium Quality
hq - High Quality
maxres - MAXimum RESolution
Image
default - Default image (1, 2, 3 shot from video, or custom uploaded)
1 - First shot from video
2 - Second shot from video
3 - Third shot from video
Use JSCRIPT.NET to get a library(dll) of the js . Then reference this dll in your .NET application and you are just there. DONE!
Uri path = Uri.fromFile(file );
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path , "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent );
}
catch (ActivityNotFoundException e) {
Toast.makeText(EmptyBlindDocumentShow.this,
"No Application available to viewPDF",
Toast.LENGTH_SHORT).show();
}
}
EventHandler
receives EventArgs
as a parameter. To resolve your problem, you can build your own MyEventArgs
.
public enum MyEvents
{
Event1
}
public class MyEventArgs : EventArgs
{
public MyEvents MyEvent { get; set; }
}
public static event EventHandler<MyEventArgs> EventTriggered;
public static void Trigger(MyEvents ev)
{
if (EventTriggered != null)
{
EventTriggered(null, new MyEventArgs { MyEvent = ev });
}
}
You can use xlrd.
From its documentation, you can read that dates are always stored as numbers; however, you can use xldate_as_tuple
to convert it to a python date.
Note: the version on the PyPI seems more up-to-date than the one available on xlrd's website.
If you want to delete all files whose names match a particular form, a wildcard (glob pattern) is the most straightforward solution. Some examples:
$ rm -f abc.log.* # Remove them all
$ rm -f abc.log.2012* # Remove all logs from 2012
$ rm -f abc.log.2012-0[123]* # Remove all files from the first quarter of 2012
Regular expressions are more powerful than wildcards; you can feed the output of grep
to rm -f
. For example, if some of the file names start with "abc.log"
and some with "ABC.log"
, grep
lets you do a case-insensitive match:
$ rm -f $(ls | grep -i '^abc\.log\.')
This will cause problems if any of the file names contain funny characters, including spaces. Be careful.
When I do this, I run the ls | grep ...
command first and check that it produces the output I want -- especially if I'm using rm -f
:
$ ls | grep -i '^abc\.log\.'
(check that the list is correct)
$ rm -f $(!!)
where !!
expands to the previous command. Or I can type up-arrow or Ctrl-P and edit the previous line to add the rm -f
command.
This assumes you're using the bash shell. Some other shells, particularly csh and tcsh and some older sh-derived shells, may not support the $(...)
syntax. You can use the equivalent backtick syntax:
$ rm -f `ls | grep -i '^abc\.log\.'`
The $(...)
syntax is easier to read, and if you're really ambitious it can be nested.
Finally, if the subset of files you want to delete can't be easily expressed with a regular expression, a trick I often use is to list the files to a temporary text file, then edit it:
$ ls > list
$ vi list # Use your favorite text editor
I can then edit the list
file manually, leaving only the files I want to remove, and then:
$ rm -f $(<list)
or
$ rm -f `cat list`
(Again, this assumes none of the file names contain funny characters, particularly spaces.)
Or, when editing the list
file, I can add rm -f
to the beginning of each line and then:
$ . ./list
or
$ source ./list
Editing the file is also an opportunity to add quotes where necessary, for example changing rm -f foo bar
to rm -f 'foo bar'
.
From a performance point of view, in python3.X
[i[0] for i in a]
and list(zip(*a))[0]
are equivalentlist(map(operator.itemgetter(0), a))
Code
import timeit
iterations = 100000
init_time = timeit.timeit('''a = [(i, u'abc') for i in range(1000)]''', number=iterations)/iterations
print(timeit.timeit('''a = [(i, u'abc') for i in range(1000)]\nb = [i[0] for i in a]''', number=iterations)/iterations - init_time)
print(timeit.timeit('''a = [(i, u'abc') for i in range(1000)]\nb = list(zip(*a))[0]''', number=iterations)/iterations - init_time)
output
3.491014136001468e-05
3.422205176000717e-05
This works at the moment (Oct. 2016), but I can't guarantee how long it will last:
https://www.facebook.com/sharer.php?caption=[caption]&description=[description]&u=[website]&picture=[image-url]