This might be completely off base, but can't you just copy the whole column into a new spreadsheet and then sort the column? I'm assuming that you don't need to maintain the order integrity.
Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:
Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:
Rory Gallagher Guitar
Gerry McAvoy Bass
Rod de'Ath Drums
Lou Martin Keyboards
Donkey Kong Sioux Self-Appointed Semi-official Stomper
Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)
Save the file as a CSV file.
Copy the contents of the CSV file to the clipboard
Verify that the "First row is column names" checkbox is checked
Paste the CSV data into the content area
Mash the "Convert CSV to JSON" button
With the data shown above, you will now have:
[
{
"MUSICIAN":"Rory Gallagher",
"INSTRUMENT":"Guitar"
},
{
"MUSICIAN":"Gerry McAvoy",
"INSTRUMENT":"Bass"
},
{
"MUSICIAN":"Rod D'Ath",
"INSTRUMENT":"Drums"
},
{
"MUSICIAN":"Lou Martin",
"INSTRUMENT":"Keyboards"
}
{
"MUSICIAN":"Donkey Kong Sioux",
"INSTRUMENT":"Self-Appointed Semi-Official Stomper"
}
]
With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.
Go here: http://jsonlint.com/
Paste the JSON into the content area
Pres the "Validate" button.
If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.
Data can be pulled into an excel from another excel through Workbook method or External reference or through Data Import facility.
If you want to read or even if you want to update another excel workbook, these methods can be used. We may not depend only on VBA for this.
For more info on these techniques, please click here to refer the article
Assuming employee numbers are in the first column and their names are in the second:
=VLOOKUP(A1, Sheet2!A:B, 2,false)
Nested if's in Excel Are ugly:
=If(G2 < 1, .1, IF(G2 < 5,.15,if(G2 < 15,.2,if(G2 < 30,.5,if(G2 < 100,.1,1.3)))))
That should cover it.
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int main ()
{
char *tmp = (char *)malloc(128);
int n=sprintf(tmp, "Hello from Chile.");
string tmp_str = tmp;
cout << *tmp << " : is a char array beginning with " <<n <<" chars long\n" << endl;
cout << tmp_str << " : is a string with " <<n <<" chars long\n" << endl;
free(tmp);
return 0;
}
OUT:
H : is a char array beginning with 17 chars long
Hello from Chile. :is a string with 17 chars long
I did it in simple way using phpmyadmin. I followed the steps by @Farhan but all data were eltered in single column. How I did:
This depends entirely on the JavaScript environment. Please elaborate.
For example, in Windows Scripting, you do things like:
var shell = WScript.CreateObject("WScript.Shell");
shell.Run("command here");
with open('file.txt', 'r') as searchfile:
for line in searchfile:
if 'searchphrase' in line:
print line
With apologies to senderle who I blatantly copied.
Both the annotations behave exactly in same manner.
Only 2 special characters '!' and '@' are accepted by the annotations @PathVariable and @RequestParam.
To check and confirm the behavior I have created a spring boot application that contains only 1 controller.
@RestController
public class Controller
{
@GetMapping("/pvar/{pdata}")
public @ResponseBody String testPathVariable(@PathVariable(name="pdata") String pathdata)
{
return pathdata;
}
@GetMapping("/rpvar")
public @ResponseBody String testRequestParam(@RequestParam("param") String paramdata)
{
return paramdata;
}
}
Hitting following Requests I got the same response:
!@ was received as response in both the requests
You have several options for iterating over a dictionary.
If you iterate over the dictionary itself (for team in league
), you will be iterating over the keys of the dictionary. When looping with a for loop, the behavior will be the same whether you loop over the dict (league
) itself, or league.keys()
:
for team in league.keys():
runs_scored, runs_allowed = map(float, league[team])
You can also iterate over both the keys and the values at once by iterating over league.items()
:
for team, runs in league.items():
runs_scored, runs_allowed = map(float, runs)
You can even perform your tuple unpacking while iterating:
for team, (runs_scored, runs_allowed) in league.items():
runs_scored = float(runs_scored)
runs_allowed = float(runs_allowed)
Try this.
Here is the service part.
[ServiceContract]
public interface IService
{
[OperationContract]
void HelloWorld();
}
public class Service : IService
{
public void HelloWorld()
{
//Hello World
}
}
Here is the Proxy
public class ServiceProxy : ClientBase<IService>
{
public ServiceProxy()
: base(new ServiceEndpoint(ContractDescription.GetContract(typeof(IService)),
new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyAppNameThatNobodyElseWillUse/helloservice")))
{
}
public void InvokeHelloWorld()
{
Channel.HelloWorld();
}
}
And here is the service hosting part.
var serviceHost = new ServiceHost
(typeof(Service), new Uri[] { new Uri("net.pipe://localhost/MyAppNameThatNobodyElseWillUse") });
serviceHost.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "helloservice");
serviceHost.Open();
Console.WriteLine("Service started. Available in following endpoints");
foreach (var serviceEndpoint in serviceHost.Description.Endpoints)
{
Console.WriteLine(serviceEndpoint.ListenUri.AbsoluteUri);
}
Here's a a couple of useful link that I found when I started with JNI
http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html
concerning your problem you can use this
JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)
{
const char *nativeString = env->GetStringUTFChars(javaString, 0);
// use your string
env->ReleaseStringUTFChars(javaString, nativeString);
}
Some the answers here are massively elaborate. The simplest option I've found is (from: http://norvig.com/python-iaq.html):
class Struct:
"A structure that can have any fields defined."
def __init__(self, **entries): self.__dict__.update(entries)
Initialising:
>>> options = Struct(answer=42, linelen=80, font='courier')
>>> options.answer
42
adding more:
>>> options.cat = "dog"
>>> options.cat
dog
edit: Sorry didn't see this example already further down.
This is a good overview:
http://reference.jumpingmonkey.org/programming_languages/objective-c/types.html
or run this code:
32 bit process:
NSLog(@"Primitive sizes:");
NSLog(@"The size of a char is: %d.", sizeof(char));
NSLog(@"The size of short is: %d.", sizeof(short));
NSLog(@"The size of int is: %d.", sizeof(int));
NSLog(@"The size of long is: %d.", sizeof(long));
NSLog(@"The size of long long is: %d.", sizeof(long long));
NSLog(@"The size of a unsigned char is: %d.", sizeof(unsigned char));
NSLog(@"The size of unsigned short is: %d.", sizeof(unsigned short));
NSLog(@"The size of unsigned int is: %d.", sizeof(unsigned int));
NSLog(@"The size of unsigned long is: %d.", sizeof(unsigned long));
NSLog(@"The size of unsigned long long is: %d.", sizeof(unsigned long long));
NSLog(@"The size of a float is: %d.", sizeof(float));
NSLog(@"The size of a double is %d.", sizeof(double));
NSLog(@"Ranges:");
NSLog(@"CHAR_MIN: %c", CHAR_MIN);
NSLog(@"CHAR_MAX: %c", CHAR_MAX);
NSLog(@"SHRT_MIN: %hi", SHRT_MIN); // signed short int
NSLog(@"SHRT_MAX: %hi", SHRT_MAX);
NSLog(@"INT_MIN: %i", INT_MIN);
NSLog(@"INT_MAX: %i", INT_MAX);
NSLog(@"LONG_MIN: %li", LONG_MIN); // signed long int
NSLog(@"LONG_MAX: %li", LONG_MAX);
NSLog(@"ULONG_MAX: %lu", ULONG_MAX); // unsigned long int
NSLog(@"LLONG_MIN: %lli", LLONG_MIN); // signed long long int
NSLog(@"LLONG_MAX: %lli", LLONG_MAX);
NSLog(@"ULLONG_MAX: %llu", ULLONG_MAX); // unsigned long long int
When run on an iPhone 3GS (iPod Touch and older iPhones should yield the same result) you get:
Primitive sizes:
The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 4.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 4.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN: -128
CHAR_MAX: 127
SHRT_MIN: -32768
SHRT_MAX: 32767
INT_MIN: -2147483648
INT_MAX: 2147483647
LONG_MIN: -2147483648
LONG_MAX: 2147483647
ULONG_MAX: 4294967295
LLONG_MIN: -9223372036854775808
LLONG_MAX: 9223372036854775807
ULLONG_MAX: 18446744073709551615
64 bit process:
The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 8.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 8.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN: -128
CHAR_MAX: 127
SHRT_MIN: -32768
SHRT_MAX: 32767
INT_MIN: -2147483648
INT_MAX: 2147483647
LONG_MIN: -9223372036854775808
LONG_MAX: 9223372036854775807
ULONG_MAX: 18446744073709551615
LLONG_MIN: -9223372036854775808
LLONG_MAX: 9223372036854775807
ULLONG_MAX: 18446744073709551615
In Linq-to-SQL if you try to get the first element on a query with no results you will get sequence contains no elements
error. I can assure you that the mentioned error is not equal to object reference not set to an instance of an object
.
in conclusion no, it won't return null since null can't say sequence contains no elements
it will always say object reference not set to an instance of an object
;)
To obtain the id of the documents in a collection, you must use snapshotChanges()
this.shirtCollection = afs.collection<Shirt>('shirts');
// .snapshotChanges() returns a DocumentChangeAction[], which contains
// a lot of information about "what happened" with each change. If you want to
// get the data and the id use the map operator.
this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Shirt;
const id = a.payload.doc.id;
return { id, ...data };
});
});
Documentation https://github.com/angular/angularfire2/blob/7eb3e51022c7381dfc94ffb9e12555065f060639/docs/firestore/collections.md#example
Stream s;
int len = (int)s.Length;
byte[] b = new byte[len];
int pos = 0;
while((r = s.Read(b, pos, len - pos)) > 0) {
pos += r;
}
A slightly more complicated solution is necesary is s.Length
exceeds Int32.MaxValue
. But if you need to read a stream that large into memory, you might want to think about a different approach to your problem.
Edit: If your stream does not support the Length
property, modify using Earwicker's workaround.
public static class StreamExtensions {
// Credit to Earwicker
public static void CopyStream(this Stream input, Stream output) {
byte[] b = new byte[32768];
int r;
while ((r = input.Read(b, 0, b.Length)) > 0) {
output.Write(b, 0, r);
}
}
}
[...]
Stream s;
MemoryStream ms = new MemoryStream();
s.CopyStream(ms);
byte[] b = ms.GetBuffer();
Hi first give an id to the select as
<select id=theid>
<option value="test">label </option>
</select>
then you can call the selected label like that:
jQuery('#theid option:selected').text()
In my case I'm doing it like this:
module SayHi {
export default () => { console.log("Hi"); }
}
new SayHi();
or this, I did not implement the array comparison so you will also have some fun :)
public bool CompareTables(DataTable a, DataTable b)
{
if(a.Rows.Count != b.Rows.Count)
{
// different size means different tables
return false;
}
for(int rowIndex=0; rowIndex<a.Rows.Count; ++rowIndex)
{
if(!arraysHaveSameContent(a.Rows[rowIndex].ItemArray, b.Rows[rowIndex].ItemArray,))
{
return false;
}
}
// Tables have same data
return true;
}
private bool arraysHaveSameContent(object[] a, object[] b)
{
// Here your super cool method to compare the two arrays with LINQ,
// or if you are a loser do it with a for loop :D
}
Sometimes we need a single way to check it. typeof not working for date etc. So I made it easy by
Date.prototype.getType() { return "date"; }
Also for Number
, String
, Boolean
etc. we often need to check the type in a single way...
There are 3 access specifiers
for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:
Public - The members declared as Public are accessible from outside the Class through an object of the class.
Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.
Private - These members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:
class MyClass
{
public:
int a;
protected:
int b;
private:
int c;
};
int main()
{
MyClass obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, gives compiler error
obj.c = 30; //Not Allowed, gives compiler error
}
Inheritance in C++ can be one of the following types:
Private
Inheritance Public
Inheritance Protected
inheritance Here are the member access rules with respect to each of these:
First and most important rule
Private
members of a class are never accessible from anywhere except the members of the same class.
All
Public
members of the Base Class becomePublic
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.
Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:public Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomePrivate
Members of the Derived class &
AllProtected
members of the Base Class becomePrivate
Members of the Derived Class.
An code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:private Base //Not mentioning private is OK because for classes it defaults to private
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Not Allowed, Compiler Error, a is private member of Derived now
b = 20; //Not Allowed, Compiler Error, b is private member of Derived now
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomeProtected
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
A Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:protected Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
b = 20; //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
Remember the same access rules apply to the classes and members down the inheritance hierarchy.
- Access Specification is per-Class not per-Object
Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.
- A Derived class can only access members of its own Base class
Consider the following code example:
class Myclass
{
protected:
int x;
};
class derived : public Myclass
{
public:
void f( Myclass& obj )
{
obj.x = 5;
}
};
int main()
{
return 0;
}
It gives an compilation error:
prog.cpp:4: error: ‘int Myclass::x’ is protected
Because the derived class can only access members of its own Base Class. Note that the object obj
being passed here is no way related to the derived
class function in which it is being accessed, it is an altogether different object and hence derived
member function cannot access its members.
friend
? How does friend
affect access specification rules?You can declare a function or class as friend
of another class. When you do so the access specification rules do not apply to the friend
ed class/function. The class or function can access all the members of that particular class.
So do
friend
s break Encapsulation?
No they don't, On the contrary they enhance Encapsulation!
friend
ship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private
or protected
members but You do not want everyone to have access by using the public
access specifier then you should use friend
ship.
File file = fileChooser.getSelectedFile();
String selected = fc.getSelectedFile().getAbsolutePath();
File srcDir = new File(selected);
FileInputStream fii;
FileOutputStream fio;
try {
fii = new FileInputStream(srcDir);
fio = new FileOutputStream("C:\\LOvE.txt");
byte [] b=new byte[1024];
int i=0;
try {
while ((fii.read(b)) > 0)
{
System.out.println(b);
fio.write(b);
}
fii.close();
fio.close();
Here's my current solution to run any code remotely on a given machine or list of machines asynchronously with logging, too!
@echo off
:: by Ralph Buchfelder, thanks to Mark Russinovich and Rob van der Woude for their work!
:: requires PsExec.exe to be in the same directory (download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx)
:: troubleshoot remote commands with PsExec arguments -i or -s if neccessary (see http://forum.sysinternals.com/pstools_forum8.html)
:: will run *in parallel* on a list of remote pcs (if given); to run serially please remove 'START "" CMD.EXE /C' from the psexec call
:: help
if '%1' =='-h' (
echo.
echo %~n0
echo.
echo Runs a command on one or many remote machines. If no input parameters
echo are given you will be asked for a target remote machine.
echo.
echo You will be prompted for remote credentials with elevated privileges.
echo.
echo UNC paths and local paths can be supplied.
echo Commands will be executed on the remote side just the way you typed
echo them, so be sure to mind extensions and the path variable!
echo.
echo Please note that PsExec.exe must be allowed on remote machines, i.e.
echo not blocked by firewall or antivirus solutions.
echo.
echo Syntax: %~n0 [^<inputfile^>]
echo.
echo inputfile = a plain text file ^(one hostname or ip address per line^)
echo.
echo.
echo Example:
echo %~n0 mylist.txt
exit /b 0
)
:checkAdmin
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' neq '0' (
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
)
set ADMINTESTDIR=%WINDIR%\System32\Test_%RANDOM%
mkdir "%ADMINTESTDIR%" 2>NUL
if errorlevel 1 (
cls
echo ERROR: This script requires elevated privileges!
echo.
echo Launch by Right-Click / Run as Administrator ...
pause
exit /b 1
) else (
rd /s /q "%ADMINTESTDIR%"
echo Running with elevated privileges...
)
echo.
:checkRequirements
if not exist "%~dp0PsExec.exe" (
echo PsExec.exe from Sysinternals/Microsoft not found
echo in %~dp0
echo.
echo Download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx
echo.
pause
exit /B
)
:environment
setlocal
echo.
echo %~n0
echo _____________________________
echo.
echo Working directory: %cd%\
echo Script directory: %~dp0
echo.
SET /P REMOTE_USER=Domain\Administrator :
SET "psCommand=powershell -Command "$pword = read-host 'Kennwort' -AsSecureString ; ^
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set REMOTE_PASS=%%p
if NOT DEFINED REMOTE_PASS SET /P REMOTE_PASS=Password :
echo.
if '%1' =='' goto menu
SET REMOTE_LIST=%1
:inputMultipleTargets
if not exist %REMOTE_LIST% (
echo File %REMOTE_LIST% not found
goto menu
)
type %REMOTE_LIST% >nul
if '%errorlevel%' neq '0' (
echo Access denied %REMOTE_LIST%
goto menu
)
set batchProcessing=true
echo Batch processing: %REMOTE_LIST% ...
ping -n 2 127.0.0.1 >nul
goto runOnce
:menu
if exist "%~dp0last.computer" set /p LAST_COMPUTER=<"%~dp0last.computer"
if exist "%~dp0last.listing" set /p LAST_LISTING=<"%~dp0last.listing"
if exist "%~dp0last.directory" set /p LAST_DIRECTORY=<"%~dp0last.directory"
if exist "%~dp0last.command" set /p LAST_COMMAND=<"%~dp0last.command"
if exist "%~dp0last.timestamp" set /p LAST_TIMESTAMP=<"%~dp0last.timestamp"
echo.
echo.
echo (1) select target computer [default]
echo (2) select multiple computers
echo -----------------------------------
echo last target : %LAST_COMPUTER%
echo last listing: %LAST_LISTING%
echo last path : %LAST_DIRECTORY%
echo last command: %LAST_COMMAND%
echo last run : %LAST_TIMESTAMP%
echo -----------------------------------
echo (0) exit
echo.
echo ENTER your choice.
echo.
echo.
:mychoice
SET /P mychoice=(0, 1, ...):
if NOT DEFINED mychoice goto promptSingleTarget
if "%mychoice%"=="1" goto promptSingleTarget
if "%mychoice%"=="2" goto promptMultipleTargets
if "%mychoice%"=="0" goto end
goto mychoice
:promptMultipleTargets
echo.
echo Please provide an input file
echo [one IP address or hostname per line]
SET /P REMOTE_LIST=Filename :
goto inputMultipleTargets
:promptSingleTarget
SET batchProcessing=
echo.
echo Please provide a hostname
SET /P REMOTE_COMPUTER=Target computer :
goto runOnce
:runOnce
cls
echo Note: Paths are mandatory for CMD-commands (e.g. dir,copy) to work!
echo Paths are provided on the remote machine via PUSHD.
echo.
SET /P REMOTE_PATH=UNC-Path or folder :
SET /P REMOTE_CMD=Command with params:
SET REMOTE_TIMESTAMP=%DATE% %TIME:~0,8%
echo.
echo Remote command starting (%REMOTE_PATH%\%REMOTE_CMD%) on %REMOTE_TIMESTAMP%...
if not defined batchProcessing goto runOnceSingle
:runOnceMulti
REM do for each line; this circumvents PsExec's @file to have stdouts separately
SET REMOTE_LOG=%~dp0\log\%REMOTE_LIST%
if not exist %REMOTE_LOG% md %REMOTE_LOG%
for /F "tokens=*" %%A in (%REMOTE_LIST%) do (
if "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "%REMOTE_CMD%" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
if not "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
)
goto restart
:runOnceSingle
SET REMOTE_LOG=%~dp0\log
if not exist %REMOTE_LOG% md %REMOTE_LOG%
if "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "%REMOTE_CMD%" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
if not "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
goto restart
:restart
echo.
echo.
echo Batch completed. Finished with last errorlevel %errorlevel% .
echo All outputs have been saved to %~dp0log\%REMOTE_TIMESTAMP%\.
echo %REMOTE_PATH% >"%~dp0last.directory"
echo %REMOTE_CMD% >"%~dp0last.command"
echo %REMOTE_LIST% >"%~dp0last.listing"
echo %REMOTE_COMPUTER% >"%~dp0last.computer"
echo %REMOTE_TIMESTAMP% >"%~dp0last.timestamp"
SET REMOTE_PATH=
SET REMOTE_CMD=
SET REMOTE_LIST=
SET REMOTE_COMPUTER=
SET REMOTE_LOG=
SET REMOTE_TIMESTAMP=
ping -n 2 127.0.0.1 >nul
goto menu
:end
SET REMOTE_USER=
SET REMOTE_PASS=
If you are using jQuery, one option that is nice (especially for complicated situations) is to use jQuery's extend method.
function foo(options) {
default_options = {
timeout : 1000,
callback : function(){},
some_number : 50,
some_text : "hello world"
};
options = $.extend({}, default_options, options);
}
If you call the function then like this:
foo({timeout : 500});
The options variable would then be:
{
timeout : 500,
callback : function(){},
some_number : 50,
some_text : "hello world"
};
Try this:
import tkinter as tk
from PIL import ImageTk, Image
#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')
path = "Aaron.jpg"
#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img = ImageTk.PhotoImage(Image.open(path))
#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)
#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")
#Start the GUI
window.mainloop()
Related docs: ImageTk Module, Tkinter Label Widget, Tkinter Pack Geometry Manager
The root.after(ms, func) is the method you need to use. Just call it once before the mainloop starts and reschedule it inside the bound function every time it is called. Here is an example:
from tkinter import *
import time
def update_clock():
timer_label.config(text=time.strftime('%H:%M:%S',time.localtime()),
font='Times 25') # change the text of the time_label according to the current time
root.after(100, update_clock) # reschedule update_clock function to update time_label every 100 ms
root = Tk() # create the root window
timer_label = Label(root, justify='center') # create the label for timer
timer_label.pack() # show the timer_label using pack geometry manager
root.after(0, update_clock) # schedule update_clock function first call
root.mainloop() # start the root window mainloop
Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:
<Router>
<Route path="/" component={App}>
<Route path="page1" component={Page1} />
<Route path="page2" component={Page2} />
</Route>
<Route path="/login" component={Login} />
</Router>
And the other components would look something like this:
var NavBar = React.createClass({
render() {
return (
<div>
<ul>
<a onClick={() => history.push('page1') }>Page 1</a>
<a onClick={() => history.push('page2') }>Page 2</a>
</ul>
</div>
)
}
});
var App = React.createClass({
render() {
return (
<div>
<NavBar />
<div>Other Content</div>
{this.props.children}
</div>
)
}
});
A bin file is just the bits and bytes that go into the rom or a particular address from which you will run the program. You can take this data and load it directly as is, you need to know what the base address is though as that is normally not in there.
An elf file contains the bin information but it is surrounded by lots of other information, possible debug info, symbols, can distinguish code from data within the binary. Allows for more than one chunk of binary data (when you dump one of these to a bin you get one big bin file with fill data to pad it to the next block). Tells you how much binary you have and how much bss data is there that wants to be initialised to zeros (gnu tools have problems creating bin files correctly).
The elf file format is a standard, arm publishes its enhancements/variations on the standard. I recommend everyone writes an elf parsing program to understand what is in there, dont bother with a library, it is quite simple to just use the information and structures in the spec. Helps to overcome gnu problems in general creating .bin files as well as debugging linker scripts and other things that can help to mess up your bin or elf output.
It's usually implemented as floor(value + 0.5)
.
Edit: and it's probably not called round since there are at least three rounding algorithms I know of: round to zero, round to closest integer, and banker's rounding. You are asking for round to closest integer.
By experience I say that you need to check if the server is running first and then try configuring MySQL. The last solution is to re-install MySQL.
It's entirely likely that a large portion of the developer base comes from a Java background where using ==
to compare strings is wrong and doesn't work.
In C# there's no (practical) difference (for strings) as long as they are typed as string.
If they are typed as object
or T
then see other answers here that talk about generic methods or operator overloading as there you definitely want to use the Equals method.
$myFile = "4-21-11.txt";
$fh = fopen($myFile, 'r');
while(!feof($fh))
{
$data[] = fgets($fh);
//Do whatever you want with the data in here
//This feeds the file into an array line by line
}
fclose($fh);
Your code is correct. I tested:
r = requests.get("http://www.google.com")
print(r.content)
And it returned plenty of content. Check the url, try "http://www.google.com". Cheers!
I have succesfully used ;
Dim regexString = New stringbuilder
With regexString
.Append("(?<h>^[\d]+[ ])(?<s>.+$)|") 'find the 2013 1st ambonstreet
.Append("(?<s>^.*?)(?<h>[ ][\d]+[ ])(?<e>[\D]+$)|") 'find the 1-7-4 Dual Ampstreet 130 A
.Append("(?<s>^[\D]+[ ])(?<h>[\d]+)(?<e>.*?$)|") 'find the Terheydenlaan 320 B3
.Append("(?<s>^.*?)(?<h>\d*?$)") 'find the 245e oosterkade 9
End With
Dim Address As Match = Regex.Match(DataRow("customerAddressLine1"), regexString.ToString(), RegexOptions.Multiline)
If Not String.IsNullOrEmpty(Address.Groups("s").Value) Then StreetName = Address.Groups("s").Value
If Not String.IsNullOrEmpty(Address.Groups("h").Value) Then HouseNumber = Address.Groups("h").Value
If Not String.IsNullOrEmpty(Address.Groups("e").Value) Then Extension = Address.Groups("e").Value
The regex will attempt to find a result, if there is none, it move to the next alternative. If no result is found, none of the 4 formats where present.
I believe the default precision is 38, default scale is zero. However the actual size of an instance of this column, is dynamic. It will take as much space as needed to store the value, or max 21 bytes.
If you have access to JavaScript, you can create an element and read its computed style.
function defaultValueOfCssPropertyForElement(cssPropertyName, elementTagName, opt_pseudoElement) {
var pseudoElement = opt_pseudoElement || null;
var element = document.createElement(elementTagName);
document.body.appendChild(element);
var computedStyle = getComputedStyle(element, pseudoElement)[cssPropertyName];
element.remove();
return computedStyle;
}
// Usage:
defaultValueOfCssPropertyForElement('display', 'div'); // Output: 'block'
defaultValueOfCssPropertyForElement('content', 'div', ':after'); // Output: 'none'
I was wondering, why they didnt provide in jquery itself, so i made a few changes in jquery file ,,, here are the changed code block:
original Code block:
post: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
Changed Code block:
post: function (url, data, callback, failcallback, type) {
if (type === undefined || type === null) {
if (!jQuery.isFunction(failcallback)) {
type=failcallback
}
else if (!jQuery.isFunction(callback)) {
type = callback
}
}
if (jQuery.isFunction(data) && jQuery.isFunction(callback)) {
failcallback = callback;
}
// shift arguments if data argument was omited
if (jQuery.isFunction(data)) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
error:failcallback,
dataType: type
});
},
This should help the one trying to catch error on $.Post in jquery.
Updated: Or there is another way to do this is :
$.post(url,{},function(res){
//To do write if call is successful
}).error(function(p1,p2,p3){
//To do Write if call is failed
});
I use XAMPP and had the same error. I used Paul Gobée solution above and it worked for me. I navigated to C:\xampp\mysql\bin\mysqld-debug.exe
and upon starting the .exe
my Windows Firewall popped up asking for permission. Once I allowed it, it worked fine. I would have commented under his post but I do not have that much rep yet... sry! Just wanted to let everyone know this worked for me as well.
Maybe you can use TextFX plugins
In TextFX, go to textfx edit ? delete blank lines
This has happened to me also, after undating to IOS11 on my iPhone. When I try to connect to the corporate network it bring up the corporate cert and says it isn't trusted. I press the 'trust' button and the connection fails and the cert does not appear in the trusted certs list.
In HTML
<SELECT NAME="Testing" id="Testing">
<OPTION VALUE="1,2010"> One
<OPTION VALUE="2,2122"> Two
<OPTION VALUE="3,0"> Three
</SELECT>
For JS
var valueOne= $('#Testing').val().split(',')[0];
var valueTwo =$('#Testing').val().split(',')[1];
console.log(valueOne); //output 1
console.log(valueTwo); //output 2010
OR FOR PHP
$selectedValue= explode(',', $value);
$valueOne= $exploded_value[0]; //output 1
$valueTwo= $exploded_value[1]; //output 2010
Custom Data attribute in HTML5
Would like to quote Ian's comment in my answer:
It's just an attribute (a valid one) on the element that you can use to store data/info about it.
This code then retrieves it later in the event handler, and uses it to find the target output element. It effectively stores the class of the div where its text should be outputted.
reactid
is just a suffix, you can have any name here eg: data-Ayman
.
If you want to find the difference check the fiddles in this SO answer and comment.
A complete example of how this could be done. To avoid having to write client-side validation scripts, the existing ValidationType = "range" has been used.
public class MinValueAttribute : ValidationAttribute, IClientValidatable
{
private readonly double _minValue;
public MinValueAttribute(double minValue)
{
_minValue = minValue;
ErrorMessage = "Enter a value greater than or equal to " + _minValue;
}
public MinValueAttribute(int minValue)
{
_minValue = minValue;
ErrorMessage = "Enter a value greater than or equal to " + _minValue;
}
public override bool IsValid(object value)
{
return Convert.ToDouble(value) >= _minValue;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = ErrorMessage;
rule.ValidationParameters.Add("min", _minValue);
rule.ValidationParameters.Add("max", Double.MaxValue);
rule.ValidationType = "range";
yield return rule;
}
}
You could get CoreUtils from GnuWin32, which is a collection of standard unix tools, ported to Windows.
It, among other things, contains head.
I feel like there should be a no javascript solution, but how is this?
$(window).resize(function() {
$('#content').height($(window).height() - 46);
});
$(window).trigger('resize');
You need nunique
:
df = df.groupby('domain')['ID'].nunique()
print (df)
domain
'facebook.com' 1
'google.com' 1
'twitter.com' 2
'vk.com' 3
Name: ID, dtype: int64
If you need to strip
'
characters:
df = df.ID.groupby([df.domain.str.strip("'")]).nunique()
print (df)
domain
facebook.com 1
google.com 1
twitter.com 2
vk.com 3
Name: ID, dtype: int64
Or as Jon Clements commented:
df.groupby(df.domain.str.strip("'"))['ID'].nunique()
You can retain the column name like this:
df = df.groupby(by='domain', as_index=False).agg({'ID': pd.Series.nunique})
print(df)
domain ID
0 fb 1
1 ggl 1
2 twitter 2
3 vk 3
The difference is that nunique()
returns a Series and agg()
returns a DataFrame.
I had a similar need, except I needed to do math on the "numbers" as well. I took some of the suggestions here and created a class that will do all this fun stuff. It allows for any unicode character to be used to represent a number and it works with decimals too.
This class is pretty easy to use. Just create a number as a type of New BaseNumber
, set a few properties, and your off. The routines take care of switching between base 10 and base x automatically and the value you set is preserved in the base you set it in, so no accuracy is lost (until conversion that is, but even then precision loss should be very minimal since this routine uses Double
and Long
where ever possible).
I can't command on the speed of this routine. It is probably quite slow, so I'm not sure if it will suit the needs of the one who asked the question, but it certain is flexible, so hopefully someone else can use this.
For anyone else that may need this code for calculating the next column in Excel, I will include the looping code I used that leverages this class.
Public Class BaseNumber
Private _CharacterArray As List(Of Char)
Private _BaseXNumber As String
Private _Base10Number As Double?
Private NumberBaseLow As Integer
Private NumberBaseHigh As Integer
Private DecimalSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
Private GroupSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator
Public Sub UseCapsLetters()
'http://unicodelookup.com
TrySetBaseSet(65, 90)
End Sub
Public Function GetCharacterArray() As List(Of Char)
Return _CharacterArray
End Function
Public Sub SetCharacterArray(CharacterArray As String)
_CharacterArray = New List(Of Char)
_CharacterArray.AddRange(CharacterArray.ToList)
TrySetBaseSet(_CharacterArray)
End Sub
Public Sub SetCharacterArray(CharacterArray As List(Of Char))
_CharacterArray = CharacterArray
TrySetBaseSet(_CharacterArray)
End Sub
Public Sub SetNumber(Value As String)
_BaseXNumber = Value
_Base10Number = Nothing
End Sub
Public Sub SetNumber(Value As Double)
_Base10Number = Value
_BaseXNumber = Nothing
End Sub
Public Function GetBaseXNumber() As String
If _BaseXNumber IsNot Nothing Then
Return _BaseXNumber
Else
Return ToBaseString()
End If
End Function
Public Function GetBase10Number() As Double
If _Base10Number IsNot Nothing Then
Return _Base10Number
Else
Return ToBase10()
End If
End Function
Private Sub TrySetBaseSet(Values As List(Of Char))
For Each value As Char In _BaseXNumber
If Not Values.Contains(value) Then
Throw New ArgumentOutOfRangeException("The string has a value, " & value & ", not contained in the selected 'base' set.")
_CharacterArray.Clear()
DetermineNumberBase()
End If
Next
_CharacterArray = Values
End Sub
Private Sub TrySetBaseSet(LowValue As Integer, HighValue As Integer)
Dim HighLow As KeyValuePair(Of Integer, Integer) = GetHighLow()
If HighLow.Key < LowValue OrElse HighLow.Value > HighValue Then
Throw New ArgumentOutOfRangeException("The string has a value not contained in the selected 'base' set.")
_CharacterArray.Clear()
DetermineNumberBase()
End If
NumberBaseLow = LowValue
NumberBaseHigh = HighValue
End Sub
Private Function GetHighLow(Optional Values As List(Of Char) = Nothing) As KeyValuePair(Of Integer, Integer)
If Values Is Nothing Then
Values = _BaseXNumber.ToList
End If
Dim lowestValue As Integer = Convert.ToInt32(Values(0))
Dim highestValue As Integer = Convert.ToInt32(Values(0))
Dim currentValue As Integer
For Each value As Char In Values
If value <> DecimalSeparator AndAlso value <> GroupSeparator Then
currentValue = Convert.ToInt32(value)
If currentValue > highestValue Then
highestValue = currentValue
End If
If currentValue < lowestValue Then
currentValue = lowestValue
End If
End If
Next
Return New KeyValuePair(Of Integer, Integer)(lowestValue, highestValue)
End Function
Public Sub New(BaseXNumber As String)
_BaseXNumber = BaseXNumber
DetermineNumberBase()
End Sub
Public Sub New(BaseXNumber As String, NumberBase As Integer)
Me.New(BaseXNumber, Convert.ToInt32("0"c), NumberBase)
End Sub
Public Sub New(BaseXNumber As String, NumberBaseLow As Integer, NumberBaseHigh As Integer)
_BaseXNumber = BaseXNumber
Me.NumberBaseLow = NumberBaseLow
Me.NumberBaseHigh = NumberBaseHigh
End Sub
Public Sub New(Base10Number As Double)
_Base10Number = Base10Number
End Sub
Private Sub DetermineNumberBase()
Dim highestValue As Integer
Dim currentValue As Integer
For Each value As Char In _BaseXNumber
currentValue = Convert.ToInt32(value)
If currentValue > highestValue Then
highestValue = currentValue
End If
Next
NumberBaseHigh = highestValue
NumberBaseLow = Convert.ToInt32("0"c) 'assume 0 is the lowest
End Sub
Private Function ToBaseString() As String
Dim Base10Number As Double = _Base10Number
Dim intPart As Long = Math.Truncate(Base10Number)
Dim fracPart As Long = (Base10Number - intPart).ToString.Replace(DecimalSeparator, "")
Dim intPartString As String = ConvertIntToString(intPart)
Dim fracPartString As String = If(fracPart <> 0, DecimalSeparator & ConvertIntToString(fracPart), "")
Return intPartString & fracPartString
End Function
Private Function ToBase10() As Double
Dim intPartString As String = _BaseXNumber.Split(DecimalSeparator)(0).Replace(GroupSeparator, "")
Dim fracPartString As String = If(_BaseXNumber.Contains(DecimalSeparator), _BaseXNumber.Split(DecimalSeparator)(1), "")
Dim intPart As Long = ConvertStringToInt(intPartString)
Dim fracPartNumerator As Long = ConvertStringToInt(fracPartString)
Dim fracPartDenominator As Long = ConvertStringToInt(GetEncodedChar(1) & String.Join("", Enumerable.Repeat(GetEncodedChar(0), fracPartString.ToString.Length)))
Return Convert.ToDouble(intPart + fracPartNumerator / fracPartDenominator)
End Function
Private Function ConvertIntToString(ValueToConvert As Long) As String
Dim result As String = String.Empty
Dim targetBase As Long = GetEncodingCharsLength()
Do
result = GetEncodedChar(ValueToConvert Mod targetBase) & result
ValueToConvert = ValueToConvert \ targetBase
Loop While ValueToConvert > 0
Return result
End Function
Private Function ConvertStringToInt(ValueToConvert As String) As Long
Dim result As Long
Dim targetBase As Integer = GetEncodingCharsLength()
Dim startBase As Integer = GetEncodingCharsStartBase()
Dim value As Char
For x As Integer = 0 To ValueToConvert.Length - 1
value = ValueToConvert(x)
result += GetDecodedChar(value) * Convert.ToInt32(Math.Pow(GetEncodingCharsLength, ValueToConvert.Length - (x + 1)))
Next
Return result
End Function
Private Function GetEncodedChar(index As Integer) As Char
If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
Return _CharacterArray(index)
Else
Return Convert.ToChar(index + NumberBaseLow)
End If
End Function
Private Function GetDecodedChar(character As Char) As Integer
If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
Return _CharacterArray.IndexOf(character)
Else
Return Convert.ToInt32(character) - NumberBaseLow
End If
End Function
Private Function GetEncodingCharsLength() As Integer
If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
Return _CharacterArray.Count
Else
Return NumberBaseHigh - NumberBaseLow + 1
End If
End Function
Private Function GetEncodingCharsStartBase() As Integer
If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
Return GetHighLow.Key
Else
Return NumberBaseLow
End If
End Function
End Class
And now for the code to loop through Excel columns:
Public Function GetColumnList(DataSheetID As String) As List(Of String)
Dim workingColumn As New BaseNumber("A")
workingColumn.SetCharacterArray("@ABCDEFGHIJKLMNOPQRSTUVWXYZ")
Dim listOfPopulatedColumns As New List(Of String)
Dim countOfEmptyColumns As Integer
Dim colHasData As Boolean
Dim cellHasData As Boolean
Do
colHasData = True
cellHasData = False
For r As Integer = 1 To GetMaxRow(DataSheetID)
cellHasData = cellHasData Or XLGetCellValue(DataSheetID, workingColumn.GetBaseXNumber & r) <> ""
Next
colHasData = colHasData And cellHasData
'keep trying until we get 4 empty columns in a row
If colHasData Then
listOfPopulatedColumns.Add(workingColumn.GetBaseXNumber)
countOfEmptyColumns = 0
Else
countOfEmptyColumns += 1
End If
'we are already starting with column A, so increment after we check column A
Do
workingColumn.SetNumber(workingColumn.GetBase10Number + 1)
Loop Until Not workingColumn.GetBaseXNumber.Contains("@")
Loop Until countOfEmptyColumns > 3
Return listOfPopulatedColumns
End Function
You'll note the important part of the Excel part is that 0 is identified by a @ in the re-based number. So I just filter out all the numbers that have an @ in them and I get the proper sequence (A, B, C, ..., Z, AA, AB, AC, ...).
docx4j now covers xlsx as well.
"Why would you use docx4j to do this", I hear you ask, "rather than POI, which focuses on xlsx and binary xls?"
Probably because you like JAXB (as opposed to XML Beans), or you are already using docx4j for docx or pptx, and need to be able to do some stuff with xlsx as well.
Another possible reason is that the jar XML Beans generates from the OpenXML schemas is too big for your purposes. (To get around this, POI offers a 'lite' subset: the 'big' ooxml-schemas-1.0.jar is 14.5 MB! But if you need to support arbitrary spreadsheets, you'll probably need the complete jar). In contrast, the whole of docx4j/pptx4j/xlsx4j weighs in at about the same as POI's lite subset.
If you are processing spreadsheets only (ie not docx or pptx), and preceding paragraph is not a concern for you, then you would probably be best off using POI.
RUN is an image build step, the state of the container after a RUN
command will be committed to the container image. A Dockerfile can have many RUN
steps that layer on top of one another to build the image.
CMD is the command the container executes by default when you launch the built image. A Dockerfile will only use the final CMD
defined. The CMD
can be overridden when starting a container with docker run $image $other_command
.
ENTRYPOINT is also closely related to CMD
and can modify the way a container starts an image.
You didnt specify the platform you use, so I assume it's a Mac ;-)
What I do is use a proxy. I use SquidMan, a standalone implementation of Squid
I start SquidMan on the Mac, then on the iPhone I enter the Proxy params in the General/Wifi Settings.
Then I can watch the HTTP trafic in the Console App, looking at the squid-access.log
If I need more infos, I switch to tcpdump, but I suppose WireShark should work too.
There are some options in constructors look, if you don't have dropdownList and you wanna insert CSS class you can use like
@Html.DropDownList("Country", null, "Choose-Category", new {@class="form-control"})
in this case Country is the name of your dropdown, null is for you aren't passing any generic list from your controller "Choose-Category" is selected item and last one in CSS class if you don't wanna select any default option so simple replace "Choose-Category" with ""
Give zero to mindate
and it'll disabale past dates.
$( "#datepicker" ).datepicker({ minDate: 0});
here is a Live fiddle working example http://jsfiddle.net/mayooresan/ZL2Bc/
The UniformGrid might not be available in Silverlight, but someone has ported it from WPF. http://www.jeff.wilcox.name/2009/01/uniform-grid/
use fwrite() instead of file_put_contents()
I think its better to to do text-align center for div and let image take care of the height. Just specify a top and bottom padding for div to have space between image and div. Look at this example: http://jsfiddle.net/Tv9mG/
<?php if($condition) : ?>
<a href="http://yahoo.com">This will only display if $condition is true</a>
<?php endif; ?>
By request, here's elseif and else (which you can also find in the docs)
<?php if($condition) : ?>
<a href="http://yahoo.com">This will only display if $condition is true</a>
<?php elseif($anotherCondition) : ?>
more html
<?php else : ?>
even more html
<?php endif; ?>
It's that simple.
The HTML will only be displayed if the condition is satisfied.
Well one major thing is anything you submit over GET
is going to be exposed via the URL. Secondly as Ceejayoz says, there is a limit on characters for a URL.
I get this warning in Angular if I run:
ng serve --sourceMap=false
To fix:
ng serve
You could use the ToString method on IQueryCollection
which will return the desired value if a single page
parameter is specified:
string page = HttpContext.Request.Query["page"].ToString();
if there are multiple values like ?page=1&page=2
then the result of the ToString call will be 1,2
But as @mike-g suggested in his answer you would better use model binding and not directly accessing the HttpContext.Request.Query
object.
Here is the link to the official documentation on how to set up custom error views:
https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views
It says to add lines like these in your URLconf (setting them anywhere else will have no effect):
handler404 = 'mysite.views.my_custom_page_not_found_view'
handler500 = 'mysite.views.my_custom_error_view'
handler403 = 'mysite.views.my_custom_permission_denied_view'
handler400 = 'mysite.views.my_custom_bad_request_view'
You can also customise the CSRF error view by modifying the setting CSRF_FAILURE_VIEW
.
It's worth reading the documentation of the default error handlers, page_not_found
, server_error
, permission_denied
and bad_request
. By default, they use these templates if they can find them, respectively: 404.html
, 500.html
, 403.html
, and 400.html
.
So if all you want to do is make pretty error pages, just create those files in a TEMPLATE_DIRS
directory, you don't need to edit URLConf at all. Read the documentation to see which context variables are available.
In Django 1.10 and later, the default CSRF error view uses the template 403_csrf.html
.
Don't forget that DEBUG
must be set to False for these to work, otherwise, the normal debug handlers will be used.
Interesting. The only thing I knew that had to do with programming and had POCO in it is the POCO C++ framework.
for(n in 1:5) {
if(n==3) next # skip 3rd iteration and go to next iteration
cat(n)
}
Take a look at this question.
TL;DR: clean, then build.
./gradlew clean packageDebug
Let's combine the culture-safe answer and the extension method answer:
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;
return DateTime.Today.AddDays(-(DateTime.Today.DayOfWeek- fdow));
}
}
if not exists (select dist_id from tbl_stock where dist_id= @cust_id and item_id=@item_id)
insert into tbl_stock(dist_id,item_id,qty)values(@cust_id, @item_id, @qty);
else
update tbl_stock set qty=(qty + @qty) where dist_id= @cust_id and item_id= @item_id;
function _modulename_getData($field, $table) {
try {
if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
/*
Here you can either echo the exception message like:
echo $e->getMessage();
Or you can throw the Exception Object $e like:
throw $e;
*/
}
}
I had this problem when I wanted to make a vnc connection via a tunnel.
But the vncserver was not running.
I solved it by opening the channel on the remote machine with vncserver :3
.
table-layout: fixed
will get force the cells to fit the table (and not the other way around), e.g.:
<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
table-layout: fixed;">
<tr>
<td>
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
</td>
</tr>
</table>
I created a jQuery version of PhpMyCoder's answer:
$('form').submit(function( e ) {
if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
//Prevent default and display error
alert("File is wrong type or over 10Mb in size!");
e.preventDefault();
}
});
function get_extension(filename) {
return filename.split('.').pop().toLowerCase();
}
Whenever we are trying to connect to URL,
if server at the other site is running on https protocol and is mandating that we should communicate via information provided in certificate then we have following option:
1) ask for the certificate(download the certificate), import this certificate in trustore. Default trustore java uses can be found in \Java\jdk1.6.0_29\jre\lib\security\cacerts, then if we retry to connect to the URL connection would be accepted.
2) In normal business cases, we might be connecting to internal URLS in organizations and we know that they are correct. In such cases, you trust that it is the correct URL, In such cases above, code can be used which will not mandate to store the certificate to connect to particular URL.
for the point no 2 we have to follow below steps :
1) write below method which sets HostnameVerifier for HttpsURLConnection which returns true for all cases meaning we are trusting the trustStore.
// trusting all certificate
public void doTrustToCertificates() throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
}
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
2) write below method, which calls doTrustToCertificates before trying to connect to URL
// connecting to URL
public void connectToUrl(){
doTrustToCertificates();//
URL url = new URL("https://www.example.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
System.out.println("ResponseCode ="+conn.getResponseCode());
}
This call will return response code = 200 means connection is successful.
For more detail and sample example you can refer to URL.
For me the laziest way to allow inline inizialization is use this macro.
#define METHOD_MEMBER(TYPE, NAME, CLASS) \
CLASS &set_ ## NAME(const TYPE &_val) { NAME = _val; return *this; } \
TYPE NAME;
struct foo {
METHOD_MEMBER(string, attr1, foo)
METHOD_MEMBER(int, attr2, foo)
METHOD_MEMBER(double, attr3, foo)
};
// inline usage
foo test = foo().set_attr1("hi").set_attr2(22).set_attr3(3.14);
That macro create attribute and self reference method.
<html>
<head>
<script type="text/javascript">
var number = 123;
var string = "abcd";
function docWrite(variable) {
document.write(variable);
}
</script>
</head>
<body>
<h1>the value for number is: <script>docWrite(number)</script></h1>
<h2>the text is: <script>docWrite(string)</script> </h2>
</body>
</html>
You can shorten document.write
but
can't avoid <script>
tag
You can play with your array
$daysArray = array('Monday', 'Tuesday', 'Sunday');
$day = current($transport); // $day = 'Monday';
$day = next($transport); // $day = 'Tuesday';
$day = current($transport); // $day = 'Tuesday';
$day = prev($transport); // $day = 'Monday';
$day = end($transport); // $day = 'Sunday';
$day = current($transport); // $day = 'Sunday';
To get the first element of array you can use current
and for last element you can use end
Edit
Just for the sake for not getting any more down votes for the answer you can convert you key to value using array_keys
and use as shown above.
As the Python documentation says:
sys.maxsize
The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.
In my computer (Linux x86_64):
>>> import sys
>>> print sys.maxsize
9223372036854775807
Setting Processor Architecture for AnyCPU Projects in Test Explorer fixed my issue! See screenshot above.
Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:
$('td').click(function(){
var row_index = $(this).closest("tr").index();
var col_index = $(this).index();
});
I'm had the same problem, and I tried with the answers above, but I wanted something more thin, then I tried to change one by one opsions, and discover that we just need to add
.carousel {
height: 100%;
}
After looking on the accepted answer I realized that if know size of required vector then we have to use a loop to initialize every element
But I found new to do this using default_structure_element like following...
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
typedef struct subject {
string name;
int marks;
int credits;
}subject;
int main(){
subject default_subject;
default_subject.name="NONE";
default_subject.marks = 0;
default_subject.credits = 0;
vector <subject> sub(10,default_subject); // default_subject to initialize
//to check is it initialised
for(ll i=0;i<sub.size();i++) {
cout << sub[i].name << " " << sub[i].marks << " " << sub[i].credits << endl;
}
}
Then I think its good to way to initialize a vector of the struct, isn't it?
There's also a pretty handy tool called binwalk, written in python, which provides for binary pattern matching (and quite a lot more besides). Here's how you would search for a binary string, which outputs the offset in decimal and hex (from the docs):
$ binwalk -R "\x00\x01\x02\x03\x04" firmware.bin
DECIMAL HEX DESCRIPTION
--------------------------------------------------------------------------
377654 0x5C336 Raw string signature
Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.
That is neither a good idea in terms of peformance nor in terms of fail-safety.
There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:
In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.
Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.
So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.
So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.
If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).
Conclusion:
using-statement
to dispose and close(in case of Connections) implicitelyThat's true not only for Connections(although most noticable). Every object implementing IDisposable
should be disposed(simplest by using-statement
), all the more in the System.Data.SqlClient
namespace.
All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.
Edit: Here's a possible implementation of your retrievePromotion
-method:
public Promotion retrievePromotion(int promotionID)
{
Promotion promo = null;
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
using (var da = new SqlDataAdapter(queryString, connection))
{
// you could also use a SqlDataReader instead
// note that a DataTable does not need to be disposed since it does not implement IDisposable
var tblPromotion = new DataTable();
// avoid SQL-Injection
da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
try
{
connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise
da.Fill(tblPromotion);
if (tblPromotion.Rows.Count != 0)
{
var promoRow = tblPromotion.Rows[0];
promo = new Promotion()
{
promotionID = promotionID,
promotionTitle = promoRow.Field<String>("PromotionTitle"),
promotionUrl = promoRow.Field<String>("PromotionURL")
};
}
}
catch (Exception ex)
{
// log this exception or throw it up the StackTrace
// we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
throw;
}
}
}
return promo;
}
I had the same problem using Apache commons-fileupload. I did not find out what causes the problems especially because I have the UTF-8 encoding in the following places: 1. HTML meta tag 2. Form accept-charset attribute 3. Tomcat filter on every request that sets the "UTF-8" encoding
-> My solution was to especially convert Strings from ISO-8859-1 (or whatever is the default encoding of your platform) to UTF-8:
new String (s.getBytes ("iso-8859-1"), "UTF-8");
hope that helps
Edit: starting with Java 7 you can also use the following:
new String (s.getBytes (StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
header('Content-Type: application/json; charset=utf-8');
For me this worked perfectly fine .
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent);
and add this permission to mainfest file:
<uses-permission android:name="android.permission.CAMERA">
It opens the camera,after capturing the image it saves the image to gallery with a new image set.
If you are using a Form Control
, you can get the same property as ActiveX
by using OLEFormat.Object
property of the Shape Object
. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.
Dim opt As OptionButton
With Sheets("Sheet1") ' Try to be always explicit
Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With
But then again, you really don't need to know the value.
If you use Form Control
, you associate a Macro
or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.
For example you have 2 Form Control
Option Buttons.
Sub CheckOptions()
Select Case Application.Caller
Case "Option Button 1"
' Action for option button 1
Case "Option Button 2"
' Action for option button 2
End Select
End Sub
In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller
.
This way, no need to check whether the option button value is true or false.
Notifications appear to have changed again (October 2016).
// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(yourClass.yourMethod), name: NSNotification.Name(rawValue: "yourNotificatioName"), object: nil)
// Post notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "yourNotificationName"), object: nil)
You can use a generator expression:
tuple(i for i in (1, 2, 3))
but parentheses were already taken for … generator expressions.
You can also use window.location.href=window.location.href;
You Create Custom ListView Which is non Scrollable
public class NonScrollListView extends ListView {
public NonScrollListView(Context context) {
super(context);
}
public NonScrollListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
}
In Your Layout Resources File
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<!-- com.Example Changed with your Package name -->
<com.Example.NonScrollListView
android:id="@+id/lv_nonscroll_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</com.Example.NonScrollListView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/lv_nonscroll_list" >
<!-- Your another layout in scroll view -->
</RelativeLayout>
</RelativeLayout>
In Java File
Create a object of your customListview instead of ListView like : NonScrollListView non_scroll_list = (NonScrollListView) findViewById(R.id.lv_nonscroll_list);
Here is a sample project, based on antew's detailed and helpful answer, that implements a ListView
with multiple headers that incorporates view holders to improve scrolling performance.
In this project, the objects represented in the ListView
are instances of either the class HeaderItem
or the class RowItem
, both of which are subclasses of the abstract class Item
. Each subclass of Item
corresponds to a different view type in the custom adapter, ItemAdapter
. The method getView()
on ItemAdapter
delegates the creation of the view for each list item to an individualized getView()
method on either HeaderItem
or RowItem
, depending on the Item
subclass used at the position passed to the getView()
method on the adapter. Each Item
subclass provides its own view holder.
The view holders are implemented as follows. The getView()
methods on the Item
subclasses check whether the View
object that was passed to the getView()
method on ItemAdapter
is null. If so, the appropriate layout is inflated, and a view holder object is instantiated and associated with the inflated view via View.setTag()
. If the View
object is not null, then a view holder object was already associated with the view, and the view holder is retrieved via View.getTag()
. The way in which the view holders are used can be seen in the following code snippet from HeaderItem
:
@Override
View getView(LayoutInflater i, View v) {
ViewHolder h;
if (v == null) {
v = i.inflate(R.layout.header, null);
h = new ViewHolder(v);
v.setTag(h);
} else {
h = (ViewHolder) v.getTag();
}
h.category.setText(text());
return v;
}
private class ViewHolder {
final TextView category;
ViewHolder(View v) {
category = v.findViewById(R.id.category);
}
}
The complete implementation of the ListView follows. Here is the Java code:
import android.app.ListActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ItemAdapter(getItems()));
}
class ItemAdapter extends ArrayAdapter<Item> {
final private List<Class<?>> viewTypes;
ItemAdapter(List<Item> items) {
super(MainActivity.this, 0, items);
if (items.contains(null))
throw new IllegalArgumentException("null item");
viewTypes = getViewTypes(items);
}
private List<Class<?>> getViewTypes(List<Item> items) {
Set<Class<?>> set = new HashSet<>();
for (Item i : items)
set.add(i.getClass());
List<Class<?>> list = new ArrayList<>(set);
return Collections.unmodifiableList(list);
}
@Override
public int getViewTypeCount() {
return viewTypes.size();
}
@Override
public int getItemViewType(int position) {
Item t = getItem(position);
return viewTypes.indexOf(t.getClass());
}
@Override
public View getView(int position, View v, ViewGroup unused) {
return getItem(position).getView(getLayoutInflater(), v);
}
}
abstract private class Item {
final private String text;
Item(String text) {
this.text = text;
}
String text() { return text; }
abstract View getView(LayoutInflater i, View v);
}
private class HeaderItem extends Item {
HeaderItem(String text) {
super(text);
}
@Override
View getView(LayoutInflater i, View v) {
ViewHolder h;
if (v == null) {
v = i.inflate(R.layout.header, null);
h = new ViewHolder(v);
v.setTag(h);
} else {
h = (ViewHolder) v.getTag();
}
h.category.setText(text());
return v;
}
private class ViewHolder {
final TextView category;
ViewHolder(View v) {
category = v.findViewById(R.id.category);
}
}
}
private class RowItem extends Item {
RowItem(String text) {
super(text);
}
@Override
View getView(LayoutInflater i, View v) {
ViewHolder h;
if (v == null) {
v = i.inflate(R.layout.row, null);
h = new ViewHolder(v);
v.setTag(h);
} else {
h = (ViewHolder) v.getTag();
}
h.option.setText(text());
return v;
}
private class ViewHolder {
final TextView option;
ViewHolder(View v) {
option = v.findViewById(R.id.option);
}
}
}
private List<Item> getItems() {
List<Item> t = new ArrayList<>();
t.add(new HeaderItem("Header 1"));
t.add(new RowItem("Row 2"));
t.add(new HeaderItem("Header 3"));
t.add(new RowItem("Row 4"));
t.add(new HeaderItem("Header 5"));
t.add(new RowItem("Row 6"));
t.add(new HeaderItem("Header 7"));
t.add(new RowItem("Row 8"));
t.add(new HeaderItem("Header 9"));
t.add(new RowItem("Row 10"));
t.add(new HeaderItem("Header 11"));
t.add(new RowItem("Row 12"));
t.add(new HeaderItem("Header 13"));
t.add(new RowItem("Row 14"));
t.add(new HeaderItem("Header 15"));
t.add(new RowItem("Row 16"));
t.add(new HeaderItem("Header 17"));
t.add(new RowItem("Row 18"));
t.add(new HeaderItem("Header 19"));
t.add(new RowItem("Row 20"));
t.add(new HeaderItem("Header 21"));
t.add(new RowItem("Row 22"));
t.add(new HeaderItem("Header 23"));
t.add(new RowItem("Row 24"));
t.add(new HeaderItem("Header 25"));
t.add(new RowItem("Row 26"));
t.add(new HeaderItem("Header 27"));
t.add(new RowItem("Row 28"));
t.add(new RowItem("Row 29"));
t.add(new RowItem("Row 30"));
t.add(new HeaderItem("Header 31"));
t.add(new RowItem("Row 32"));
t.add(new HeaderItem("Header 33"));
t.add(new RowItem("Row 34"));
t.add(new RowItem("Row 35"));
t.add(new RowItem("Row 36"));
return t;
}
}
There are also two list item layouts, one for each Item subclass. Here is the layout header
, used by HeaderItem:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFAAAAAA"
>
<TextView
android:id="@+id/category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:textColor="#FF000000"
android:textSize="20sp"
android:textStyle="bold"
/>
</LinearLayout>
And here is the layout row
, used by RowItem:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
>
<TextView
android:id="@+id/option"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
/>
</LinearLayout>
Here is an image of a portion of the resulting ListView:
I had the same problem, but running the Server before running the Client fixed it.
For example,
package main
import "fmt"
func main() {
type Map1 map[string]interface{}
type Map2 map[string]int
m := Map1{"foo": Map2{"first": 1}, "boo": Map2{"second": 2}}
//m = map[foo:map[first: 1] boo: map[second: 2]]
fmt.Println("m:", m)
for k, v := range m {
fmt.Println("k:", k, "v:", v)
}
}
Output:
m: map[boo:map[second:2] foo:map[first:1]]
k: boo v: map[second:2]
k: foo v: map[first:1]
Deleting a function is a C++11 feature:
The common idiom of "prohibiting copying" can now be expressed directly:
class X { // ... X& operator=(const X&) = delete; // Disallow copying X(const X&) = delete; };
[...]
The "delete" mechanism can be used for any function. For example, we can eliminate an undesired conversion like this:
struct Z { // ... Z(long long); // can initialize with an long long Z(long) = delete; // but not anything less };
You can capture the image from windows using the Python web driver. Use the code below which page need to capture the screenshot.
driver.save_screenshot('c:\foldername\filename.extension(png, jpeg)')
Just in case if you can use yarn
which is recommended for React apps,
you can do,
yarn add [email protected] // this is to add bootstrap with a specific version
This will add the bootstrap as a dependency to your package.json
as well.
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"bootstrap": "4.1.1", // it will add an entry here
"react": "^16.5.2",
"react-dom": "^16.5.2",
"react-scripts": "1.1.5"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
After that just import bootstrap
in your index.js
file.
import 'bootstrap/dist/css/bootstrap.css';
Set the original background-color in you CSS file:
.forum{
background-color:#f0f;
}?
You don't have to capture the original color in jQuery. Remember that jQuery will alter the style INLINE, so by setting the background-color to null you will get the same result.
$(function() {
$(".forum").hover(
function() {
$(this).css('background-color', '#ff0')
}, function() {
$(this).css('background-color', '')
});
});?
The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
Example usage:
var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
Which I got from https://stackoverflow.com/a/8412989/1232175.
In my case, I used the ssl
module to "workaround" the certification like so:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
Then to read your link content, you can use:
urllib.request.urlopen(urllink)
It depends on the compiler. If you compile with, say, G++ on Linux and VC++ on Windows, this will do :
#ifdef linux
...
#elif _WIN32
...
#else
...
#endif
I used below layout and able to achieve custom layout in Navigation View.
<android.support.design.widget.NavigationView
android:id="@+id/navi_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start|top"
android:background="@color/navigation_view_bg_color"
app:theme="@style/NavDrawerTextStyle">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/drawer_header" />
<include layout="@layout/navigation_drawer_menu" />
</LinearLayout>
</android.support.design.widget.NavigationView>
while you should show how your code looks like that gives the problem, i think this scenario is very common. See copy/deepcopy
global
members are not available by default in your <template>
's scope. But you can easily pass them on using computed
properties.
computed: {
moment: () => moment,
console: () => console,
window: () => window
}
Now you can use any of them in your template. i.e: console.log(moment(), window)
.
Note this doesn't add any overhead.
If you want nice json without hardcoding attributes into your service classes,
use <webHttp defaultOutgoingResponseFormat="Json"/>
in your behavior config
Ok this is my solution: in ~/.bash_aliases just add the following:
# ADDS MY PATH WHEN SET AS ROOT
if [ $(id -u) = "0" ]; then
export PATH=$PATH:/home/your_user/bin
fi
Voila! Now you can execute your own scripts with sudo or set as ROOT without having to do an export PATH=$PATH:/home/your_user/bin everytime.
Notice that I need to be explicit when adding my PATH since HOME for superuser is /root
After getting an image from the gallery, just pass the URI in the below method only for Android 4.4 (KitKat):
public String getPath(Uri contentUri) {// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// Where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel,
new String[] { id }, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
1.
Type t = typeof(obj1);
if (t == typeof(int))
This is illegal, because typeof
only works on types, not on variables. I assume obj1 is a variable. So, in this way typeof
is static, and does its work at compile time instead of runtime.
2.
if (obj1.GetType() == typeof(int))
This is true
if obj1
is exactly of type int
. If obj1
derives from int
, the if condition will be false
.
3.
if (obj1 is int)
This is true
if obj1
is an int
, or if it derives from a class called int
, or if it implements an interface called int
.
As others said, use a simple if.
You should think about the ordering.
e.g
1 <= x && x <= 100
is easier to read than
x >= 1 && x <= 100
just to add to the answers here, I was using the height as a function with two options either specify the height if it is less than the window height, or set it back to auto
var windowHeight = $(window).height();
$('div#someDiv').height(function(){
if ($(this).height() < windowHeight)
return windowHeight;
return 'auto';
});
I needed to center the content vertically if it was smaller than the window height or else let it scroll naturally so this is what I came up with
People hate on tables for non-tabular data, but what you're asking for is exactly what tables are good at. <table width="100%">
To create a test case template:
"New" -> "JUnit Test Case" -> Select "Class under test" -> Select "Available methods". I think the wizard is quite easy for you.
In ES6 you can use Math.sign function to determine if,
1. its +ve no
2. its -ve no
3. its zero (0)
4. its NaN
console.log(Math.sign(1)) // prints 1
console.log(Math.sign(-1)) // prints -1
console.log(Math.sign(0)) // prints 0
console.log(Math.sign("abcd")) // prints NaN
For those that want to get the x and y coordinates of various positions of an element, relative to the document.
const getCoords = (element, position) => {
const { top, left, width, height } = element.getBoundingClientRect();
let point;
switch (position) {
case "top left":
point = {
x: left + window.pageXOffset,
y: top + window.pageYOffset
};
break;
case "top center":
point = {
x: left + width / 2 + window.pageXOffset,
y: top + window.pageYOffset
};
break;
case "top right":
point = {
x: left + width + window.pageXOffset,
y: top + window.pageYOffset
};
break;
case "center left":
point = {
x: left + window.pageXOffset,
y: top + height / 2 + window.pageYOffset
};
break;
case "center":
point = {
x: left + width / 2 + window.pageXOffset,
y: top + height / 2 + window.pageYOffset
};
break;
case "center right":
point = {
x: left + width + window.pageXOffset,
y: top + height / 2 + window.pageYOffset
};
break;
case "bottom left":
point = {
x: left + window.pageXOffset,
y: top + height + window.pageYOffset
};
break;
case "bottom center":
point = {
x: left + width / 2 + window.pageXOffset,
y: top + height + window.pageYOffset
};
break;
case "bottom right":
point = {
x: left + width + window.pageXOffset,
y: top + height + window.pageYOffset
};
break;
}
return point;
};
getCoords(document.querySelector('selector'), 'center')
getCoords(document.querySelector('selector'), 'bottom right')
getCoords(document.querySelector('selector'), 'top center')
I made a parent div expand around content of a child div by having the child div as a single column that does not have any positioning attribute such as absolute specified.
Example:
#wrap {width:400px;padding:10px 200px 10px 200px;position:relative;margin:0px auto;}
#maincolumn {width:400px;}
Based on maincolumn div being the deepest child div of #wrap this defines the depth of the #wrap div and the 200px padding on either side creates two big blank columns for you to place absolutely positioned divs in as you please. You could even change the padding top and bottom to place header divs and footer divs using position:absolute.
Well, the "text-overflow: ellipsis" worked for me, but just if my limit was based on 'width', I has needed a solution that can be applied on lines ( on the'height' instead the 'width' ) so I did this script:
function listLimit (elm, line){
var maxHeight = parseInt(elm.css('line-Height'))*line;
while(elm.height() > maxHeight){
var text = elm.text();
elm.text(text.substring(0,text.length-10)).text(elm.text()+'...');
}
}
And when I must, for example, that my h3 has only 2 lines I do :
$('h3').each(function(){
listLimit ($(this), 2)
})
I dunno if that was the best practice for performance needs, but worked for me.
git revert -m
allows to un-merge still keeping the history of both merge and un-do operation. Might be good for documenting probably.
This is precisely what the member function std::vector::insert
is for
std::vector<int> AB = A;
AB.insert(AB.end(), B.begin(), B.end());
Update
Original
var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");
string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding
request.Method = "PUT";
request.ContentType = ""; // place MIME type here
request.ContentLength = data.Length;
var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();
You should use a sticky footer solution such as this one :
* {
margin: 0;
}
html, body {
height: 100%;
}
.wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
height: 142px; /* .push must be the same height as .footer */
}
There are others like this;
* {margin:0;padding:0;}
/* must declare 0 margins on everything, also for main layout components use padding, not
vertical margins (top and bottom) to add spacing, else those margins get added to total height
and your footer gets pushed down a bit more, creating vertical scroll bars in the browser */
html, body, #wrap {height: 100%;}
body > #wrap {height: auto; min-height: 100%;}
#main {padding-bottom: 150px;} /* must be same height as the footer */
#footer {position: relative;
margin-top: -150px; /* negative value of footer height */
height: 150px;
clear:both;}
/* CLEAR FIX*/
.clearfix:after {content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;}
.clearfix {display: inline-block;}
/* Hides from IE-mac \*/
* html .clearfix { height: 1%;}
.clearfix {display: block;}
with the html:
<div id="wrap">
<div id="main" class="clearfix">
</div>
</div>
<div id="footer">
</div>
@mikejonesguy answer is perfect, just in case you plan to test room migrations (recommended), add the schema location to the source sets.
In your build.gradle file you specify a folder to place these generated schema JSON files. As you update your schema, you’ll end up with several JSON files, one for every version. Make sure you commit every generated file to source control. The next time you increase your version number again, Room will be able to use the JSON file for testing.
- Florina Muntenescu (source)
build.gradle
android {
// [...]
defaultConfig {
// [...]
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
}
// add the schema location to the source sets
// used by Room, to test migrations
sourceSets {
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
}
// [...]
}
Your regular expression should look like:
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/
Here is an explanation:
/^
(?=.*\d) // should contain at least one digit
(?=.*[a-z]) // should contain at least one lower case
(?=.*[A-Z]) // should contain at least one upper case
[a-zA-Z0-9]{8,} // should contain at least 8 from the mentioned characters
$/
You can try this:
<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
<item name="tabBackground">@drawable/background</item>
</style>
In your background xml file:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@color/white" />
<item android:drawable="@color/black" />
</selector>
One more thing, using printf with predefined var as template.
msg="First line %s
Second line %s
Third line %s
"
one='additional message for the first line'
two='2'
tri='this is the last one'
printf "$msg" "$one" "$two" "$tri"
This ^^^ will print whole message with additional vars inserted instead of '%s' in provided order.
Main culprit for this error is logic which determines encoding when converting Stream
or byte[]
array to .NET string
.
Using StreamReader
created with 2nd constructor parameter detectEncodingFromByteOrderMarks
set to true, will determine proper encoding and create string
which does not break XmlDocument.LoadXml
method.
public string GetXmlString(string url)
{
using var stream = GetResponseStream(url);
using var reader = new StreamReader(stream, true);
return reader.ReadToEnd(); // no exception on `LoadXml`
}
Common mistake would be to just blindly use UTF8
encoding on the stream
or byte[]
. Code bellow would produce string
that looks valid when inspected in Visual Studio debugger, or copy-pasted somewhere, but it will produce the exception when used with Load
or LoadXml
if file is encoded differently then UTF8 without BOM.
public string GetXmlString(string url)
{
byte[] bytes = GetResponseByteArray(url);
return System.Text.Encoding.UTF8.GetString(bytes); // potentially exception on `LoadXml`
}
A list comprehension seems to be a good way to do this:
>>> [mydict[x] for x in mykeys]
[3, 1]
You need to set line-height.
<div style="border: 1px solid red;">
<span style="font-size: 38px; vertical-align:middle; float:left; line-height: 38px">Hejsan</span>
<span style="font-size: 13px; vertical-align:middle; float:right; line-height: 38px">svejsan</span>
<div style="clear: both;"></div>
In a scenario where you intend to push a single email to different recipients at one instance (i.e CC multiple email addresses), the solution below works fine with Laravel 5.4 and above.
Mail::to('[email protected]')
->cc(['[email protected]','[email protected]','[email protected]','[email protected]'])
->send(new document());
where document is any class that further customizes your email.
The easiest method for obtaining both a setter
and a getter
for a property which works for any type including dynamic
and ExpandoObject
is to use FastMember
which also happens to be the fastest method around (it uses Emit).
You can either get a TypeAccessor
based on a given type or an ObjectAccessor
based of an instance of a given type.
Example:
var staticData = new Test { Id = 1, Name = "France" };
var objAccessor = ObjectAccessor.Create(staticData);
objAccessor["Id"].Should().Be(1);
objAccessor["Name"].Should().Be("France");
var anonymous = new { Id = 2, Name = "Hilton" };
objAccessor = ObjectAccessor.Create(anonymous);
objAccessor["Id"].Should().Be(2);
objAccessor["Name"].Should().Be("Hilton");
dynamic expando = new ExpandoObject();
expando.Id = 3;
expando.Name = "Monica";
objAccessor = ObjectAccessor.Create(expando);
objAccessor["Id"].Should().Be(3);
objAccessor["Name"].Should().Be("Monica");
var typeAccessor = TypeAccessor.Create(staticData.GetType());
typeAccessor[staticData, "Id"].Should().Be(1);
typeAccessor[staticData, "Name"].Should().Be("France");
typeAccessor = TypeAccessor.Create(anonymous.GetType());
typeAccessor[anonymous, "Id"].Should().Be(2);
typeAccessor[anonymous, "Name"].Should().Be("Hilton");
typeAccessor = TypeAccessor.Create(expando.GetType());
((int)typeAccessor[expando, "Id"]).Should().Be(3);
((string)typeAccessor[expando, "Name"]).Should().Be("Monica");
I would recommend storing the time as integers and regulate it through the division and modulo operators, once that is done convert the integers into the string format you require.
Alternatively, you could do:
for i in range(0, len(a), 2):
#do something
The extended slice notation is much more concise, though.
Use Application.ActiveWorkbook.Path
for just the path itself (without the workbook name) or Application.ActiveWorkbook.FullName
for the path with the workbook name.
Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.
The JSON snippet you have posted is malformed.
You have posted:
[{
"name" : "shopqwe",
"mobiles" : [],
"address" : {
"town" : "city",
"street" : "streetqwe",
"streetNumber" : "59",
"cordX" : 2.229997,
"cordY" : 1.002539
},
"shoe"[{
"shoeName" : "addidas",
"number" : "631744030",
"producent" : "nike",
"price" : 999.0,
"sizes" : [30.0, 35.0, 38.0]
}]
while the correct JSON would be:
[{
"name" : "shopqwe",
"mobiles" : [],
"address" : {
"town" : "city",
"street" : "streetqwe",
"streetNumber" : "59",
"cordX" : 2.229997,
"cordY" : 1.002539
},
"shoe" : [{
"shoeName" : "addidas",
"number" : "631744030",
"producent" : "nike",
"price" : 999.0,
"sizes" : [30.0, 35.0, 38.0]
}
]
}
]
I had a problem with a big delay between calling setNeedsDisplay and drawRect: (5 seconds). It turned out I called setNeedsDisplay in a different thread than the main thread. After moving this call to the main thread the delay went away.
Hope this is of some help.
removing first characters:
x <- 'hello stackoverflow'
substring(x, 2, nchar(x))
Idea is select all characters starting from 2 to number of characters in x. This is important when you have unequal number of characters in word or phrase.
Selecting the first letter is trivial as previous answers:
substring(x,1,1)
Inline frame is just one "box" and you can place it anywhere on your site. Frames are a bunch of 'boxes' put together to make one site with many pages.
Typescript solution that clones the array instead of mutating existing one
export function swapItemsInArray<T>(items: T[], indexA: number, indexB: number): T[] {
const itemA = items[indexA];
const clone = [...items];
clone[indexA] = clone[indexB];
clone[indexB] = itemA;
return clone;
}
You need to add
#container
{
display:inline-block;
position:relative;
background:rgb(255,100,0);
margin:0px;
width:40%;
height:100px;
margin-right:-4px;
}
because whenever you write display:inline-block
it takes an additional margin-right:4px
. So, you need to remove it.
You'll have problems creating lists without commas. It shouldn't be too hard to transform your data so that it uses commas as separating character.
Once you have commas in there, it's a relatively simple list creation operations:
array1 = [1,2,3]
array2 = [4,5,6]
array3 = [array1, array2]
array4 = [7,8,9]
array5 = [10,11,12]
array3 = [array3, [array4, array5]]
When testing we get:
print(array3)
[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
And if we test with indexing it works correctly reading the matrix as made up of 2 rows and 2 columns:
array3[0][1]
[4, 5, 6]
array3[1][1]
[10, 11, 12]
Hope that helps.
str="1w 2d 1h"
regex="([0-9])w ([0-9])d ([0-9])h"
if [[ $str =~ $regex ]]
then
week="${BASH_REMATCH[1]}"
day="${BASH_REMATCH[2]}"
hour="${BASH_REMATCH[3]}"
echo $week --- $day ---- $hour
fi
output: 1 --- 2 ---- 1
As Victoria wrote, Google Maps is no longer free, but you can switch your map provider. You may be interested in OpenStreetMap, there is an easy way to use it on your site described here: https://handyman.dulare.com/switching-from-google-maps-to-openstreetmap/
Unfortunately, on the OpenStreetMap, there is no easy way to provide directions from one point to another, there is also no street view.
I had a similar issue and searched all the internet for this problem
if you have this problem just copy your HTML code in a new HTML file and use the normal <meta charset="UTF-8">
and it will work....
just create a new HTML file in the same location and use a different name
Encode each value in the list to a string:
[x.encode('UTF8') for x in EmployeeList]
You need to pick a valid encoding; don't use str()
as that'll use the system default (for Python 2 that's ASCII) which will not encode all possible codepoints in a Unicode value.
UTF-8 is capable of encoding all of the Unicode standard, but any codepoint outside the ASCII range will lead to multiple bytes per character.
However, if all you want to do is test for a specific string, test for a unicode string and Python won't have to auto-encode all values when testing for that:
u'1001' in EmployeeList.values()
You can plot multiple subplots of multiple pandas data frames using matplotlib with a simple trick of making a list of all data frame. Then using the for loop for plotting subplots.
Working code:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# dataframe sample data
df1 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df2 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df3 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df4 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df5 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df6 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
#define number of rows and columns for subplots
nrow=3
ncol=2
# make a list of all dataframes
df_list = [df1 ,df2, df3, df4, df5, df6]
fig, axes = plt.subplots(nrow, ncol)
# plot counter
count=0
for r in range(nrow):
for c in range(ncol):
df_list[count].plot(ax=axes[r,c])
count=+1
Using this code you can plot subplots in any configuration. You need to just define number of rows nrow
and number of columns ncol
. Also, you need to make list of data frames df_list
which you wanted to plot.
Make UIAlertController+AlertController Category as:
UIAlertController+AlertController.h
typedef void (^UIAlertCompletionBlock) (UIAlertController *alertViewController, NSInteger buttonIndex);
@interface UIAlertController (AlertController)
+ (instancetype)showAlertIn:(UIViewController *)controller
WithTitle:(NSString *)title
message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitle
tapBlock:(UIAlertCompletionBlock)tapBlock;
@end
UIAlertController+AlertController.m
@implementation UIAlertController (NTAlertController)
+ (instancetype)showAlertIn:(UIViewController *)controller
WithTitle:(NSString *)title
message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitle
tapBlock:(UIAlertCompletionBlock)tapBlock {
UIAlertController *alertController = [self alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
if(cancelButtonTitle != nil) {
UIAlertAction *cancelButton = [UIAlertAction
actionWithTitle:cancelButtonTitle
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action)
{
tapBlock(alertController, ALERTACTION_CANCEL); // CANCEL BUTTON CALL BACK ACTION
}];
[alertController addAction:cancelButton];
}
if(otherButtonTitle != nil) {
UIAlertAction *otherButton = [UIAlertAction
actionWithTitle:otherButtonTitle
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
tapBlock(alertController, ALERTACTION_OTHER); // OTHER BUTTON CALL BACK ACTION
}];
[alertController addAction:otherButton];
}
[controller presentViewController:alertController animated:YES completion:nil];
return alertController;
}
@end
in your ViewController.m
[UIAlertController showAlertIn:self WithTitle:@"" message:@"" cancelButtonTitle:@"Cancel" otherButtonTitles:@"Other" tapBlock:^(UIAlertController *alertController, NSInteger index){
if(index == ALERTACTION_CANCEL){
// CANCEL BUTTON ACTION
}else
if(index == ALERTACTION_OTHER){
// OTHER BUTTON ACTION
}
[alertController dismissViewControllerAnimated:YES completion:nil];
}];
NOTE: If you want to add more than two buttons then add another more UIAlertAction to the UIAlertController.
Have a look at the python documentation for filter(function, iterable)
(from here):
Construct an iterator from those elements of iterable for which function returns true.
So in order to get a list back you have to use list class:
shesaid = list(filter(greetings(), ["hello", "goodbye"]))
But this probably isn't what you wanted, because it tries to call the result of greetings()
, which is "hello", on the values of your input list, and this won't work. Here also the iterator type comes into play, because the results aren't generated until you use them (for example by calling list()
on it). So at first you won't get an error, but when you try to do something with shesaid
it will stop working:
>>> print(list(shesaid))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
If you want to check which elements in your list are equal to "hello" you have to use something like this:
shesaid = list(filter(lambda x: x == "hello", ["hello", "goodbye"]))
(I put your function into a lambda, see Randy C's answer for a "normal" function)
Link to the PEP discussing the new bool type in Python 2.3: http://www.python.org/dev/peps/pep-0285/.
When converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0.
>>> int(False)
0
>>> int(True)
1
>>> bool(5)
True
>>> bool(-5)
True
>>> bool(0)
False
select count(*)
from user_tab_columns
where table_name='MYTABLE' --use upper case
Instead of uppercase you can use lower function. Ex: select count(*) from user_tab_columns where lower(table_name)='table_name';
This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12
but Excel.XlFileFormat.xlOpenXMLWorkbook
. The actual C# command was
excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Excel.XlSaveConflictResolution.xlUserResolution, true,
Missing.Value, Missing.Value, Missing.Value);
I hope this helps someone else in the future.
Missing.Value
is found in the System.Reflection
namespace.
Swift 4 Dictionary
extension.
extension Dictionary {
var jsonStringRepresentation: String? {
guard let theJSONData = try? JSONSerialization.data(withJSONObject: self,
options: [.prettyPrinted]) else {
return nil
}
return String(data: theJSONData, encoding: .ascii)
}
}
I know this is an old question, but I had a similar issue and found that:
lm(x ~ y + relevel(b, ref = "3"))
does exactly what you asked.
sudo nvram "recovery-boot-mode=unused"
sudo reboot
csrutil disable
spctl kext-consent add VB5E2TV963
nvram -d recovery-boot-mode
reboot
sudo mount -uw /
sudo chown :admin /System/Library/Extensions/
sudo chmod 775 /System/Library/Extensions/
Run the Guest Additions installer and go through the end (in principle, it goes through successfully)
Now in the terminal, do:
sudo chown :wheel /System/Library/Extensions/
sudo chmod 755 /System/Library/Extensions/
sudo nvram "recovery-boot-mode=unused"
sudo reboot
csrutil enable
nvram -d recovery-boot-mode
reboot
You should be set.
public functin func_name(Request $request){$reqOutput = $request->getRequestUri();}
When input value is empty search else the value inside input. This code works for me:
$("#your_input").on('focus', function () {
$(this).autocomplete('search', $(this).val() == '' ? " " : $(this).val());
});
This is the numerical representation of the date. The thing you get when referring to dates from formulas like that.
You'll have to do:
= A1 & TEXT(A2, "mm/dd/yyyy")
The biggest problem here is that the format specifier is locale-dependent. It will not work/produce not what expected if the file is opened with a differently localized Excel.
Now, you could have a user-defined function:
public function AsDisplayed(byval c as range) as string
AsDisplayed = c.Text
end function
and then
= A1 & AsDisplayed(A2)
But then there's a bug (feature?) in Excel because of which the .Text
property is suddenly not available during certain stages of the computation cycle, and your formulas display #VALUE
instead of what they should.
That is, it's bad either way.
You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.
You just need to re-open the image with IrfanView after changing the view color to white.
To change the viewing color in Irfanview go to:
Options > Properties/Settings > Viewing > Main window color
method = POST
will work if you 'post' a form to the url /test.
if you type a url in address bar of a browser and hit enter, it's always a GET
request, so you had to specify POST request.
Google for HTTP GET
and HTTP POST
(there are several others like PUT DELETE). They all have their own meaning.
Apparently, there's a lot of "dead wood" in the "build" directories of a project.
Under linux/unix, a simple way to get a clean, private backup is to use the "tar" command along with the "--exclude=String" option.
For example, to create an archive of all my apps while excluding the build directories, I have a script that creates the following 2 commands :
cd $HOME/android/Studio
tar cvf MyBackup-2017-07-13.tar Projects --exclude=build
NumPy 1.7.0 (when numpy.pad
was added) is pretty old now (it was released in 2013) so even though the question asked for a way without using that function I thought it could be useful to know how that could be achieved using numpy.pad
.
It's actually pretty simple:
>>> import numpy as np
>>> a = np.array([[ 1., 1., 1., 1., 1.],
... [ 1., 1., 1., 1., 1.],
... [ 1., 1., 1., 1., 1.]])
>>> np.pad(a, [(0, 1), (0, 1)], mode='constant')
array([[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])
In this case I used that 0
is the default value for mode='constant'
. But it could also be specified by passing it in explicitly:
>>> np.pad(a, [(0, 1), (0, 1)], mode='constant', constant_values=0)
array([[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])
Just in case the second argument ([(0, 1), (0, 1)]
) seems confusing: Each list item (in this case tuple) corresponds to a dimension and item therein represents the padding before (first element) and after (second element). So:
[(0, 1), (0, 1)]
^^^^^^------ padding for second dimension
^^^^^^-------------- padding for first dimension
^------------------ no padding at the beginning of the first axis
^--------------- pad with one "value" at the end of the first axis.
In this case the padding for the first and second axis are identical, so one could also just pass in the 2-tuple:
>>> np.pad(a, (0, 1), mode='constant')
array([[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])
In case the padding before and after is identical one could even omit the tuple (not applicable in this case though):
>>> np.pad(a, 1, mode='constant')
array([[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0.],
[ 0., 1., 1., 1., 1., 1., 0.],
[ 0., 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0., 0.]])
Or if the padding before and after is identical but different for the axis, you could also omit the second argument in the inner tuples:
>>> np.pad(a, [(1, ), (2, )], mode='constant')
array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
However I tend to prefer to always use the explicit one, because it's just to easy to make mistakes (when NumPys expectations differ from your intentions):
>>> np.pad(a, [1, 2], mode='constant')
array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.]])
Here NumPy thinks you wanted to pad all axis with 1 element before and 2 elements after each axis! Even if you intended it to pad with 1 element in axis 1 and 2 elements for axis 2.
I used lists of tuples for the padding, note that this is just "my convention", you could also use lists of lists or tuples of tuples, or even tuples of arrays. NumPy just checks the length of the argument (or if it doesn't have a length) and the length of each item (or if it has a length)!
__cplusplus
In C++0x the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L.
import { HttpClientModule } from '@angular/common/http';
The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below
http.get('friends.json').subscribe(result => this.result =result);
I have set the vm argument in WAS server as -Dfile.encoding=UTF-8 to change the servers' default character set.
You can add onclick=""
to hovered element. Hover will work after that.
Edit: But you really shouldn't add anything style related to your markup, just posted it as an alternative.
Yes. Which platform are you writing for? ASP.NET C#?
List<string> myList = new List<string>();
Session["var"] = myList;
Then, to retrieve:
myList = (List<string>)Session["var"];
My answer is an amalgamation of the above two with extension to drawing sphere of user-defined opacity and some annotation. It finds application in b-vector visualization on a sphere for magnetic resonance image (MRI). Hope you find it useful:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
# alpha controls opacity
ax.plot_surface(x, y, z, color="g", alpha=0.3)
# a random array of 3D coordinates in [-1,1]
bvecs= np.random.randn(20,3)
# tails of the arrows
tails= np.zeros(len(bvecs))
# heads of the arrows with adjusted arrow head length
ax.quiver(tails,tails,tails,bvecs[:,0], bvecs[:,1], bvecs[:,2],
length=1.0, normalize=True, color='r', arrow_length_ratio=0.15)
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('b-vectors on unit sphere')
plt.show()
The main (very interesting) difference for me is that:
"string" & Null
-> "string"
while
"string" + Null
-> Null
But that's probably more useful in database apps like Access.
If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.
You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar
):
openssl genrsa -aes128 -passout pass:foobar 3072
However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.
A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:
openssl genrsa -aes128 -passout file:passphrase.txt 3072
Or supply the passphrase on standard input:
openssl genrsa -aes128 -passout stdin 3072
You can also used a named pipe with the file:
option, or a file descriptor.
To then obtain the matching public key, you need to use openssl rsa
, supplying the same passphrase with the -passin
parameter as was used to encrypt the private key:
openssl rsa -passin file:passphrase.txt -pubout
(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>
).
Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar
:
openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub
You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.
Rows("52:55").EntireRow.Hidden = False
becomes
activesheet.Rows("52:55").EntireRow.Hidden = False
i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,
Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub
That's it. Anytime you change something, it will run the macro test1.
If you are sending alphanumeric data try changing
'Content-Type': 'multipart/form-data'
to
'Content-Type': 'application/x-www-form-urlencoded'
If you are sending non-alphanumeric data try to remove 'Content-Type' at all.
If it still does not work, consider trying request-promise (at least to test whether it is really axios problem or not)
Not a direct answer to this question but rather to the "issue" of $event.currentTarget
apparently be set to null.
This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.
You can check this for more information: Consecutive calls to console.log produce inconsistent results
I believe you want to use confirm()
<script type="text/javascript">
function clicked() {
if (confirm('Do you want to submit?')) {
yourformelement.submit();
} else {
return false;
}
}
</script>
Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.
To clear a canvas, use the delete method. Give it the special parameter "all"
to delete all items on the canvas (the string "all"
" is a special tag that represents all items on the canvas):
canvas.delete("all")
If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all"
, you could supply the name of a tag.
If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.
Blockquote
If you're trying to pull from another branch into your branch. If you're seeing this error.
First, you should try doing git commit and then pull another branch into yours.
In my case i forgot to add the () after the function name inside the render function of a react component
public render() {
let ctrl = (
<>
<div className="aaa">
{this.renderView}
</div>
</>
);
return ctrl;
};
private renderView() : JSX.Element {
// some html
};
Changing the render method, as it states in the error message to
<div className="aaa">
{this.renderView()}
</div>
fixed the problem
This should do what you're looking for:
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}
Usage:
echo clean('a|"bc!@£de^&$f g');
Will output: abcdef-g
Edit:
Hey, just a quick question, how can I prevent multiple hyphens from being next to each other? and have them replaced with just 1?
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}
Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.
It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.
Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart
and touchmove
handlers, which may prevent the scroll entirely by calling preventDefault()
on the event.
Solution: {passive: true}
By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault
to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user
.
document.addEventListener("touchstart", function(e) {
console.log(e.defaultPrevented); // will be false
e.preventDefault(); // does nothing since the listener is passive
console.log(e.defaultPrevented); // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
You could use Series.reindex
:
import pandas as pd
idx = pd.date_range('09-01-2013', '09-30-2013')
s = pd.Series({'09-02-2013': 2,
'09-03-2013': 10,
'09-06-2013': 5,
'09-07-2013': 1})
s.index = pd.DatetimeIndex(s.index)
s = s.reindex(idx, fill_value=0)
print(s)
yields
2013-09-01 0
2013-09-02 2
2013-09-03 10
2013-09-04 0
2013-09-05 0
2013-09-06 5
2013-09-07 1
2013-09-08 0
...
You can specify the connection timeout within the SQL connection string, when you connect to the database, like so:
"Data Source=localhost;Initial Catalog=database;Connect Timeout=15"
On the server level, use MSSQLMS to view the server properties, and on the Connections page you can specify the default query timeout.
I'm not quite sure that queries keep on running after the client connection has closed. Queries should not take that long either, MSSQL can handle large databases, I've worked with GB's of data on it before. Run a performance profile on the queries, prehaps some well-placed indexes could speed it up, or rewriting the query could too.
Update: According to this list, SQL timeouts happen when waiting for attention acknowledgement from server:
Suppose you execute a command, then the command times out. When this happens the SqlClient driver sends a special 8 byte packet to the server called an attention packet. This tells the server to stop executing the current command. When we send the attention packet, we have to wait for the attention acknowledgement from the server and this can in theory take a long time and time out. You can also send this packet by calling SqlCommand.Cancel on an asynchronous SqlCommand object. This one is a special case where we use a 5 second timeout. In most cases you will never hit this one, the server is usually very responsive to attention packets because these are handled very low in the network layer.
So it seems that after the client connection times out, a signal is sent to the server to cancel the running query too.
I realise this is an old question, but another possible consideration depending on your exact requirements is that validating on https://validator.w3.org/ generates warnings as follows:
Warning: The form role is unnecessary for element form.
Using RandomAccessFile
would be simple and handy.
RandomAccessFile f = new RandomAccessFile(filepath, "r");
byte[] bytes = new byte[(int) f.length()];
f.read(bytes);
f.close();
In this particular example I think @Tagir is 100% correct get it into one filter and do the two checks. I wouldn't use Optional.ofNullable
the Optional stuff is really for return types not to be doing logic... but really neither here nor there.
I wanted to point out that java.util.Objects
has a nice method for this in a broad case, so you can do this:
cars.stream()
.filter(Objects::nonNull)
Which will clear out your null objects. For anyone not familiar, that's the short-hand for the following:
cars.stream()
.filter(car -> Objects.nonNull(car))
To partially answer the question at hand to return the list of car names that starts with "M"
:
cars.stream()
.filter(car -> Objects.nonNull(car))
.map(car -> car.getName())
.filter(carName -> Objects.nonNull(carName))
.filter(carName -> carName.startsWith("M"))
.collect(Collectors.toList());
Once you get used to the shorthand lambdas you could also do this:
cars.stream()
.filter(Objects::nonNull)
.map(Car::getName) // Assume the class name for car is Car
.filter(Objects::nonNull)
.filter(carName -> carName.startsWith("M"))
.collect(Collectors.toList());
Unfortunately once you .map(Car::getName)
you'll only be returning the list of names, not the cars. So less beautiful but fully answers the question:
cars.stream()
.filter(car -> Objects.nonNull(car))
.filter(car -> Objects.nonNull(car.getName()))
.filter(car -> car.getName().startsWith("M"))
.collect(Collectors.toList());
I don't know if there's a 'proper' way to do it, but your snippet is on the right track: just add import foo
to foo.py, do inspect.getmembers(foo)
, and it should work fine.
Since version 2.5 of the Pipeline Nodes and Processes Plugin (a component of the Pipeline plugin, installed by default), the WORKSPACE
environment variable is available again. This version was released on 2016-09-23, so it should be available on all up-to-date Jenkins instances.
node('label'){
// now you are on slave labeled with 'label'
def workspace = WORKSPACE
// ${workspace} will now contain an absolute path to job workspace on slave
workspace = env.WORKSPACE
// ${workspace} will still contain an absolute path to job workspace on slave
// When using a GString at least later Jenkins versions could only handle the env.WORKSPACE variant:
echo "Current workspace is ${env.WORKSPACE}"
// the current Jenkins instances will support the short syntax, too:
echo "Current workspace is $WORKSPACE"
}
It seems to be (as of 2018.03) in code-insider. A directive has been introduced called python.venvFolders:
"python.venvFolders": [
"envs",
".pyenv",
".direnv"
],
All you need is to add your virtualenv folder name.
After setting up GOPRIVATE
and git config ...
People may still meeting problems like this when fetching private source:
https fetch: Get "https://private/user/repo?go-get=1": EOF
They can't use private repo without .git
extension.
The reason is the go tool has no idea about the VCS protocol of this repo, git
or svn
or any other, unlike github.com
or golang.org
them are hardcoded into go's source.
Then the go tool will do a https
query before fetching your private repo:
https://private/user/repo?go-get=1
If your private repo has no support for https
request, please use replace
to tell it directly :
require private/user/repo v1.0.0
...
replace private/user/repo => private.server/user/repo.git v1.0.0
This answer is written to show just how trivial it is to bypass poorly written PHP user-validation code, how (and using what) these attacks work and how to replace the old MySQL functions with a secure prepared statement - and basically, why StackOverflow users (probably with a lot of rep) are barking at new users asking questions to improve their code.
First off, please feel free to create this test mysql database (I have called mine prep):
mysql> create table users(
-> id int(2) primary key auto_increment,
-> userid tinytext,
-> pass tinytext);
Query OK, 0 rows affected (0.05 sec)
mysql> insert into users values(null, 'Fluffeh', 'mypass');
Query OK, 1 row affected (0.04 sec)
mysql> create user 'prepared'@'localhost' identified by 'example';
Query OK, 0 rows affected (0.01 sec)
mysql> grant all privileges on prep.* to 'prepared'@'localhost' with grant option;
Query OK, 0 rows affected (0.00 sec)
With that done, we can move to our PHP code.
Lets assume the following script is the verification process for an admin on a website (simplified but working if you copy and use it for testing):
<?php
if(!empty($_POST['user']))
{
$user=$_POST['user'];
}
else
{
$user='bob';
}
if(!empty($_POST['pass']))
{
$pass=$_POST['pass'];
}
else
{
$pass='bob';
}
$database='prep';
$link=mysql_connect('localhost', 'prepared', 'example');
mysql_select_db($database) or die( "Unable to select database");
$sql="select id, userid, pass from users where userid='$user' and pass='$pass'";
//echo $sql."<br><br>";
$result=mysql_query($sql);
$isAdmin=false;
while ($row = mysql_fetch_assoc($result)) {
echo "My id is ".$row['id']." and my username is ".$row['userid']." and lastly, my password is ".$row['pass']."<br>";
$isAdmin=true;
// We have correctly matched the Username and Password
// Lets give this person full access
}
if($isAdmin)
{
echo "The check passed. We have a verified admin!<br>";
}
else
{
echo "You could not be verified. Please try again...<br>";
}
mysql_close($link);
?>
<form name="exploited" method='post'>
User: <input type='text' name='user'><br>
Pass: <input type='text' name='pass'><br>
<input type='submit'>
</form>
Seems legit enough at first glance.
The user has to enter a login and password, right?
Brilliant, not enter in the following:
user: bob
pass: somePass
and submit it.
The output is as follows:
You could not be verified. Please try again...
Super! Working as expected, now lets try the actual username and password:
user: Fluffeh
pass: mypass
Amazing! Hi-fives all round, the code correctly verified an admin. It's perfect!
Well, not really. Lets say the user is a clever little person. Lets say the person is me.
Enter in the following:
user: bob
pass: n' or 1=1 or 'm=m
And the output is:
The check passed. We have a verified admin!
Congrats, you just allowed me to enter your super-protected admins only section with me entering a false username and a false password. Seriously, if you don't believe me, create the database with the code I provided, and run this PHP code - which at glance REALLY does seem to verify the username and password rather nicely.
So, in answer, THAT IS WHY YOU ARE BEING YELLED AT.
So, lets have a look at what went wrong, and why I just got into your super-admin-only-bat-cave. I took a guess and assumed that you weren't being careful with your inputs and simply passed them to the database directly. I constructed the input in a way tht would CHANGE the query that you were actually running. So, what was it supposed to be, and what did it end up being?
select id, userid, pass from users where userid='$user' and pass='$pass'
That's the query, but when we replace the variables with the actual inputs that we used, we get the following:
select id, userid, pass from users where userid='bob' and pass='n' or 1=1 or 'm=m'
See how I constructed my "password" so that it would first close the single quote around the password, then introduce a completely new comparison? Then just for safety, I added another "string" so that the single quote would get closed as expected in the code we originally had.
However, this isn't about folks yelling at you now, this is about showing you how to make your code more secure.
Okay, so what went wrong, and how can we fix it?
This is a classic SQL injection attack. One of the simplest for that matter. On the scale of attack vectors, this is a toddler attacking a tank - and winning.
So, how do we protect your sacred admin section and make it nice and secure? The first thing to do will be to stop using those really old and deprecated mysql_*
functions. I know, you followed a tutorial you found online and it works, but it's old, it's outdated and in the space of a few minutes, I have just broken past it without so much as breaking a sweat.
Now, you have the better options of using mysqli_ or PDO. I am personally a big fan of PDO, so I will be using PDO in the rest of this answer. There are pro's and con's, but personally I find that the pro's far outweigh the con's. It's portable across multiple database engines - whether you are using MySQL or Oracle or just about bloody anything - just by changing the connection string, it has all the fancy features we want to use and it is nice and clean. I like clean.
Now, lets have a look at that code again, this time written using a PDO object:
<?php
if(!empty($_POST['user']))
{
$user=$_POST['user'];
}
else
{
$user='bob';
}
if(!empty($_POST['pass']))
{
$pass=$_POST['pass'];
}
else
{
$pass='bob';
}
$isAdmin=false;
$database='prep';
$pdo=new PDO ('mysql:host=localhost;dbname=prep', 'prepared', 'example');
$sql="select id, userid, pass from users where userid=:user and pass=:password";
$myPDO = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
if($myPDO->execute(array(':user' => $user, ':password' => $pass)))
{
while($row=$myPDO->fetch(PDO::FETCH_ASSOC))
{
echo "My id is ".$row['id']." and my username is ".$row['userid']." and lastly, my password is ".$row['pass']."<br>";
$isAdmin=true;
// We have correctly matched the Username and Password
// Lets give this person full access
}
}
if($isAdmin)
{
echo "The check passed. We have a verified admin!<br>";
}
else
{
echo "You could not be verified. Please try again...<br>";
}
?>
<form name="exploited" method='post'>
User: <input type='text' name='user'><br>
Pass: <input type='text' name='pass'><br>
<input type='submit'>
</form>
The major differences are that there are no more mysql_*
functions. It's all done via a PDO object, secondly, it is using a prepared statement. Now, what's a prepred statement you ask? It's a way to tell the database ahead of running a query, what the query is that we are going to run. In this case, we tell the database: "Hi, I am going to run a select statement wanting id, userid and pass from the table users where the userid is a variable and the pass is also a variable.".
Then, in the execute statement, we pass the database an array with all the variables that it now expects.
The results are fantastic. Lets try those username and password combinations from before again:
user: bob
pass: somePass
User wasn't verified. Awesome.
How about:
user: Fluffeh
pass: mypass
Oh, I just got a little excited, it worked: The check passed. We have a verified admin!
Now, lets try the data that a clever chap would enter to try to get past our little verification system:
user: bob
pass: n' or 1=1 or 'm=m
This time, we get the following:
You could not be verified. Please try again...
This is why you are being yelled at when posting questions - it's because people can see that your code can be bypassed wihout even trying. Please, do use this question and answer to improve your code, to make it more secure and to use functions that are current.
Lastly, this isn't to say that this is PERFECT code. There are many more things that you could do to improve it, use hashed passwords for example, ensure that when you store sensetive information in the database, you don't store it in plain text, have multiple levels of verification - but really, if you just change your old injection prone code to this, you will be WELL along the way to writing good code - and the fact that you have gotten this far and are still reading gives me a sense of hope that you will not only implement this type of code when writing your websites and applications, but that you might go out and research those other things I just mentioned - and more. Write the best code you can, not the most basic code that barely functions.
Here is my solution:
DataTable datatable = (DataTable)dataset.datatablename;
Try this simple class for customizing a dialog to your liking:
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
public class CustomDialog
{
private List<JComponent> components;
private String title;
private int messageType;
private JRootPane rootPane;
private String[] options;
private int optionIndex;
public CustomDialog()
{
components = new ArrayList<>();
setTitle("Custom dialog");
setMessageType(JOptionPane.PLAIN_MESSAGE);
setRootPane(null);
setOptions(new String[] { "OK", "Cancel" });
setOptionSelection(0);
}
public void setTitle(String title)
{
this.title = title;
}
public void setMessageType(int messageType)
{
this.messageType = messageType;
}
public void addComponent(JComponent component)
{
components.add(component);
}
public void addMessageText(String messageText)
{
JLabel label = new JLabel("<html>" + messageText + "</html>");
components.add(label);
}
public void setRootPane(JRootPane rootPane)
{
this.rootPane = rootPane;
}
public void setOptions(String[] options)
{
this.options = options;
}
public void setOptionSelection(int optionIndex)
{
this.optionIndex = optionIndex;
}
public int show()
{
int optionType = JOptionPane.OK_CANCEL_OPTION;
Object optionSelection = null;
if(options.length != 0)
{
optionSelection = options[optionIndex];
}
int selection = JOptionPane.showOptionDialog(rootPane,
components.toArray(), title, optionType, messageType, null,
options, optionSelection);
return selection;
}
public static String getLineBreak()
{
return "<br>";
}
}
--parents
is copying the directory structure, so you should get rid of that.
The way you've written this, the find
executes, and the output is put onto the command line such that cp
can't distinguish between the spaces separating the filenames, and the spaces within the filename. It's better to do something like
$ find . -name \*.xls -exec cp {} newDir \;
in which cp
is executed for each filename that find
finds, and passed the filename correctly. Here's more info on this technique.
Instead of all the above, you could use zsh and simply type
$ cp **/*.xls target_directory
zsh
can expand wildcards to include subdirectories and makes this sort of thing very easy.
A combination of both attempts is probably what you need:
^[0-9]{1,45}$
You will need to configure you IIS (assuming this is the web server your are/will using) allowing access from WLAN/LAN to specific users (or anonymous). Allow IIS trought your firewall if you have one.
Your application won't need to be changed, that's just networking problems ans configuration you will have to face to allow acces only trought LAN and WLAN.
In C# 3, you can do:
IList<string> l = new List<string> { "test1", "test2", "test3" };
This uses the new collection initializer syntax in C# 3.
In C# 2, I would just use your second option.
Your array is occupying roughly 8 GB of memory (1,000 x 1,000,000 x sizeof(double) bytes). That might be a factor in your problem. It is a global variable rather than a stack variable, so you may be OK, but you're pushing limits here.
Writing that much data to a file is going to take a while.
You don't check that the file was opened successfully, which could be a source of trouble, too (if it did fail, a segmentation fault is very likely).
You really should introduce some named constants for 1,000 and 1,000,000; what do they represent?
You should also write a function to do the calculation; you could use an inline
function in C99 or later (or C++). The repetition in the code is excruciating to behold.
You should also use C99 notation for main()
, with the explicit return type (and preferably void
for the argument list when you are not using argc
or argv
):
int main(void)
Out of idle curiosity, I took a copy of your code, changed all occurrences of 1000 to ROWS, all occurrences of 1000000 to COLS, and then created enum { ROWS = 1000, COLS = 10000 };
(thereby reducing the problem size by a factor of 100). I made a few minor changes so it would compile cleanly under my preferred set of compilation options (nothing serious: static
in front of the functions, and the main array; file
becomes a local to main
; error check the fopen()
, etc.).
I then created a second copy and created an inline function to do the repeated calculation, (and a second one to do subscript calculations). This means that the monstrous expression is only written out once — which is highly desirable as it ensure consistency.
#include <stdio.h>
#define lambda 2.0
#define g 1.0
#define F0 1.0
#define h 0.1
#define e 0.00001
enum { ROWS = 1000, COLS = 10000 };
static double F[ROWS][COLS];
static void Inicio(double D[ROWS][COLS])
{
for (int i = 399; i < 600; i++) // Magic numbers!!
D[i][0] = F0;
}
enum { R = ROWS - 1 };
static inline int ko(int k, int n)
{
int rv = k + n;
if (rv >= R)
rv -= R;
else if (rv < 0)
rv += R;
return(rv);
}
static inline void calculate_value(int i, int k, double A[ROWS][COLS])
{
int ks2 = ko(k, -2);
int ks1 = ko(k, -1);
int kp1 = ko(k, +1);
int kp2 = ko(k, +2);
A[k][i] = A[k][i-1]
+ e/(h*h*h*h) * g*g * (A[kp2][i-1] - 4.0*A[kp1][i-1] + 6.0*A[k][i-1] - 4.0*A[ks1][i-1] + A[ks2][i-1])
+ 2.0*g*e/(h*h) * (A[kp1][i-1] - 2*A[k][i-1] + A[ks1][i-1])
+ e * A[k][i-1] * (lambda - A[k][i-1] * A[k][i-1]);
}
static void Iteration(double A[ROWS][COLS])
{
for (int i = 1; i < COLS; i++)
{
for (int k = 0; k < R; k++)
calculate_value(i, k, A);
A[999][i] = A[0][i];
}
}
int main(void)
{
FILE *file = fopen("P2.txt","wt");
if (file == 0)
return(1);
Inicio(F);
Iteration(F);
for (int i = 0; i < COLS; i++)
{
for (int j = 0; j < ROWS; j++)
{
fprintf(file,"%lf \t %.4f \t %lf\n", 1.0*j/10.0, 1.0*i, F[j][i]);
}
}
fclose(file);
return(0);
}
This program writes to P2.txt
instead of P1.txt
. I ran both programs and compared the output files; the output was identical. When I ran the programs on a mostly idle machine (MacBook Pro, 2.3 GHz Intel Core i7, 16 GiB 1333 MHz RAM, Mac OS X 10.7.5, GCC 4.7.1), I got reasonably but not wholly consistent timing:
Original Modified
6.334s 6.367s
6.241s 6.231s
6.315s 10.778s
6.378s 6.320s
6.388s 6.293s
6.285s 6.268s
6.387s 10.954s
6.377s 6.227s
8.888s 6.347s
6.304s 6.286s
6.258s 10.302s
6.975s 6.260s
6.663s 6.847s
6.359s 6.313s
6.344s 6.335s
7.762s 6.533s
6.310s 9.418s
8.972s 6.370s
6.383s 6.357s
However, almost all that time is spent on disk I/O. I reduced the disk I/O to just the very last row of data, so the outer I/O for
loop became:
for (int i = COLS - 1; i < COLS; i++)
the timings were vastly reduced and very much more consistent:
Original Modified
0.168s 0.165s
0.145s 0.165s
0.165s 0.166s
0.164s 0.163s
0.151s 0.151s
0.148s 0.153s
0.152s 0.171s
0.165s 0.165s
0.173s 0.176s
0.171s 0.165s
0.151s 0.169s
The simplification in the code from having the ghastly expression written out just once is very beneficial, it seems to me. I'd certainly far rather have to maintain that program than the original.
Both will generate the same columns when you run the migration. In rails console, you can see that this is the case:
:001 > Micropost
=> Micropost(id: integer, user_id: integer, created_at: datetime, updated_at: datetime)
The second command adds a belongs_to :user
relationship in your Micropost model whereas the first does not. When this relationship is specified, ActiveRecord will assume that the foreign key is kept in the user_id
column and it will use a model named User
to instantiate the specific user.
The second command also adds an index on the new user_id
column.
If checkout master
was the last thing you did, then the reflog entry HEAD@{1}
will contain your commits (otherwise use git reflog
or git log -p
to find them). Use git merge HEAD@{1}
to fast forward them into master.
EDIT:
As noted in the comments, Git Ready has a great article on this.
git reflog
and git reflog --all
will give you the commit hashes of the mis-placed commits.
Source: http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html
VERY IMPORTANT: If you are using LOMBOK, make shure to exclude attributes of collections like Set, List, etc...
Like this:
@EqualsAndHashCode(exclude = {"attributeOfTypeList", "attributeOfTypeSet"})
You probably shouldn't, and you can probably do what you want to do in a safer and simpler way. Technically to use variable number of arguments in C you include stdarg.h. From that you'll get the va_list
type as well as three functions that operate on it called va_start()
, va_arg()
and va_end()
.
#include<stdarg.h>
int maxof(int n_args, ...)
{
va_list ap;
va_start(ap, n_args);
int max = va_arg(ap, int);
for(int i = 2; i <= n_args; i++) {
int a = va_arg(ap, int);
if(a > max) max = a;
}
va_end(ap);
return max;
}
If you ask me, this is a mess. It looks bad, it's unsafe, and it's full of technical details that have nothing to do with what you're conceptually trying to achieve. Instead, consider using overloading or inheritance/polymorphism, builder pattern (as in operator<<()
in streams) or default arguments etc. These are all safer: the compiler gets to know more about what you're trying to do so there are more occasions it can stop you before you blow your leg off.
public DataTable TopDataRow(DataTable dt, int count)
{
DataTable dtn = dt.Clone();
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i < count)
{
dtn.ImportRow(row);
i++;
}
if (i > count)
break;
}
return dtn;
}
I'm pretty sure it's an Adobe standard, bearing in mind the whole PDF standard is theirs to begin with; despite being open now.
My guess would be no for all PDF viewers supporting it, as some definitely will not have a JS engine. I doubt you can rely on full support outside the most recent versions of Acrobat (Reader). So I guess it depends on how you imagine it being used, if mainly via a browser display, then the majority of the market is catered for by Acrobat (Reader) and Chrome's built-in viewer - dare say there is documentation on whether Chrome's PDF viewer supports JS fully.
You are not seeding the number.
Use This:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
cout << (rand() % 100) << endl;
return 0;
}
You only need to seed it once though. Basically don't seed it every random number.
Check if you have installed express
module. If not, use this command:
npm install express
and if your node_modules
directory is in another place, set NODE_PATH
envirnment variable:
set NODE_PATH=your\directory\to\node_modules;%NODE_PATH%
These people have developed a fingerprinting method for recognising a user with a high level of accuracy:
https://panopticlick.eff.org/static/browser-uniqueness.pdf
We investigate the degree to which modern web browsers are subject to “device fingerprinting” via the version and configuration information that they will transmit to websites upon request. We implemented one possible fingerprinting algorithm, and collected these fingerprints from a large sample of browsers that visited our test side, panopticlick.eff.org. We observe that the distribution of our finger- print contains at least 18.1 bits of entropy, meaning that if we pick a browser at random, at best we expect that only one in 286,777 other browsers will share its fingerprint. Among browsers that support Flash or Java, the situation is worse, with the average browser carrying at least 18.8 bits of identifying information. 94.2% of browsers with Flash or Java were unique in our sample.
By observing returning visitors, we estimate how rapidly browser fingerprints might change over time. In our sample, fingerprints changed quite rapidly, but even a simple heuristic was usually able to guess when a fingerprint was an “upgraded” version of a previously observed browser’s fingerprint, with 99.1% of guesses correct and a false positive rate of only 0.86%.
We discuss what privacy threat browser fingerprinting poses in practice, and what countermeasures may be appropriate to prevent it. There is a tradeoff between protection against fingerprintability and certain kinds of debuggability, which in current browsers is weighted heavily against privacy. Paradoxically, anti-fingerprinting privacy technologies can be self- defeating if they are not used by a sufficient number of people; we show that some privacy measures currently fall victim to this paradox, but others do not...
I was also facing this issue
Error- Windows cannot find 'http://127.0.01:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again
After some research work, I found out that my HTTPPORT
ie. 8080
was occupied by Apace HTTP Server
and hence connection by OracleServiceXE
could not be established.
What I did to solve this issue was :
Apache2.4
and manually stopped it to free my 8080
port.Start Database
, and I received message : The OracleServiceXE service is starting.............. The OracleServiceXE service was started successfully.
http://127.0.0.1:8080/apex/f?p=4950
url to my browser which auto redirected me to http://127.0.0.1:8080/apex/f?p=4950:1:3763261197573303
That's it my issue got resolved.
In order to remember this new url and make sure that next time whenever I hit Get Started
I should be redirected to http://127.0.0.1:8080/apex/f?p=4950:1:3763261197573303
instead of http://127.0.0.1:8080/apex/f?p=4950
, what I did was :
Directory:\OracleDatabase\app\oracle\product\11.2.0\server
and search for Get_Started.html
.Get_Started.html
and select Properties
Apply
Hope this Helps.
If you are using rails > 3 version, then there is a concept called asset pipeline
. You could add your CSS to
app/assets/stylesheets
then it will automatically be picked up by the app. (this is useful as rails will automatically compress the CSS files)
read more here about the asset pipeline