On a rather unrelated note: more performance hacks!
When traversing the sequence, we can only get 3 possible cases in the 2-neighborhood of the current element N
(shown first):
To leap past these 2 elements means to compute (N >> 1) + N + 1
, ((N << 1) + N + 1) >> 1
and N >> 2
, respectively.
Let`s prove that for both cases (1) and (2) it is possible to use the first formula, (N >> 1) + N + 1
.
Case (1) is obvious. Case (2) implies (N & 1) == 1
, so if we assume (without loss of generality) that N is 2-bit long and its bits are ba
from most- to least-significant, then a = 1
, and the following holds:
(N << 1) + N + 1: (N >> 1) + N + 1:
b10 b1
b1 b
+ 1 + 1
---- ---
bBb0 bBb
where B = !b
. Right-shifting the first result gives us exactly what we want.
Q.E.D.: (N & 1) == 1 ? (N >> 1) + N + 1 == ((N << 1) + N + 1) >> 1
.
As proven, we can traverse the sequence 2 elements at a time, using a single ternary operation. Another 2× time reduction.
The resulting algorithm looks like this:
uint64_t sequence(uint64_t size, uint64_t *path) {
uint64_t n, i, c, maxi = 0, maxc = 0;
for (n = i = (size - 1) | 1; i > 2; n = i -= 2) {
c = 2;
while ((n = ((n & 3)? (n >> 1) + n + 1 : (n >> 2))) > 2)
c += 2;
if (n == 2)
c++;
if (c > maxc) {
maxi = i;
maxc = c;
}
}
*path = maxc;
return maxi;
}
int main() {
uint64_t maxi, maxc;
maxi = sequence(1000000, &maxc);
printf("%llu, %llu\n", maxi, maxc);
return 0;
}
Here we compare n > 2
because the process may stop at 2 instead of 1 if the total length of the sequence is odd.
Let`s translate this into assembly!
MOV RCX, 1000000;
DEC RCX;
AND RCX, -2;
XOR RAX, RAX;
MOV RBX, RAX;
@main:
XOR RSI, RSI;
LEA RDI, [RCX + 1];
@loop:
ADD RSI, 2;
LEA RDX, [RDI + RDI*2 + 2];
SHR RDX, 1;
SHRD RDI, RDI, 2; ror rdi,2 would do the same thing
CMOVL RDI, RDX; Note that SHRD leaves OF = undefined with count>1, and this doesn't work on all CPUs.
CMOVS RDI, RDX;
CMP RDI, 2;
JA @loop;
LEA RDX, [RSI + 1];
CMOVE RSI, RDX;
CMP RAX, RSI;
CMOVB RAX, RSI;
CMOVB RBX, RCX;
SUB RCX, 2;
JA @main;
MOV RDI, RCX;
ADD RCX, 10;
PUSH RDI;
PUSH RCX;
@itoa:
XOR RDX, RDX;
DIV RCX;
ADD RDX, '0';
PUSH RDX;
TEST RAX, RAX;
JNE @itoa;
PUSH RCX;
LEA RAX, [RBX + 1];
TEST RBX, RBX;
MOV RBX, RDI;
JNE @itoa;
POP RCX;
INC RDI;
MOV RDX, RDI;
@outp:
MOV RSI, RSP;
MOV RAX, RDI;
SYSCALL;
POP RAX;
TEST RAX, RAX;
JNE @outp;
LEA RAX, [RDI + 59];
DEC RDI;
SYSCALL;
Use these commands to compile:
nasm -f elf64 file.asm
ld -o file file.o
See the C and an improved/bugfixed version of the asm by Peter Cordes on Godbolt. (editor's note: Sorry for putting my stuff in your answer, but my answer hit the 30k char limit from Godbolt links + text!)
You might want to change the DNS settings of the Docker daemon. You can edit (or create) the configuration file at /etc/docker/daemon.json
with the dns key, as
{
"dns": ["your_dns_address", "8.8.8.8"]
}
In the example above, the first element of the list is the address of your DNS server. The second item is the Google’s DNS which can be used when the first one is not available.
Before proceeding, save daemon.json and restart the docker service.
sudo service docker restart
Once fixed, retry to run the build command.
Notice Allowed methods in the response
Connection: close
Date: Tue, 11 Feb 2014 15:17:24 GMT
Content-Length: 34
Content-Type: text/html
Allow: GET, DELETE
X-Powered-By: Servlet/2.5 JSP/2.1
It accepts only GET and DELETE. Hence, you need to tweak the server to enable PUT and POST as well.
Allow: GET, DELETE
PHP - curl:
$username = 'myusername';
$password = 'mypassword';
...
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
...
PHP - POST in WordPress:
$username = 'myusername';
$password = 'mypassword';
...
wp_remote_post('https://...some...api...endpoint...', array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode("$username:$password")
)
));
...
Recently I used an AS3 engine: PushButton (now is dead, but it's still functional and you could use something else) to do this job. To make it works with Android and iOS, the project was compiled in AIR for both platforms and everything worked with no performance damage. Since Flash Builder is kinda expensive ($249), you could use FlashDevelop (there is some tutorials to compile in AIR with it).
Flash could be an option since is very easy to learn.
Had the same problem today setting up my repo from scratch. I tried everything, nothing worked except removing the origin and re-adding it back again.
git remote rm origin
git remote add origin [email protected]:web3coach/the-blockchain-bar-newsletter-edition.git
git fetch --all
// Ta daaa all branches fetched
I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:
String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
byte[] b = baos.toByteArray();
encImage = Base64.encodeToString(b, Base64.DEFAULT);
When I started using json, I was confused and unable to figure it out for some time, but finally I got what I wanted
Here is the simple solution
import json
m = {'id': 2, 'name': 'hussain'}
n = json.dumps(m)
o = json.loads(n)
print(o['id'], o['name'])
from bs4 import BeautifulSoup
from requests_html import HTMLSession
url = 'your_url'
session = HTMLSession()
resp = session.get(url)
# if element with id "articlebody" is dynamic, else need not to render
resp.html.render()
soup = bs(resp.html.html, "lxml")
soup.find("div", {"id": "articlebody"})
I adapted one of the answers from the referenced question, but added the ability to define an explicit mapping for character names.
var char_names = {
160:'nbsp',
161:'iexcl',
220:'Uuml',
223:'szlig',
196:'Auml',
252:'uuml',
};
function HTMLEncode(str){
var aStr = str.split(''),
i = aStr.length,
aRet = [];
while (--i >= 0) {
var iC = aStr[i].charCodeAt();
if (iC < 32 || (iC > 32 && iC < 65) || iC > 127 || (iC>90 && iC<97)) {
if(char_names[iC]!=undefined) {
aRet.push('&'+char_names[iC]+';');
}
else {
aRet.push('&#'+iC+';');
}
} else {
aRet.push(aStr[i]);
}
}
return aRet.reverse().join('');
}
var text = "Übergroße Äpfel mit Würmer";
alert(HTMLEncode(text));
I tried to use the code above but didn't work. The JSON structure returned by Google is so different and there is a very important miss in the helper function: a call to DataContractJsonSerializer.ReadObject()
that actually deserializes the JSON data into the object.
Here is the code that WORKS in 2011:
using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Collections.Generic;
namespace <YOUR_NAMESPACE>
{
public class JSONHelper
{
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
obj = (T)serialiser.ReadObject(ms);
ms.Close();
return obj;
}
}
public class Result
{
public string GsearchResultClass { get; set; }
public string unescapedUrl { get; set; }
public string url { get; set; }
public string visibleUrl { get; set; }
public string cacheUrl { get; set; }
public string title { get; set; }
public string titleNoFormatting { get; set; }
public string content { get; set; }
}
public class Page
{
public string start { get; set; }
public int label { get; set; }
}
public class Cursor
{
public string resultCount { get; set; }
public Page[] pages { get; set; }
public string estimatedResultCount { get; set; }
public int currentPageIndex { get; set; }
public string moreResultsUrl { get; set; }
public string searchResultTime { get; set; }
}
public class ResponseData
{
public Result[] results { get; set; }
public Cursor cursor { get; set; }
}
public class GoogleSearchResults
{
public ResponseData responseData { get; set; }
public object responseDetails { get; set; }
public int responseStatus { get; set; }
}
}
To get the content of the first result, do:
GoogleSearchResults googleResults = new GoogleSearchResults();
googleResults = JSONHelper.Deserialise<GoogleSearchResults>(jsonData);
string contentOfFirstResult = googleResults.responseData.results[0].content;
Instead of .each, another (perhaps more concise) approach to getting all those prices might be:
var prices = $(products).children("li").map(function() {
return $(this).prop("data-price");
}).get();
additionally you may want to consider filtering the array to get rid of empty or non-numeric array values in case they should exist:
prices = prices.filter(function(n){ return(!isNaN(parseFloat(n))) });
then use Sergey's solution above:
var max = Math.max.apply(Math,prices);
var min = Math.min.apply(Math,prices);
I believe the more efficient approach to this is to use the cron job module in the shared server admin panel to run the laravel scheduler command which will in turn call the configured artisan command, something like this should do the job:
* * * * * /usr/bin/php /var/www/web/artisan schedule:run /dev/null 2>&1
With scheduler setup in cron, you can edit the schedule method in \App\Console\Kernel.php to call the right artisan command, something like this:
$schedule->command('queue:work')->cron('* * * * *')->withoutOverlapping();
$schedule->command('route:cache')->cron('0 0 * * *')->withoutOverlapping();
You can always delete the lines above after the commands run
Another way to detect the bitness of Office is to find out the typelib.
For example, to detect Outlook's bitness, write a .JS file as following:
function detectVersion()
var outlooktlib = "TypeLib\\{00062FFF-0000-0000-C000-000000000046}";
var HKCR = 0x80000000;
var loc = new ActiveXObject("WbemScripting.SWbemLocator");
var svc = loc.ConnectServer(null,"root\\default");
var reg = svc.Get("StdRegProv");
var method = reg.Methods_.Item("EnumKey");
var inparam = method.InParameters.SpawnInstance_();
inparam.hDefKey = HKCR;
inparam.sSubKeyName = outlooktlib;
var outparam = reg.ExecMethod_(method.Name,inparam);
tlibver = outparam.sNames.toArray()[0];
method = reg.Methods_.Item("GetStringValue");
inparam = method.InParameters.SpawnInstance_();
inparam.hDefKey = HKCR;
inparam.sSubKeyName = outlooktlib + "\\" + tlibver + "\\0\\win32";
inparam.sValueName = "";
outparam = reg.ExecMethod_(method.Name,inparam);
if(outparam.sValue) return "32 bit";
method = reg.Methods_.Item("GetStringValue");
inparam = method.InParameters.SpawnInstance_();
inparam.hDefKey = HKCR;
inparam.sSubKeyName = outlooktlib + "\\" + tlibver + "\\0\\win64";
inparam.sValueName = "";
outparam = reg.ExecMethod_(method.Name,inparam);
if(outparam.sValue) return "64 bit";
return "Not installed or unrecognizable";
}
You could find out other Office component's typelib id, and replace the first line of the function for it. Here is a brief list of interesting IDs:
{4AFFC9A0-5F99-101B-AF4E-00AA003F0F07} - Access
{00020905-0000-0000-C000-000000000046} - Word
{00020813-0000-0000-C000-000000000046} - Excel
{91493440-5A91-11CF-8700-00AA0060263B} - Powerpoint
{0002123C-0000-0000-C000-000000000046} - Publisher
{0EA692EE-BB50-4E3C-AEF0-356D91732725} - OneNote 2010+
{F2A7EE29-8BF6-4A6D-83F1-098E366C709C} - OneNote 2007
All above lib id were found through the Windows SDK tool OLE-COM Object Viewer
, you could find out more lib id's by using it.
The benefit of this approach is that it works for all versions of office, and provides control on every single component in you interest. Furthermore, those keys are in the HKEY_CLASSES_ROOT and deeply integrated into the system, so it is highly unlikely they were not accessible even in a sandbox environment.
win32com.client
is a part of pywin32
So, download pywin32 from here
I agree with peterh's answer, so for those of you who like to copy and paste instead of 60 more seconds of Googling:
private String getComputerName()
{
Map<String, String> env = System.getenv();
if (env.containsKey("COMPUTERNAME"))
return env.get("COMPUTERNAME");
else if (env.containsKey("HOSTNAME"))
return env.get("HOSTNAME");
else
return "Unknown Computer";
}
I have tested this in Windows 7 and it works. If peterh was right the else if
should take care of Mac and Linux. Maybe someone can test this? You could also implement Brian Roach's answer inside the else
if you wanted extra robustness.
Code Example : Reading data from DataGridView and storing it in an array
int[,] n = new int[3, 19];
for (int i = 0; i < (StartDataView.Rows.Count - 1); i++)
{
for (int j = 0; j < StartDataView.Columns.Count; j++)
{
if(this.StartDataView.Rows[i].Cells[j].Value.ToString() != string.Empty)
{
try
{
n[i, j] = int.Parse(this.StartDataView.Rows[i].Cells[j].Value.ToString());
}
catch (Exception Ee)
{ //get exception of "null"
MessageBox.Show(Ee.ToString());
}
}
}
}
If I understood you well I think you have two ways of doing it.
First you could try ngSwitch and the second possible way would be creating you own filter. Probably ngSwitch is the right aproach but if you want to hide or show inline content just using {{}} filter is the way to go.
Here is a fiddle with a simple filter as an example.
<div ng-app="exapleOfFilter">
<div ng-controller="Ctrl">
<input ng-model="greeting" type="greeting">
<br><br>
<h1>{{greeting|isHello}}</h1>
</div>
</div>
angular.module('exapleOfFilter', []).
filter('isHello', function() {
return function(input) {
// conditional you want to apply
if (input === 'hello') {
return input;
}
return '';
}
});
function Ctrl($scope) {
$scope.greeting = 'hello';
}
A postback is the process of re-loading a page, so if you want the page to close after the postback then you need to set your window.close() javascript to run with the browser's onload event during that postback, normally done using the ClientScript.RegisterStartupScript()
function.
But are you sure this is what you want to do? Closing pages tends to piss off users.
Just go to the properties of your cmd.exe shortcut and change the 'start in' by adding the file name where you put all your '.txt' files.I had same problems and i put the whole file mane as 'D:\photon' in the 'start in' of the properties and it worked.Remember you have to put all your files in that folder otherwise you have to create many shortcuts for each data files.Sorry for late reply
If you want to merge the filters (eg. CSV and Excel files), use this formula:
OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";
Or if you want to see XML or PDF files in one time use this:
of.Filter = @" XML or PDF |*.xml;*.pdf";
SAP SE is a German multinational that makes enterprise software. It is best known for SAP ERP and its predecessors (SAP R/2 & SAP R/3). As the name suggests, SAP ERP is an ERP system, which basically means that it supports a wide range of business processes from warehouse management and sales to HR, business intelligence, etc.
Although SAP ERP isn't the only software sold by SAP, people are typically refering to SAP ERP when they say "they're using SAP at work". It's important to note, though, that SAP is the name of the company and no software is sold or licensed as just "SAP".
ABAP is a 4GL programming language created by SAP, and commonly compared with OpenEdge ABL or COBOL. Much of SAP's software is written in ABAP. SAP provides an ABAP Workbench, which is a collection of tools that allows third party developers to develop, test and run custom ABAP programs within the SAP ERP system. The ABAP Workbench is typically used only when business logic cannot be implemented in SAP ERP by means of mere configuration.
On Windows I found the answer https://stackoverflow.com/a/13706972/3014879 using
fileIsLocked = !file.renameTo(file)
most useful, as it avoids false positives when processing write protected (or readonly) files.
Use GetParent()
as shown, works nicely. Add error checking as you need.
var fn = openFileDialogSapTable.FileName;
var currentPath = Path.GetFullPath( fn );
currentPath = Directory.GetParent(currentPath).FullName;
Today I had a scenario, where I was performing following:
myViewGroup.setVisibility(View.GONE);
Right on the next frame I was performing an if
check somewhere else for visibility state of that view. Guess what? The following condition was passing:
if(myViewGroup.getVisibility() == View.VISIBLE) {
// this `if` was fulfilled magically
}
Placing breakpoints you can see, that visibility changes to GONE
, but right on the next frame it magically becomes VISIBLE
. I was trying to understand how the hell this could happen.
Turns out there was an animation applied to this view, which internally caused the view to change it's visibility to VISIBLE
until finishing the animation:
public void someFunction() {
...
TransitionManager.beginDelayedTransition(myViewGroup);
...
myViewGroup.setVisibility(View.GONE);
}
If you debug, you'll see that myViewGroup
indeed changes its visibility to GONE
, but right on the next frame it would again become visible in order to run the animation.
So, if you come across with such a situation, make sure you are not performing an if
check in amidst of animating the view.
You can remove all animations on the view via View.clearAnimation()
.
(EDITED) I made it so it stops after 100 times
@echo off
goto actual
set /a loopcount=0
:actual
set /a loopcount=%loopcount% + 1
echo %random% %random% %random% %random%
timeout 1 /nobreak>nul
if %loopcount%== 100 goto stop
goto actual
:stop
exit
This will generate 4 random numbers ever 1 second 100 times. Take out the "timeout 1 /nobreak>nul" to make it go super fast.
It's not a direct answer to the question but you could just use the OR-operator
( grep "#SystemMaxUse=" journald.conf > /dev/null && sed -i 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf ) || echo "This file has been edited. You'll need to do it manually."
'nunique' is an option for .agg() since pandas 0.20.0, so:
df.groupby('date').agg({'duration': 'sum', 'user_id': 'nunique'})
There is no native but what if you use what I put in this post:
How to parse excel rows back to types using EPPlus
If you want to point it at a table only it will need to be modified. Something like this should do it:
public static IEnumerable<T> ConvertTableToObjects<T>(this ExcelTable table) where T : new()
{
//DateTime Conversion
var convertDateTime = new Func<double, DateTime>(excelDate =>
{
if (excelDate < 1)
throw new ArgumentException("Excel dates cannot be smaller than 0.");
var dateOfReference = new DateTime(1900, 1, 1);
if (excelDate > 60d)
excelDate = excelDate - 2;
else
excelDate = excelDate - 1;
return dateOfReference.AddDays(excelDate);
});
//Get the properties of T
var tprops = (new T())
.GetType()
.GetProperties()
.ToList();
//Get the cells based on the table address
var start = table.Address.Start;
var end = table.Address.End;
var cells = new List<ExcelRangeBase>();
//Have to use for loops insteadof worksheet.Cells to protect against empties
for (var r = start.Row; r <= end.Row; r++)
for (var c = start.Column; c <= end.Column; c++)
cells.Add(table.WorkSheet.Cells[r, c]);
var groups = cells
.GroupBy(cell => cell.Start.Row)
.ToList();
//Assume the second row represents column data types (big assumption!)
var types = groups
.Skip(1)
.First()
.Select(rcell => rcell.Value.GetType())
.ToList();
//Assume first row has the column names
var colnames = groups
.First()
.Select((hcell, idx) => new { Name = hcell.Value.ToString(), index = idx })
.Where(o => tprops.Select(p => p.Name).Contains(o.Name))
.ToList();
//Everything after the header is data
var rowvalues = groups
.Skip(1) //Exclude header
.Select(cg => cg.Select(c => c.Value).ToList());
//Create the collection container
var collection = rowvalues
.Select(row =>
{
var tnew = new T();
colnames.ForEach(colname =>
{
//This is the real wrinkle to using reflection - Excel stores all numbers as double including int
var val = row[colname.index];
var type = types[colname.index];
var prop = tprops.First(p => p.Name == colname.Name);
//If it is numeric it is a double since that is how excel stores all numbers
if (type == typeof(double))
{
if (!string.IsNullOrWhiteSpace(val?.ToString()))
{
//Unbox it
var unboxedVal = (double)val;
//FAR FROM A COMPLETE LIST!!!
if (prop.PropertyType == typeof(Int32))
prop.SetValue(tnew, (int)unboxedVal);
else if (prop.PropertyType == typeof(double))
prop.SetValue(tnew, unboxedVal);
else if (prop.PropertyType == typeof(DateTime))
prop.SetValue(tnew, convertDateTime(unboxedVal));
else
throw new NotImplementedException(String.Format("Type '{0}' not implemented yet!", prop.PropertyType.Name));
}
}
else
{
//Its a string
prop.SetValue(tnew, val);
}
});
return tnew;
});
//Send it back
return collection;
}
Here is a test method:
[TestMethod]
public void Table_To_Object_Test()
{
//Create a test file
var fi = new FileInfo(@"c:\temp\Table_To_Object.xlsx");
using (var package = new ExcelPackage(fi))
{
var workbook = package.Workbook;
var worksheet = workbook.Worksheets.First();
var ThatList = worksheet.Tables.First().ConvertTableToObjects<ExcelData>();
foreach (var data in ThatList)
{
Console.WriteLine(data.Id + data.Name + data.Gender);
}
package.Save();
}
}
Gave this in the console:
1JohnMale
2MariaFemale
3DanielUnknown
Just be careful if you Id field is an number or string in excel since the class is expecting a string.
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=
Creating it once and using it wherever needed is a good idea. Add this in your styles.xml:
<style name="Divider">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">1dp</item>
<item name="android:background">?android:attr/listDivider</item>
</style>
and add this in your xml code, where a line divider is needed:
<View style="@style/Divider"/>
Originally answered by toddles_fp to this question: Android Drawing Separator/Divider Line in Layout?
SELECT DATEPART(MM,'january '+'01 1900')
SELECT MONTH('january ' + '01 1900')
SELECT month(dateadd(month,DATEDIFF(month,0,'january 01 2015'),0))
Have a look at: https://developers.google.com/accounts/docs/OAuth2UserAgent#handlingtheresponse
It says:
Other parameters included in the response include
expires_in
andtoken_type
. These parameters describe the lifetime of the token in seconds...
/* Microsoft Edge Browser 12-18 (All versions before Chromium) - one-liner method */
_:-ms-lang(x), _:-webkit-full-screen, .selector { property:value; }
That works great!
// for instance:
_:-ms-lang(x), _:-webkit-full-screen, .headerClass
{
border: 1px solid brown;
}
https://jeffclayton.wordpress.com/2015/04/07/css-hacks-for-windows-10-and-spartan-browser-preview/
You need to pass a function to setTimeout
$(window).load(function () {
window.setTimeout(function () {
window.location.href = "https://www.google.co.in";
}, 5000)
});
Having spent lot of time trying to fix this. I had no luck with any solution provide here or elsewhere.
But then later realised it wasn't so much as just solving the issue. But you also need to RESTART the VSCODE for it to take affect.
First, backup
your existing repo:
(a) mkdir backup
(b) cd backup
(c) git clone non_bare_repo
Second, run the following:
git clone --bare -l non_bare_repo new_bare_repo
Just to improve Wael's answer and put it on a single line:
dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);
UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.
Simpler and better: For API >= 16
Simply add "parentActivityName" for each activity in Manifest. The back button will automatically take u to the parent activity.
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:label="@string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
You've already discovered the simplest way to specify a shallow clone in Git-SVN, by specifying the SVN revision number that you want to start your clone at ( -r$REV:HEAD
).
For example: git svn clone -s -r1450:HEAD some/svn/repo
Git's data structure is based on pointers in a directed acyclic graph (DAG), which makes it trivial to walk back n
commits. But in SVN ( and therefore in Git-SVN) you will have to find the revision number yourself.
First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php
) will display an identification form, asking for a login and password.
To get that form, you should not use :
$cfg['Servers'][$i]['auth_type'] = 'config';
But you should use :
$cfg['Servers'][$i]['auth_type'] = 'cookie';
(At least, that's what I have on a server which prompts for login/password, using a form)
For more informations, you can take a look at the documentation :
'config'
authentication ($auth_type = 'config'
) is the plain old way: username and password are stored in config.inc.php.'cookie'
authentication mode ($auth_type = 'cookie'
) as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.
DDL: Change the schema
DML: Change the data
Seems specific to MySQL limitations (rails's source code)
First add #include <cmath>
then
you can use pow
methode in your code for example :
pow(3.5, 3);
Which 3.5 is base and 3 is exp
Let me try to summarize the most important reasons for choosing field-based access. If you want to dive deeper, please read this article on my blog: Access Strategies in JPA and Hibernate – Which is better, field or property access?
Field-based access is by far the better option. Here are 5 reasons for it:
Reason 1: Better readability of your code
If you use field-based access, you annotate your entity attributes with your mapping annotations. By placing the definition of all entity attributes at the top of your class, you get a relatively compact view of all attributes and their mappings.
Reason 2: Omit getter or setter methods that shouldn’t be called by your application
Another advantage of field-based access is that your persistence provider, e.g., Hibernate or EclipseLink, doesn’t use the getter and setter methods of your entity attributes. That means that you don’t need to provide any method that shouldn’t be used by your business code. This is most often the case for setter methods of generated primary key attributes or version columns. Your persistence provider manages the values of these attributes, and you should not set them programmatically.
Reason 3: Flexible implementation of getter and setter methods
Because your persistence provider doesn’t call the getter and setter methods, they are not forced to fulfill any external requirements. You can implement these methods in any way you want. That enables you to implement business-specific validation rules, to trigger additional business logic or to convert the entity attribute into a different data type.
You can, for example, use that to wrap an optional association or attribute into a Java Optional
.
Reason 4: No need to mark utility methods as @Transient
Another benefit of the field-based access strategy is that you don’t need to annotate your utility methods with @Transient
. This annotation tells your persistence provider that a method or attribute is not part of the entity persistent state. And because with field-type access the persistent state gets defined by the attributes of your entity, your JPA implementation ignores all methods of your entity.
Reason 5: Avoid bugs when working with proxies
Hibernate uses proxies for lazily fetched to-one associations so that it can control the initialization of these associations. That approach works fine in almost all situations. But it introduces a dangerous pitfall if you use property-based access.
If you use property-based access, Hibernate initializes the attributes of the proxy object when you call the getter method. That’s always the case if you use the proxy object in your business code. But quite a lot of equals and hashCode implementations access the attributes directly. If this is the first time you access any of the proxy attributes, these attributes are still uninitialized.
python enumerate
function will be satisfied your requirements
result = list(enumerate([1,3,7,12]))
print result
output
[(0, 1), (1, 3), (2, 7),(3,12)]
You can use sp_MSforeachdb to search all databases.
declare @RETURN_VALUE int
declare @command1 nvarchar(2000)
set @command1 = "Your command goes here"
exec @RETURN_VALUE = sp_MSforeachdb @command1 = @command1
Raj
This..
(
(meta_key = 'lat' AND meta_value >= '60.23457047672217')
OR
(meta_key = 'lat' AND meta_value <= '60.23457047672217')
)
is the same as
(
(meta_key = 'lat')
)
Adding it all together (the same applies to the long
filter) you have this impossible WHERE clause which will give no rows because meta_key
cannot be 2 values in one row
WHERE
(meta_key = 'lat' AND meta_key = 'long' )
You need to review your operators to make sure you get the correct logic
.so
files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.
.a
files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar
command -- a predecessor of tar
that's now just used for making libraries) of the original .o object files.
.la
files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?
Static and dynamic libraries each have pros and cons.
Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.
Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.
Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.
Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.
Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.
Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.
Dynamic libraries are especially useful for system libraries, like libc
. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.
I solved this,
1) by creating new commit with changes i want..
r8gs4r commit 0
2) i know which commit i need to merge with it. which is commit 3.
so, git rebase -i HEAD~4
# 4 represents recent 4 commit (here commit 3 is in 4th place)
3) in interactive rebase recent commit will located at bottom. it will looks alike,
pick q6ade6 commit 3
pick vr43de commit 2
pick ac123d commit 1
pick r8gs4r commit 0
4) here we need to rearrange commit if you want to merge with specific one. it should be like,
parent
|_child
pick q6ade6 commit 3
f r8gs4r commit 0
pick vr43de commit 2
pick ac123d commit 1
after rearrange you need to replace p
pick
with f
(fixup will merge without commit message) or s
(squash merge with commit message can change in run time)
and then save your tree.
now merge done with existing commit.
Note: Its not preferable method unless you're maintain on your own. if you have big team size its not a acceptable method to rewrite git tree will end up in conflicts which you know other wont. if you want to maintain you tree clean with less commits can try this and if its small team otherwise its not preferable.....
I find the solution in spring.io,like this:
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
ALTER TABLE YourTable ALTER COLUMN YourColumn columnType NULL
The optimal solution is probably one that does not include an additional database read operation prior to saving the model instance, nor any further django-library. This is why laffuste's solutions is preferable. In the context of an admin site, one can simply override the save_model
-method, and invoke the form's has_changed
method there, just as in Sion's answer above. You arrive at something like this, drawing on Sion's example setting but using changed_data
to get every possible change:
class ModelAdmin(admin.ModelAdmin):
fields=['name','mode']
def save_model(self, request, obj, form, change):
form.changed_data #output could be ['name']
#do somethin the changed name value...
#call the super method
super(self,ModelAdmin).save_model(request, obj, form, change)
save_model
:https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model
changed_data
-method for a Field:https://docs.djangoproject.com/en/1.10/ref/forms/api/#django.forms.Form.changed_data
Alternatively,
select id from call
minus
select id from phone_number
Today not working adjustResize on full screen issue is actual for android sdk.
From answers i found:
the solution - but solution has this showing on picture issue :
Than i found the solution and remove the one unnecessary action:
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
So, see my fixed solution code on Kotlin:
class AndroidBug5497Workaround constructor(val activity: Activity) {
private val content = activity.findViewById<View>(android.R.id.content) as FrameLayout
private val mChildOfContent = content.getChildAt(0)
private var usableHeightPrevious: Int = 0
private val contentContainer = activity.findViewById(android.R.id.content) as ViewGroup
private val rootView = contentContainer.getChildAt(0)
private val rootViewLayout = rootView.layoutParams as FrameLayout.LayoutParams
private val listener = {
possiblyResizeChildOfContent()
}
fun addListener() {
mChildOfContent.apply {
viewTreeObserver.addOnGlobalLayoutListener(listener)
}
}
fun removeListener() {
mChildOfContent.apply {
viewTreeObserver.removeOnGlobalLayoutListener(listener)
}
}
private fun possiblyResizeChildOfContent() {
val contentAreaOfWindowBounds = Rect()
mChildOfContent.getWindowVisibleDisplayFrame(contentAreaOfWindowBounds)
val usableHeightNow = contentAreaOfWindowBounds.height()
if (usableHeightNow != usableHeightPrevious) {
rootViewLayout.height = usableHeightNow
rootView.layout(contentAreaOfWindowBounds.left,
contentAreaOfWindowBounds.top, contentAreaOfWindowBounds.right, contentAreaOfWindowBounds.bottom);
mChildOfContent.requestLayout()
usableHeightPrevious = usableHeightNow
}
}
}
My bug fixing implement code:
class LeaveDetailActivity : BaseActivity(){
private val keyBoardBugWorkaround by lazy {
AndroidBug5497Workaround(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onResume() {
keyBoardBugWorkaround.addListener()
super.onResume()
}
override fun onPause() {
keyBoardBugWorkaround.removeListener()
super.onPause()
}
}
No need for array. Just use something like this:
Sub ARRAYER()
Dim Rng As Range
Dim Number_of_Sims As Long
Dim i As Long
Number_of_Sims = 10
Set Rng = Range("C4:G4")
For i = 1 To Number_of_Sims
Rng.Offset(i, 0).Value = Rng.Value
Worksheets("Sheetname").Calculate 'replacing Sheetname with name of your sheet
Next
End Sub
If you are using the default template that is created when you select a new ASP.net Web application and selected Individual User accounts as Authentication and trying to create users with Roles so here is the solution. In the Account Controller's Register method which is called using [HttpPost], add the following lines in if condition
.
using Microsoft.AspNet.Identity.EntityFramework;
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
var roleManager = new RoleManager<IdentityRole>(roleStore);
if(!await roleManager.RoleExistsAsync("YourRoleName"))
await roleManager.CreateAsync(new IdentityRole("YourRoleName"));
await UserManager.AddToRoleAsync(user.Id, "YourRoleName");
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
This will create first create a role in your database and then add the newly created user to this role.
I've worked with a lot of CSV files in my time. I'd like to add the advice:
1 - Depending on the source (Excel, etc), commas or tabs may be embedded in a field. Usually, the rule is that they will be 'protected' because the field will be double-quote delimited, as in "Boston, MA 02346".
2 - Some sources will not double-quote delimit all text fields. Other sources will. Others will delimit all fields, even numerics.
3 - Fields containing double-quotes usually get the embedded double quotes doubled up (and the field itself delimited with double quotes, as in "George ""Babe"" Ruth".
4 - Some sources will embed CR/LFs (Excel is one of these!). Sometimes it'll be just a CR. The field will usually be double-quote delimited, but this situation is very difficult to handle.
Use jQuery multiple-selector if the only difference between the two functions is the value of the button being triggered.
$("#button_1, #button_2").on("click", function(e) {
e.preventDefault();
$.ajax({type: "POST",
url: "/pages/test/",
data: { id: $(this).val(), access_token: $("#access_token").val() },
success:function(result) {
alert('ok');
},
error:function(result) {
alert('error');
}
});
});
As it's not specified if you mean the system's current date or the date held in a variable, I'll answer for latter with an example.
<?php
$dateAsString = "Wed, 11 Apr 2018 19:00:00 -0500";
// This converts it to a unix timestamp so that the date() function can work with it.
$dateAsUnixTimestamp = strtotime($dateAsString);
// Output it month is various formats according to http://php.net/date
echo date('M',$dateAsUnixTimestamp);
// Will output Apr
echo date('n',$dateAsUnixTimestamp);
// Will output 4
echo date('m',$dateAsUnixTimestamp);
// Will output 04
?>
File pathToBinary = new File("C:\\user\\Programme\\FirefoxPortable\\App\\Firefox\\firefox.exe");
FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();
WebDriver driver = new FirefoxDriver(ffBinary,firefoxProfile);
you can achieve this by using below in the commandline itself
-e for error_x000D_
-X for debug_x000D_
-q for only error
_x000D_
e.g :
mvn test -X -DsomeProperties='SomeValue' [For Debug level Logs]_x000D_
mvn test -e -DsomeProperties='SomeValue' [For Error level Logs]_x000D_
mvn test -q -DsomeProperties='SomeValue' [For Only Error Logs]
_x000D_
The most common cause of this problem is that Matlab cannot find the file on it's search path. Basically, Matlab looks for files in:
pwd
);path
at the command line) @(whatever the class of the first argument is)
that is in any directory above.As someone else suggested, you can use the command which
, but that is often unhelpful in this case - it tells you Matlab can't find the file, which you knew already.
So the first thing to do is make sure the file is locatable on the path.
Next thing to do is make sure that the file that matlab is finding (use which) requires the same type as the first argument you are actually passing. I.el, If w
is supposed to be different class, and there is a divrat
function there, but w
is actually empty, []
, so matlab is looking for Double/divrat
, when there is only a @(yourclass)/divrat.
This is just speculation on my part, but this often bites me.
For Alpine Linux:
apk add openssl-dev
Others have answered in terms of how to handle the specific escaping in this case.
A broader answer is not to try to do it yourself. Use an XML API - there are plenty available for just about every modern programming platform in existence.
XML APIs will handle things like this for you automatically, making it a lot harder to go wrong. Unless you're writing an XML API yourself, you should rarely need to worry about the details like this.
I added the .resx file via Visual Studio. This created a designer.cs
file with properties to immediately return the value of any key I wanted. For example, this is some auto-generated code from the designer file.
/// <summary>
/// Looks up a localized string similar to When creating a Commissioning change request, you must select valid Assignees, a Type, a Component, and at least one (1) affected unit..
/// </summary>
public static string MyErrorMessage {
get {
return ResourceManager.GetString("MyErrorMessage", resourceCulture);
}
}
That way, I was able to simply do:
string message = Errors.MyErrorMessage;
Where Errors
is the Errors.resx
file created through Visual Studio and MyErrorMessage
is the key.
try using apply function.
df['quantity'] = df['quantity'].apply(lambda x: x*-1)
The syntax is changed in new 3.x releases rather than old 2.x releases: for example in python 2.x you can write: print "Hi new world" but in the new 3.x release you need to use the new syntax and write it like this: print("Hi new world")
check the documentation: http://docs.python.org/3.3/library/functions.html?highlight=print#print
Another solution you can use is SQL Developer.
With it, you have the ability to import from a csv file (other delimited files are available).
Just open the table view, then:
You have the option to have SQL Developer do the inserts for you, create an sql insert script, or create the data for a SQL Loader script (have not tried this option myself).
Of course all that is moot if you can only use the command line, but if you are able to test it with SQL Developer locally, you can always deploy the generated insert scripts (for example).
Just adding another option to the 2 already very good answers.
I see that a few important reasons for doing as few new's as possible are missed:
new
has a non-deterministic execution timeCalling new
may or may not cause the OS to allocate a new physical page to your process this can be quite slow if you do it often. Or it may already have a suitable memory location ready, we don't know. If your program needs to have consistent and predictable execution time (like in a real-time system or game/physics simulation) you need to avoid new
in your time critical loops.
new
is an implicit thread synchronizationYes you heard me, your OS needs to make sure your page tables are consistent and as such calling new
will cause your thread to acquire an implicit mutex lock. If you are consistently calling new
from many threads you are actually serialising your threads (I've done this with 32 CPUs, each hitting on new
to get a few hundred bytes each, ouch! that was a royal p.i.t.a. to debug)
The rest such as slow, fragmentation, error prone, etc have already been mentioned by other answers.
A combination of the regex and SimpleDateFormat is the right answer i believe. SimpleDateFormat does not catch exception if the individual components are invalid meaning, Format Defined: yyyy-mm-dd input: 201-0-12 No exception will be thrown.This case should have been handled. But with the regex as suggested by Sok Pomaranczowy and Baby will take care of this particular case.
The real answer is : It depends
There are a couple factors to consider, the most obvious are : the cpu you are running these algorithms on and the implementation of the algorithms.
For instance, me and my friend both run the exact same openssl version and get slightly different results with different Intel Core i7 cpus.
My test at work with an Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz
The 'numbers' are in 1000s of bytes per second processed.
type 16 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes
md5 64257.97k 187370.26k 406435.07k 576544.43k 649827.67k
sha1 73225.75k 202701.20k 432679.68k 601140.57k 679900.50k
And his with an Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz
The 'numbers' are in 1000s of bytes per second processed.
type 16 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes
md5 51859.12k 156255.78k 350252.00k 513141.73k 590701.52k
sha1 56492.56k 156300.76k 328688.76k 452450.92k 508625.68k
We both are running the exact same binaries of OpenSSL 1.0.1j 15 Oct 2014 from the ArchLinux official package.
My opinion on this is that with the added security of sha1, cpu designers are more likely to improve the speed of sha1 and more programmers will be working on the algorithm's optimization than md5sum.
I guess that md5 will no longer be used some day since it seems that it has no advantage over sha1. I also tested some cases on real files and the results were always the same in both cases (likely limited by disk I/O).
md5sum of a large 4.6GB file took the exact same time than sha1sum of the same file, same goes with many small files (488 in the same directory). I ran the tests a dozen times and they were consitently getting the same results.
--
It would be very interesting to investigate this further. I guess there are some experts around that could provide a solid answer to why sha1 is getting faster than md5 on newer processors.
You need to load jquery first before bootstrap.
require.config({
paths: {
jquery: 'libs/jquery/jquery',
underscore: 'libs/underscore/underscore',
backbone: 'libs/backbone/backbone',
bootstrap: 'libs/bootstrap',
jquerytablesorter: 'libs/tablesorter/jquery.tablesorter',
tablesorter: 'libs/tablesorter/tables',
ajaxupload: 'libs/ajax-upload',
templates: '../templates'
},
shim: {
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'jquery': {
exports: '$'
},
'bootstrap': {
deps: ['jquery'],
exports: '$'
},
'jquerytablesorter': {
deps: ['jquery'],
exports: '$'
},
'tablesorter': {
deps: ['jquery'],
exports: '$'
},
'ajaxupload': {
deps: ['jquery'],
exports: '$'
},
'underscore': {
exports: '_'
},
}
});
require(['app', ], function(App) {
App.initialize();
});
Works like charm! quick and easy fix.
Here is an example I just used:
at 8am /EVERY:M,T,W,Th,F,S,Su cmd /c c:\myapp.exe
The result was:
Added a new job with job ID = 1
Then, to check my work:
at
np.insert can also be used for the purpose
import numpy as np
a = np.array([[1, 3, 4],
[1, 2, 3],
[1, 2, 1]])
x = 5
index = 3 # the position for x to be inserted before
np.insert(a, index, x, axis=1)
array([[1, 3, 4, 5],
[1, 2, 3, 5],
[1, 2, 1, 5]])
index
can also be a list
/tuple
>>> index = [1, 1, 3] # equivalently (1, 1, 3)
>>> np.insert(a, index, x, axis=1)
array([[1, 5, 5, 3, 4, 5],
[1, 5, 5, 2, 3, 5],
[1, 5, 5, 2, 1, 5]])
or a slice
>>> index = slice(0, 3)
>>> np.insert(a, index, x, axis=1)
array([[5, 1, 5, 3, 5, 4],
[5, 1, 5, 2, 5, 3],
[5, 1, 5, 2, 5, 1]])
The getWidth method of the Display object is deprecated. Override onSizeChanged to get the size of the WebView when it becomes available.
WebView webView = new WebView(context) {
@Override
protected void onSizeChanged(int w, int h, int ow, int oh) {
// if width is zero, this method will be called again
if (w != 0) {
Double scale = Double.valueOf(w) / Double.valueOf(WEB_PAGE_WIDTH);
scale *= 100d;
setInitialScale(scale.intValue());
}
super.onSizeChanged(w, h, ow, oh);
}
};
I agree that @DaveAbrahams's answer using the bisect module is the correct approach. He did not mention one important detail in his answer.
From the docs bisect.bisect_left(a, x, lo=0, hi=len(a))
The bisection module does not require the search array to be precomputed ahead of time. You can just present the endpoints to the bisect.bisect_left
instead of it using the defaults of 0
and len(a)
.
Even more important for my use, looking for a value X such that the error of a given function is minimized. To do that, I needed a way to have the bisect_left's algorithm call my computation instead. This is really simple.
Just provide an object that defines __getitem__
as a
For example, we could use the bisect algorithm to find a square root with arbitrary precision!
import bisect
class sqrt_array(object):
def __init__(self, digits):
self.precision = float(10**(digits))
def __getitem__(self, key):
return (key/self.precision)**2.0
sa = sqrt_array(4)
# "search" in the range of 0 to 10 with a "precision" of 0.0001
index = bisect.bisect_left(sa, 7, 0, 10*10**4)
print 7**0.5
print index/(10**4.0)
Try rewriting your success handler to:
success : handleData
The success property of the ajax method only requires a reference to a function.
In your handleData function you can take up to 3 parameters:
object data
string textStatus
jqXHR jqXHR
Edit: This library is now available through Bower and NPM. See github repo for details.
UPDATED ANSWER:
Disclaimer: I'm the author.
Here's a few things you can do using the latest version (Responsive Bootstrap Toolkit 2.5.0):
// Wrap everything in an IIFE
(function($, viewport){
// Executes only in XS breakpoint
if( viewport.is('xs') ) {
// ...
}
// Executes in SM, MD and LG breakpoints
if( viewport.is('>=sm') ) {
// ...
}
// Executes in XS and SM breakpoints
if( viewport.is('<md') ) {
// ...
}
// Execute only after document has fully loaded
$(document).ready(function() {
if( viewport.is('xs') ) {
// ...
}
});
// Execute code each time window size changes
$(window).resize(
viewport.changed(function() {
if( viewport.is('xs') ) {
// ...
}
})
);
})(jQuery, ResponsiveBootstrapToolkit);
As of version 2.3.0, you don't need the four <div>
elements mentioned below.
ORIGINAL ANSWER:
I don't think you need any huge script or library for that. It's a fairly simple task.
Insert the following elements just before </body>
:
<div class="device-xs visible-xs"></div>
<div class="device-sm visible-sm"></div>
<div class="device-md visible-md"></div>
<div class="device-lg visible-lg"></div>
These 4 divs allow you check for currently active breakpoint. For an easy JS detection, use the following function:
function isBreakpoint( alias ) {
return $('.device-' + alias).is(':visible');
}
Now to perform a certain action only on the smallest breakpoint you could use:
if( isBreakpoint('xs') ) {
$('.someClass').css('property', 'value');
}
Detecting changes after DOM ready is also fairly simple. All you need is a lightweight window resize listener like this one:
var waitForFinalEvent = function () {
var b = {};
return function (c, d, a) {
a || (a = "I am a banana!");
b[a] && clearTimeout(b[a]);
b[a] = setTimeout(c, d)
}
}();
var fullDateString = new Date();
Once you're equipped with it, you can start listening for changes and execute breakpoint-specific functions like so:
$(window).resize(function () {
waitForFinalEvent(function(){
if( isBreakpoint('xs') ) {
$('.someClass').css('property', 'value');
}
}, 300, fullDateString.getTime())
});
If you want to delete rows based on multiple values of the column, you could use:
df[(df.line_race != 0) & (df.line_race != 10)]
To drop all rows with values 0 and 10 for line_race
.
Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.
*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.
I used this code to write directly to the event log Application:
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1);
}
As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources @ Windows Dev Center (I bolded the part which refers to source name):
Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.
Assuming you are writing a bootloader or other application that has access to the BIOS, here is a rough sketch of what you can do:
Here is my implementation of this:
; Prints AL in hex.
printhexb:
push ax
shr al, 0x04
call print_nibble
pop ax
and al, 0x0F
call print_nibble
ret
print_nibble:
cmp al, 0x09
jg .letter
add al, 0x30
mov ah, 0x0E
int 0x10
ret
.letter:
add al, 0x37
mov ah, 0x0E
int 0x10
ret
I faced Similar issue in Eclipse Indigo. I changed the HeapSize it started working correctly. I just added following eclipse.ini file -vmargs -Xms1024m -Xmx1024m
It worked fine after increasing the VM size
Add below line(s) in file ~/.wgetrc or /etc/wgetrc (create the file if it is not there):
http_proxy = http://[Proxy_Server]:[port]
https_proxy = http://[Proxy_Server]:[port]
ftp_proxy = http://[Proxy_Server]:[port]
For more information, https://www.thegeekdiary.com/how-to-use-wget-to-download-file-via-proxy/
Empty Collection. If you're using C#, the assumption is that maximizing system resources is not essential. While less efficient, returning Empty Collection is much more convenient for the programmers involved (for the reason Will outlined above).
I've used Perfect Full Page Background Image to accomplish this on a previous site.
You can use background-size: cover; if you only need to support modern browsers.
A more convenient way:
Create an executable script as mentioned above:
#!/bin/sh
cd /Applications/Adobe\ Flash\ Builder\ 4.6
open -n Adobe\ Flash\ Builder\ 4.6.app
In you current instance of Flashbuilder or Eclipse, add a new external tool configuration. This is the button next to the debug/run/profile buttons on your toolbar. In that dialog, click on "Program" and add a new one. Give it the name you want and in the "Location" field, put the path to the script from step 1:
/Users/username/bin/flashbuilder
You can stop at step 2, but I prefer adding a custom icon to the toolbar. I use a the Quick Launch plugin to do that:
After adding the plugin, go to "Run"->"Organize Quick Lauches" and add the external tool config from step 2. Then you can configure the icon for it.
After you save that, you'll see the icon in your toolbar. Now you can just click it every time you want a new Flashbuilder/Eclipse instance.
When you source, you're loading the activate script into your active shell.
When you do it in a script, you load it into that shell which exits when your script finishes and you're back to your original, unactivated shell.
Your best option would be to do it in a function
activate () {
. ../.env/bin/activate
}
or an alias
alias activate=". ../.env/bin/activate"
Hope this helps.
Maybe it will be helpfull for you. You could use "DirectoryInfo.EnumerateFiles" method and handle UnauthorizedAccessException as you need.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
DirectoryInfo diTop = new DirectoryInfo(@"d:\");
try
{
foreach (var fi in diTop.EnumerateFiles())
{
try
{
// Display each file over 10 MB;
if (fi.Length > 10000000)
{
Console.WriteLine("{0}\t\t{1}", fi.FullName, fi.Length.ToString("N0"));
}
}
catch (UnauthorizedAccessException UnAuthTop)
{
Console.WriteLine("{0}", UnAuthTop.Message);
}
}
foreach (var di in diTop.EnumerateDirectories("*"))
{
try
{
foreach (var fi in di.EnumerateFiles("*", SearchOption.AllDirectories))
{
try
{
// Display each file over 10 MB;
if (fi.Length > 10000000)
{
Console.WriteLine("{0}\t\t{1}", fi.FullName, fi.Length.ToString("N0"));
}
}
catch (UnauthorizedAccessException UnAuthFile)
{
Console.WriteLine("UnAuthFile: {0}", UnAuthFile.Message);
}
}
}
catch (UnauthorizedAccessException UnAuthSubDir)
{
Console.WriteLine("UnAuthSubDir: {0}", UnAuthSubDir.Message);
}
}
}
catch (DirectoryNotFoundException DirNotFound)
{
Console.WriteLine("{0}", DirNotFound.Message);
}
catch (UnauthorizedAccessException UnAuthDir)
{
Console.WriteLine("UnAuthDir: {0}", UnAuthDir.Message);
}
catch (PathTooLongException LongPath)
{
Console.WriteLine("{0}", LongPath.Message);
}
}
}
I have used this technique successfully in the past:
Using Excel to generate Inserts for SQL Server
(...) Skip a column (or use it for notes) and then type something like the following formula in it:
="insert into tblyourtablename (yourkeyID_pk, intmine, strval) values ("&A4&", "&B4&", N'"&C4&"')"
Now you’ve got your insert statement for a table with your primary key (PK), an integer and a unicode string. (...)
I was receiving this error when I installed a clean Node dev environment on windows.
To fix this, I went into my new project directory (that I just scaffolded with yo angular
) and typed in two commands:
npm install -g grunt --save-dev
That will install the local grunt dependencies to your project. Next:
npm install
That will ensure all your (new) project dependencies are installed.
Tada!
I think the problem is that you think the statement ...
x = Integer.valueOf(9);
... causes that the value of '9' get 'stored' into(!) the Object on which x is referencing.
But thats wrong.
Instead the statement causes something similar as if you would call
x = new Integer(9);
If you have a look to the java source code, you will see what happens in Detail.
Here is the code of the "valueOf(int i)" method in the "Integer" class:
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
and further, whenever the IntegerCache class is used for the first time the following script gets invoked:
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
You see that either a new Integer Object is created with "new Integer(i)" in the valueOf method ... ... or a reference to a Integer Object which is stored in the IntegerCache is returned.
In both cases x will reference to a new Object.
And this is why the reference to the Object in your list get lost when you call ...
x = Integer.valueOf(9);
Instead of doing so, in combination with a ListIterator use ...
i.set(Integer.valueOf(9));
... after you got the element you want to change with ...
i.next();
I had a span that would create a popup. If I used "click touchstart" it would trigger parts of the popup during the touchend. I fixed this by making the span "click touchend".
On ADT-bundled Eclipse I had to first uninstall the ADT and then do a fresh install.
To remove the ADT plugin from Eclipse:
Ok it looks like NPM is using your .gitignore
as a base for the .npmignore
file, and thus ignores /lib
. If you add a blank .npmignore
file into the root of your application, everything should work.
[edit] - more info on this behaviour here: https://docs.npmjs.com/misc/developers#keeping-files-out-of-your-package
Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.
set nocount on
create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)
insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)
declare @PersonID int
set @PersonID = 1
IF EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Posted_Flag = 1
AND Staff_Id = @PersonID
)
BEGIN
RAISERROR('Timesheets have already been posted!', 16, 1)
ROLLBACK TRAN
END
ELSE
IF NOT EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Staff_Id = @PersonID
)
BEGIN
RAISERROR('Default list has not been loaded!', 16, 1)
ROLLBACK TRAN
END
ELSE
print 'No problems here'
drop table Timesheet_Hours
you should use []
var x = ConfigurationManager.AppSettings["APIKey"];
This is is the same as a weighted average problem where all the weights are the same, and there are two dimensions.
Find the average of all latitudes for your center latitude and the average of all longitudes for the center longitude.
Caveat Emptor: This is a close distance approximation and the error will become unruly when the deviations from the mean are more than a few miles due to the curvature of the Earth. Remember that latitudes and longitudes are degrees (not really a grid).
It seems having msysgit (Git for Windows) installed is causing the problem.
In most cases you'll have a pretty recent version of Git for Windows installed. Cited from https://code.google.com/p/tortoisegit/:
There was a security issue in Git, see here. Git for Windows < 1.9.5 is affected - so you should update, TortoiseGit itself is not affected (using the default configuration; only if libgit2 is manually enabled for checkout/fetching). TortoiseGit 1.8.13.0 includes all fixes.
But it seems Aptana Studio Installer won't accept any pre-installed version of Git for Windows!
What you need to do:
That's it !!!
try setting this
CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
in {$tomcat-folder}\bin\setenv.sh
(create it if necessary).
See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.
But that doesn't seem like the proper way to do it..
That is indeed the proper way to do it (or at least a proper way to do it). This is a key aspect of promises, they're a pipeline, and the data can be massaged by the various handlers in the pipeline.
Example:
const promises = [_x000D_
new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
.then(data => {_x000D_
console.log("First handler", data);_x000D_
return data.map(entry => entry * 10);_x000D_
})_x000D_
.then(data => {_x000D_
console.log("Second handler", data);_x000D_
});
_x000D_
(catch
handler omitted for brevity. In production code, always either propagate the promise, or handle rejection.)
The output we see from that is:
First handler [1,2] Second handler [10,20]
...because the first handler gets the resolution of the two promises (1
and 2
) as an array, and then creates a new array with each of those multiplied by 10 and returns it. The second handler gets what the first handler returned.
If the additional work you're doing is synchronous, you can also put it in the first handler:
Example:
const promises = [_x000D_
new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
.then(data => {_x000D_
console.log("Initial data", data);_x000D_
data = data.map(entry => entry * 10);_x000D_
console.log("Updated data", data);_x000D_
return data;_x000D_
});
_x000D_
...but if it's asynchronous you won't want to do that as it ends up getting nested, and the nesting can quickly get out of hand.
After having a chance to study the Express 3 API Reference a bit more I discovered what I was looking for. Specifically the entries for app.locals
and then a bit farther down res.locals
held the answers I needed.
I discovered for myself that the function app.locals
takes an object and stores all of its properties as global variables scoped to the application. These globals are passed as local variables to each view. The function res.locals
, however, is scoped to the request and thus, response local variables are accessible only to the view(s) rendered during that particular request/response.
So for my case in my app.js
what I did was add:
app.locals({
site: {
title: 'ExpressBootstrapEJS',
description: 'A boilerplate for a simple web application with a Node.JS and Express backend, with an EJS template with using Twitter Bootstrap.'
},
author: {
name: 'Cory Gross',
contact: '[email protected]'
}
});
Then all of these variables are accessible in my views as site.title
, site.description
, author.name
, author.contact
.
I could also define local variables for each response to a request with res.locals
, or simply pass variables like the page's title in as the options
parameter in the render
call.
EDIT: This method will not allow you to use these locals in your middleware. I actually did run into this as Pickels suggests in the comment below. In this case you will need to create a middleware function as such in his alternative (and appreciated) answer. Your middleware function will need to add them to res.locals
for each response and then call next
. This middleware function will need to be placed above any other middleware which needs to use these locals.
EDIT: Another difference between declaring locals via app.locals
and res.locals
is that with app.locals
the variables are set a single time and persist throughout the life of the application. When you set locals with res.locals
in your middleware, these are set everytime you get a request. You should basically prefer setting globals via app.locals
unless the value depends on the request req
variable passed into the middleware. If the value doesn't change then it will be more efficient for it to be set just once in app.locals
.
Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'")
If rows.Count > 0 Then
searchedValue = rows(0).Item("ColumnName2")
End If
With FirstOrDefault
:
Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
searchedValue = row.Item("ColumnName2")
End If
In C#:
var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault();
if (row != null)
searchedValue = row["ColumnName2"];
A common case for simply setting -fpermissive and not sweating it exists: the thoroughly-tested and working third-party library that won't compile on newer compiler versions without -fpermissive. These libraries exist, and are very likely not the application developer's problem to solve, nor in the developer's schedule budget to do it.
Set -fpermissive and move on in that case.
there are lots of compression methods that work recursively command line and its good to know who the end audience is.
i.e. if it is to be sent to someone running windows then zip would probably be best:
zip -r file.zip folder_to_zip
unzip filenname.zip
for other linux users or your self tar is great
tar -cvzf filename.tar.gz folder
tar -cvjf filename.tar.bz2 folder # even more compression
#change the -c to -x to above to extract
One must be careful with tar and how things are tarred up/extracted, for example if I run
cd ~
tar -cvzf passwd.tar.gz /etc/passwd
tar: Removing leading `/' from member names
/etc/passwd
pwd
/home/myusername
tar -xvzf passwd.tar.gz
this will create /home/myusername/etc/passwd
unsure if all versions of tar do this:
Removing leading `/' from member names
Without defaultdict:
words = "apple banana apple strawberry banana lemon"
my_count = {}
for word in words.split():
try: my_count[word] += 1
except KeyError: my_count[word] = 1
It's waiting for you to "push". Try:
$ git push
Also , with Anonymous types ( I prefer not to do this) -- this is just another approach.
void Main()
{
var x = new
{
items = new[]
{
new
{
name = "command", index = "X", optional = "0"
},
new
{
name = "command", index = "X", optional = "0"
}
}
};
JavaScriptSerializer js = new JavaScriptSerializer(); //system.web.extension assembly....
Console.WriteLine(js.Serialize(x));
}
result :
{"items":[{"name":"command","index":"X","optional":"0"},{"name":"command","index":"X","optional":"0"}]}
.NET 2.0 does not use lambda expressions. You need to compile to .NET 3.0 to use them.
In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:
user = UniversityDetails.objects.get(email=email)
is email a str
, or a None
? or an int
?
To remove spaces from left/right, use LTRIM/RTRIM. What you had
UPDATE *tablename*
SET *columnname* = LTRIM(RTRIM(*columnname*));
would have worked on ALL the rows. To minimize updates if you don't need to update, the update code is unchanged, but the LIKE expression in the WHERE clause would have been
UPDATE [tablename]
SET [columnname] = LTRIM(RTRIM([columnname]))
WHERE 32 in (ASCII([columname]), ASCII(REVERSE([columname])));
Note: 32 is the ascii code for the space character.
Select 4th option
$('#select').val($('#select option').eq(3).val());
Create a raw
android resource directory.
Once the raw directory is created, Make sure to add a valid media file
After following the above procedure, you should be able to access your media files by using R.raw.media_file
It is best to use native dictionaries and arrays because they have been optimized for use with swift. That being said you can use NS... classes in swift and I think this situation warrants that. Here is how you would implement it:
var path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist")
var dict = NSDictionary(contentsOfFile: path)
So far (in my opinion) this is the easiest and most efficient way to access a plist, but in the future I expect that apple will add more functionality (such as using plist) into native dictionaries.
I am not familiar with JXL and but we use POI. POI is well maintained and can handle both the binary .xls format and the new xml based format that was introduced in Office 2007.
CSV files are not excel files, they are text based files, so these libraries don't read them. You will need to parse out a CSV file yourself. I am not aware of any CSV file libraries, but I haven't looked either.
If you want to be correct, use INFORMATION_SCHEMA.
SELECT *
FROM information_schema.tables
WHERE table_schema = 'yourdb'
AND table_name = 'testtable'
LIMIT 1;
Alternatively, you can use SHOW TABLES
SHOW TABLES LIKE 'yourtable';
If there is a row in the resultset, table exists.
Try this
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.custom_actionbar, menu);
menu.setGroupVisible(...);
}
When you write an XML layout, it will be inflated by the Android OS which basically means that it will be rendered by creating view object in memory. Let's call that implicit inflation (the OS will inflate the view for you). For instance:
class Name extends Activity{
public void onCreate(){
// the OS will inflate the your_layout.xml
// file and use it for this activity
setContentView(R.layout.your_layout);
}
}
You can also inflate views explicitly by using the LayoutInflater
. In that case you have to:
LayoutInflater
View
For instance:
LayoutInflater inflater = LayoutInflater.from(YourActivity.this); // 1
View theInflatedView = inflater.inflate(R.layout.your_layout, null); // 2 and 3
setContentView(theInflatedView) // 4
the symbol ? after the int means that it can be nullable.
The ? symbol is usually used in situations whereby the variable can accept a null or an integer or alternatively, return an integer or null.
Hope the context of usage helps. In this way you are not restricted to solely dealing with integers.
For my case, I was using an Ivy repository, and my Gradle dependencies were stored in ~/.ivy2/
.
Two routes for this. One way would be to use regular expressions. You can find out more about regular expressions here. A good regular expression for this would be something like "\w+" Then count the number of matches.
If you don't want to go that route, you could have a boolean flag that remembers if the last character you've seen is a space. If it is, don't count it. So the center of the loop looks like this:
boolean prevCharWasSpace=true;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' ') {
prevCharWasSpace=true;
}
else{
if(prevCharWasSpace) wordChar++;
prevCharWasSpace = false;
}
}
Update
Using the split technique is exactly equivalent to what's happening here, but it doesn't really explain why it works. If we go back to our CS theory, we want to construct a Finite State Automa (FSA) that counts words. That FSA may appear as:
If you look at the code, it implements this FSA exactly. The prevCharWasSpace keeps track of which state we're in, and the str1.charAt('i') is decideds which edge (or arrow) is being followed. If you use the split method, a regular expression equivalent of this FSA is constructed internally, and is used to split the string into an array.
Using a terminal command i.e. "clear", in a script called from cron (no terminal) will trigger this error message. In your particular script, the smbmount command expects a terminal in which case the work-arounds above are appropriate.
Let me try to explain (more on Blog) :
Car
constructor var Car = function(){}
, this is how things are internally:
We have one {prototype}
hidden link to Function.prototype
which is not accessible and one prototype
link to Car.prototype
which is accessible and has an actual constructor
of Car
. Both Function.prototype and Car.prototype have hidden links to Object.prototype
.When we want to create two equivalent objects by using the new
operator and create
method then we have to do it like this: Honda = new Car();
and Maruti = Object.create(Car.prototype)
.
What is happening?
Honda = new Car();
— When you create an object like this then hidden {prototype}
property is pointed to Car.prototype
. So here, the {prototype}
of the Honda object will always be Car.prototype
— we don't have any option to change the {prototype}
property of the object. What if I want to change the prototype of our newly created object?
Maruti = Object.create(Car.prototype)
— When you create an object like this you have an extra option to choose your object's {prototype}
property. If you want Car.prototype as the {prototype}
then pass it as a parameter in the function. If you don't want any {prototype}
for your object then you can pass null
like this: Maruti = Object.create(null)
.
Conclusion — By using the method Object.create
you have the freedom to choose your object {prototype}
property. In new Car();
, you don't have that freedom.
Preferred way in OO JavaScript :
Suppose we have two objects a
and b
.
var a = new Object();
var b = new Object();
Now, suppose a
has some methods which b
also wants to access. For that, we require object inheritance (a
should be the prototype of b
only if we want access to those methods). If we check the prototypes of a
and b
then we will find out that they share the prototype Object.prototype
.
Object.prototype.isPrototypeOf(b); //true
a.isPrototypeOf(b); //false (the problem comes into the picture here).
Problem — we want object a
as the prototype of b
, but here we created object b
with the prototype Object.prototype
.
Solution — ECMAScript 5 introduced Object.create()
, to achieve such inheritance easily. If we create object b
like this:
var b = Object.create(a);
then,
a.isPrototypeOf(b);// true (problem solved, you included object a in the prototype chain of object b.)
So, if you are doing object oriented scripting then Object.create()
is very useful for inheritance.
I am using this code. You can also your this for getting city and other details about a Latitude and longitude :
public class getReverseGeoCoding {
private String Address1 = "", Address2 = "", City = "", State = "", Country = "", County = "", PIN = "";
public void getAddress() {
Address1 = "";
Address2 = "";
City = "";
State = "";
Country = "";
County = "";
PIN = "";
try {
JSONObject jsonObj = parser_Json.getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + Global.curLatitude + ","
+ Global.curLongitude + "&sensor=true&key=YOUR_API_KEY");
String Status = jsonObj.getString("status");
if (Status.equalsIgnoreCase("OK")) {
JSONArray Results = jsonObj.getJSONArray("results");
JSONObject zero = Results.getJSONObject(0);
JSONArray address_components = zero.getJSONArray("address_components");
for (int i = 0; i < address_components.length(); i++) {
JSONObject zero2 = address_components.getJSONObject(i);
String long_name = zero2.getString("long_name");
JSONArray mtypes = zero2.getJSONArray("types");
String Type = mtypes.getString(0);
if (TextUtils.isEmpty(long_name) == false || !long_name.equals(null) || long_name.length() > 0 || long_name != "") {
if (Type.equalsIgnoreCase("street_number")) {
Address1 = long_name + " ";
} else if (Type.equalsIgnoreCase("route")) {
Address1 = Address1 + long_name;
} else if (Type.equalsIgnoreCase("sublocality")) {
Address2 = long_name;
} else if (Type.equalsIgnoreCase("locality")) {
// Address2 = Address2 + long_name + ", ";
City = long_name;
} else if (Type.equalsIgnoreCase("administrative_area_level_2")) {
County = long_name;
} else if (Type.equalsIgnoreCase("administrative_area_level_1")) {
State = long_name;
} else if (Type.equalsIgnoreCase("country")) {
Country = long_name;
} else if (Type.equalsIgnoreCase("postal_code")) {
PIN = long_name;
}
}
// JSONArray mtypes = zero2.getJSONArray("types");
// String Type = mtypes.getString(0);
// Log.e(Type,long_name);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getAddress1() {
return Address1;
}
public String getAddress2() {
return Address2;
}
public String getCity() {
return City;
}
public String getState() {
return State;
}
public String getCountry() {
return Country;
}
public String getCounty() {
return County;
}
public String getPIN() {
return PIN;
}
}
For more detail on how to get Google Map Api key
JSON PARSER CLASS
public class parser_Json {
public static JSONObject getJSONfromURL(String url) {
// initialize
InputStream is = null;
String result = "";
JSONObject jObject = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObject = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jObject;
}
}
You can get more info from this question : Get the particular address using latitude and longitude
This will create an alias st
for status
:
git config --add alias.st status
The original question hinted that it would be nice to be able to filter all the properties based on a prefix. I have just confirmed that this works as of Spring Boot 2.1.1.RELEASE, for Properties
or Map<String,String>
. I'm sure it's worked for while now. Interestingly, it does not work without the prefix =
qualification, i.e. I do not know how to get the entire environment loaded into a map. As I said, this might actually be what OP wanted to begin with. The prefix and the following '.' will be stripped off, which might or might not be what one wants:
@ConfigurationProperties(prefix = "abc")
@Bean
public Properties getAsProperties() {
return new Properties();
}
@Bean
public MyService createService() {
Properties properties = getAsProperties();
return new MyService(properties);
}
Postscript: It is indeed possible, and shamefully easy, to get the entire environment. I don't know how this escaped me:
@ConfigurationProperties
@Bean
public Properties getProperties() {
return new Properties();
}
Use
a = sorted(a, key=lambda x: x.modified, reverse=True)
# ^^^^
On Python 2.x, the sorted
function takes its arguments in this order:
sorted(iterable, cmp=None, key=None, reverse=False)
so without the key=
, the function you pass in will be considered a cmp
function which takes 2 arguments.
I know the question is from 2012, but I found the easiest way ever, and I wanted to share.
HTML:
<div id="parent">
<div id="child">Content here</div>
</div>
and CSS:
#parent{
height: 100%;
display: table;
}
#child {
display: table-cell;
vertical-align: middle;
}
Please check you pom.xml for the below tags
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
it should point the required jdk version
appHelper.validateDates = function (start, end) {
var returnval = false;
var fd = new Date(start);
var fdms = fd.getTime();
var ed = new Date(end);
var edms = ed.getTime();
var cd = new Date();
var cdms = cd.getTime();
if (fdms >= edms) {
returnval = false;
console.log("step 1");
}
else if (cdms >= edms) {
returnval = false;
console.log("step 2");
}
else {
returnval = true;
console.log("step 3");
}
console.log("vall", returnval)
return returnval;
}
This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_table;
gid | datepose | pvc | modifiedpvc
-----+----------+-----+-------------
1 | 1961 | 01 | 00
2 | 1949 | | 01
3 | 1990 | 02 | 00
1 | 1981 | | 02
1 | | 03 | 00
1 | | | 03
(6 rows)
set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
The single quotes do not indicate a string, they make it starts: 'C:\
instead of C:\
so
%name%
is the usual syntax for expanding a variable, the !name!
syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION
first, or by running the command prompt with CMD /V:ON
.
Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4
to keep the current PATH content, and add something to the end.
To do this in IntelliJ IDEA 2020.2.3 (Community edition) on Windows 10:
Updated for 11/2020.
There are actually many good reasons to consider using accessors rather than directly exposing fields of a class - beyond just the argument of encapsulation and making future changes easier.
Here are the some of the reasons I am aware of:
With python or pandas when you use read_csv
or pd.read_csv
, both of them look into current working directory, by default where the python process have started. So you need to use os
module to chdir()
and take it from there.
import pandas as pd
import os
print(os.getcwd())
os.chdir("D:/01Coding/Python/data_sets/myowndata")
print(os.getcwd())
df = pd.read_csv('data.csv',nrows=10)
print(df.head())
I had the similar issue and the above examples doesn't help me to read properties. I have posted the complete class which will help you to read properties values from application.properties file in SpringBoot application in the below link.
Spring Boot - Environment @Autowired throws NullPointerException
Replace this line:
StreamWriter sw = new StreamWriter("c:/file.txt");
with this code:
StreamWriter sw = File.AppendText("c:/file.txt");
and then write your line to the text file like this:
sw.WriteLine("text content");
This is what I use in my application:
static void Main()
{
bool mutexCreated = false;
System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local\slimCODE.slimKEYS.exe", out mutexCreated );
if( !mutexCreated )
{
if( MessageBox.Show(
"slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?",
"slimKEYS already running",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question ) != DialogResult.Yes )
{
mutex.Close();
return;
}
}
// The usual stuff with Application.Run()
mutex.Close();
}
Android Architecture Components library you can use the ProcessLifecycleOwner
to set up a listener to the whole application process for onStart
and onStop
events. To do this, make your application class implement the LifecycleObserver
interface and add some annotations for onStart
and onStop
to your foreground and background methods.
class ArchLifecycleApp : Application(), LifecycleObserver {
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onAppBackgrounded() {
Log.d("Awww", "App in background")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onAppForegrounded() {
Log.d("Yeeey", "App in foreground")
}
}
I tried this, I've got something like
script type="text/javascript" src="createDiv.php?id=" script
AND In createDiv.php I Have
document getElementbyid(imgslide).appendchild(imgslide5).innerHTML = 'php echo $helloworld; ';
And I got supermad because the php at the beginning of the createDiv.php I made the $helloWorld
php variable was formatted cut and paste from the html page
But it wouldn't work cause Of whitespaces was anyone gonna tell anyone about the whitespace problem cause my real php whitespace still works but not this one.
function removeParam(parameter)
{
var url=document.location.href;
var urlparts= url.split('?');
if (urlparts.length>=2)
{
var urlBase=urlparts.shift();
var queryString=urlparts.join("?");
var prefix = encodeURIComponent(parameter)+'=';
var pars = queryString.split(/[&;]/g);
for (var i= pars.length; i-->0;)
if (pars[i].lastIndexOf(prefix, 0)!==-1)
pars.splice(i, 1);
url = urlBase+'?'+pars.join('&');
window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .
}
return url;
}
This will resolve your problem
This is simple code, but of course a little bit slower.
String s = ...;
int countDollar = s.length()-s.replaceAll("\\$","").length();
int counta = s.length()-s.replaceAll("a","").length();
An even better answer is here in a duplicate question
The most simple and the correct way is to use Record type Record<string, string>
const myVar : Record<string, string> = {
key1: 'val1',
key2: 'val2',
}
I was having trouble with this same issue, so I wrote a package called include.
Include handles figuring out your project's root folder by way of locating your package.json file, then passes the path argument you give it to the native require() without all of the relative path mess. I imagine this not as a replacement for require(), but a tool for requiring handling non-packaged / non-third-party files or libraries. Something like
var async = require('async'),
foo = include('lib/path/to/foo')
I hope this can be useful.
You can use Array.prototype.forEach
, but async/await is not so compatible. This is because the promise returned from an async callback expects to be resolved, but Array.prototype.forEach
does not resolve any promises from the execution of its callback. So then, you can use forEach, but you'll have to handle the promise resolution yourself.
Here is a way to read and print each file in series using Array.prototype.forEach
async function printFilesInSeries () {
const files = await getFilePaths()
let promiseChain = Promise.resolve()
files.forEach((file) => {
promiseChain = promiseChain.then(() => {
fs.readFile(file, 'utf8').then((contents) => {
console.log(contents)
})
})
})
await promiseChain
}
Here is a way (still using Array.prototype.forEach
) to print the contents of files in parallel
async function printFilesInParallel () {
const files = await getFilePaths()
const promises = []
files.forEach((file) => {
promises.push(
fs.readFile(file, 'utf8').then((contents) => {
console.log(contents)
})
)
})
await Promise.all(promises)
}
Try reindex.
UPDATE: As pointed out in the comments, this was in reply to the original question.
You might need to change your path by:
import os
path=os.chdir(str('Here should be the path to your file')) #This command changes directory
This is what worked for me at least! Hope it works for you too!
This happens when you somehow confused java itself. You are trying to run a java 6 VM where it found a JRE 7. It might show this problem even if you type in the command line just java
or java -version
in a misconfigured environment. The JAR is not the problem, except in the very unlikely case where the code in JAR is looking in the Windows Registry for that (which probably is not your case).
In my case, I had the java.exe
, javaw.exe
and javaws.exe
from Java 6 in the Windows/System32
folder (don't know how it got to be there). The rest of the JDK and JRE where found in the PATH inside C:\Java\jdk_1.7.0\bin
. Oops!
Changing in my package.json file "start": "export PORT=3001 && react-scripts start"
worked for me too and I'm on macOS 10.13.4
I was in need of copying the data from one workbook to another using VBA. The requirement was as mentioned below 1. On pressing an Active X button open the dialogue to select the file from which the data needs to be copied. 2. On clicking OK the value should get copied from a cell / range to currently working workbook.
I did not want to use the open function because it opens the workbook which will be annoying
Below is the code that I wrote in the VBA. Any improvement or new alternative is welcome.
Code: Here I am copying the A1:C4 content from a workbook to the A1:C4 of current workbook
Private Sub CommandButton1_Click()
Dim BackUp As String
Dim cellCollection As New Collection
Dim strSourceSheetName As String
Dim strDestinationSheetName As String
strSourceSheetName = "Sheet1" 'Mention the Source Sheet Name of Source Workbook
strDestinationSheetName = "Sheet2" 'Mention the Destination Sheet Name of Destination Workbook
Set cellCollection = GetCellsFromRange("A1:C4") 'Mention the Range you want to copy data from Source Workbook
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Show
'.Filters.Add "Macro Enabled Xl", "*.xlsm;", 1
For intWorkBookCount = 1 To .SelectedItems.Count
Dim strWorkBookName As String
strWorkBookName = .SelectedItems(intWorkBookCount)
For cellCount = 1 To cellCollection.Count
On Error GoTo ErrorHandler
BackUp = Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount))
Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)) = GetData(strWorkBookName, strSourceSheetName, cellCollection.Item(cellCount))
Dim strTempValue As String
strTempValue = Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)).Value
If (strTempValue = "0") Then
strTempValue = BackUp
End If
Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)) = strTempValue
ErrorHandler:
If (Err.Number <> 0) Then
Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)) = BackUp
Exit For
End If
Next cellCount
Next intWorkBookCount
End With
End Sub
Function GetCellsFromRange(RangeInScope As String) As Collection
Dim startCell As String
Dim endCell As String
Dim intStartColumn As Integer
Dim intEndColumn As Integer
Dim intStartRow As Integer
Dim intEndRow As Integer
Dim coll As New Collection
startCell = Left(RangeInScope, InStr(RangeInScope, ":") - 1)
endCell = Right(RangeInScope, Len(RangeInScope) - InStr(RangeInScope, ":"))
intStartColumn = Range(startCell).Column
intEndColumn = Range(endCell).Column
intStartRow = Range(startCell).Row
intEndRow = Range(endCell).Row
For lngColumnCount = intStartColumn To intEndColumn
For lngRowCount = intStartRow To intEndRow
coll.Add (Cells(lngRowCount, lngColumnCount).Address(RowAbsolute:=False, ColumnAbsolute:=False))
Next lngRowCount
Next lngColumnCount
Set GetCellsFromRange = coll
End Function
Function GetData(FileFullPath As String, SheetName As String, CellInScope As String) As String
Dim Path As String
Dim FileName As String
Dim strFinalValue As String
Dim doesSheetExist As Boolean
Path = FileFullPath
Path = StrReverse(Path)
FileName = StrReverse(Left(Path, InStr(Path, "\") - 1))
Path = StrReverse(Right(Path, Len(Path) - InStr(Path, "\") + 1))
strFinalValue = "='" & Path & "[" & FileName & "]" & SheetName & "'!" & CellInScope
GetData = strFinalValue
End Function
The best solution I found is html-pdf. It's simple and work with big html.
https://www.npmjs.com/package/html-pdf
Its as simple as that:
pdf.create(htm, options).toFile('./pdfname.pdf', function(err, res) {
if (err) {
console.log(err);
}
});
I am sorry, I forget to answer this question. After few days of googling I found, that problem was caused by hyperthreading (or hyper - v). I decided to edit my boot.ini file with option to start up windows with hyperthreading turned off. I followed this tutorial and now everything works perfect
String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);
Here;this is the solution.
As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:
git reset HEAD .
(note the trailing dot)git stash
git checkout master
git fetch upstream; git merge upstream/master
git checkout new-branch; git rebase master
git stash apply stash@{1}
Similar to Oli's answer, I use an argument Object and an Object which defines the default values. With a little bit of sugar...
/**
* Updates an object's properties with other objects' properties. All
* additional non-falsy arguments will have their properties copied to the
* destination object, in the order given.
*/
function extend(dest) {
for (var i = 1, l = arguments.length; i < l; i++) {
var src = arguments[i]
if (!src) {
continue
}
for (var property in src) {
if (src.hasOwnProperty(property)) {
dest[property] = src[property]
}
}
}
return dest
}
/**
* Inherit another function's prototype without invoking the function.
*/
function inherits(child, parent) {
var F = function() {}
F.prototype = parent.prototype
child.prototype = new F()
child.prototype.constructor = child
return child
}
...this can be made a bit nicer.
function Field(kwargs) {
kwargs = extend({
required: true, widget: null, label: null, initial: null,
helpText: null, errorMessages: null
}, kwargs)
this.required = kwargs.required
this.label = kwargs.label
this.initial = kwargs.initial
// ...and so on...
}
function CharField(kwargs) {
kwargs = extend({
maxLength: null, minLength: null
}, kwargs)
this.maxLength = kwargs.maxLength
this.minLength = kwargs.minLength
Field.call(this, kwargs)
}
inherits(CharField, Field)
What's nice about this method?
undefined
when, say there are 5 arguments and you only want to customise the last one, as you would have to do with some of the other methods suggested.CharField
calls Field
's constructor).There is more than one way to do it:
1- Add your UIView
on UIWindow
instead of adding it on UIViewController
. This way it will be on top of everything.
[[(AppDelegate *)[UIApplication sharedApplication].delegate window] addSubview:view];
2- Use custom transition that will keep your UIViewController showing in the back with a 0.5 alpha
For that I recommend you look at this: https://github.com/Citrrus/BlurryModalSegue
You can use .length
with just a descendant selector, like this:
var count = $("#selected li").length;
If you have to use .children()
, then it's like this:
var count = $("#selected ul").children().length;
Peter Steinberger just tweeted about the private notification UIWindowFirstResponderDidChangeNotification
, which you can observe if you want to watch the firstResponder change.
C99 does, if you have
#include <stdbool.h>
If the compiler does not support C99, you can define it yourself:
// file : myboolean.h
#ifndef MYBOOLEAN_H
#define MYBOOLEAN_H
#define false 0
#define true 1
typedef int bool; // or #define bool int
#endif
(but note that this definition changes ABI for bool
type so linking against external libraries which were compiled with properly defined bool
may cause hard-to-diagnose runtime errors).
In my case the crucial thing was to set in 'scrollwheel':false
in init. Notice: I am using jQuery UI Map
. Below is my CoffeeScript init function heading:
$("#map_canvas").gmap({'scrollwheel':false}).bind "init", (evt, map) ->
// String.class here is the parameter type, that might not be the case with you
Method method = clazz.getMethod("methodName", String.class);
Object o = method.invoke(null, "whatever");
In case the method is private use getDeclaredMethod()
instead of getMethod()
. And call setAccessible(true)
on the method object.
After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts
subdirectory.
In CSS code:
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font.woff") format('woff');
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-bold.woff") format('woff');
font-weight: bold;
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-boldoblique.woff") format('woff');
font-weight: bold;
font-style: italic;
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-oblique.woff") format('woff');
font-style: italic;
}
After having that definitions, you can just write, for example,
In HTML code:
<div class="mydiv">
<b>this will be written with awesome-font-bold.woff</b>
<br/>
<b><i>this will be written with awesome-font-boldoblique.woff</i></b>
<br/>
<i>this will be written with awesome-font-oblique.woff</i>
<br/>
this will be written with awesome-font.woff
</div>
In CSS code:
.mydiv {
font-family: myfont
}
The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.
Another useful property of the cross product is that its magnitude is related to the sine of the angle between the two vectors:
| a x b | = |a| . |b| . sine(theta)
or
sine(theta) = | a x b | / (|a| . |b|)
So, in implementation 1 above, if a
and b
are known in advance to be unit vectors then the result of that function is exactly that sine() value.
I am running PHP version 5.4 on shared hosting and both of these both successfully return the same results:
php_uname('n');
gethostname();
My situation was a little different, I'm testing my app using Espresso
and I had to launch my Activity with ActivityTestRule
from the instrumentation Context
(which is not the one coming from an Activity
).
fun intent(context: Context) =
Intent(context, HomeActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
I had to change the flags and add an or
bitwise ( |
in Java) with Intent.FLAG_ACTIVITY_NEW_TASK
So it results in:
fun intent(context: Context) =
Intent(context, HomeActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
Extending @Ryogi answer above, you can take advantage of the lower.tail
parameter like so:
qt(0.25/2, 40, lower.tail = FALSE)
# 75% confidence
qt(0.01/2, 40, lower.tail = FALSE)
# 99% confidence
Not sure what you are really after but if you want to print exactly what you have you can do:
Option 1
print(df['Item'].to_csv(index=False))
Sweet
Candy
Chocolate
Option 2
for v in df['Item']:
print(v)
Sweet
Candy
Chocolate
I've written a controller for handling the logic behind an array of radio buttons. It's open source and on GitHub, check it out!
Calendar cal = Calendar.getInstance(); //This to obtain today's date in our Calendar var.
java.sql.Date date = new Date (cal.getTimeInMillis());
You can't have bare words in the code, that's the reason why they created variables (your code will fail with NameError
).
The code you provided would create a database table named month
(plus whatever prefix django adds to that), because that's the name of the CharField
.
But there are better ways to create the particular choices you want. See a previous Stack Overflow question.
import calendar
tuple((m, m) for m in calendar.month_name[1:])
NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT.
NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but not others, if you choose. If you plan to use NOLOCK on all tables in a complex query, then using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED is easier, because you don't have to apply the hint to every table.
Here is information about all of the isolation levels at your disposal, as well as table hints.
Range("A1").value = Environ("Username")
This is better than Application.Username
, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.
Application Username
is the name of the User set in Excel > Tools > Options Environ("Username")
is the name you registered for Windows; see Control Panel >SystemHi I needed to do the same thing! Don't ask why but I was generating a html using python and needed a way to loop through items in a list and have each item take on a row of its own WITHIN A SINGLE CELL of a table.
I found that the br tag worked well for me. For example:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<TABLE>
<TR>
<TD>
item 1 <BR>
item 2 <BR>
item 3 <BR>
item 4 <BR>
</TD>
</TR>
</TABLE>
</BODY>
This will produce the output that I wanted.
I don't think this is possible using PostgreSQL alone in the most general case. When you install PostgreSQL, you pick a time zone. I'm pretty sure the default is to use the operating system's timezone. That will usually be reflected in postgresql.conf as the value of the parameter "timezone". But the value ends up as "localtime". You can see this setting with the SQL statement.
show timezone;
But if you change the timezone in postgresql.conf to something like "Europe/Berlin", then show timezone;
will return that value instead of "localtime".
So I think your solution will involve setting "timezone" in postgresql.conf to an explicit value rather than the default "localtime".
Taking reference of ThiefMaster? sometimes we get an error with value given as '\n' or null and perform for that required to handle ValueError:
Handling the exception is the way to go
try:
gotdata = dlist[1]
except (IndexError, ValueError):
gotdata = 'null'
Use This function to set all Type of margins
public void setViewMargins(Context con, ViewGroup.LayoutParams params,
int left, int top , int right, int bottom, View view) {
final float scale = con.getResources().getDisplayMetrics().density;
// convert the DP into pixel
int pixel_left = (int) (left * scale + 0.5f);
int pixel_top = (int) (top * scale + 0.5f);
int pixel_right = (int) (right * scale + 0.5f);
int pixel_bottom = (int) (bottom * scale + 0.5f);
ViewGroup.MarginLayoutParams s = (ViewGroup.MarginLayoutParams) params;
s.setMargins(pixel_left, pixel_top, pixel_right, pixel_bottom);
view.setLayoutParams(params);
}
Not exactly answering the question, but faced with the same problem I ended up doing this:
UPDATE people_exit SET last_name = SUBSTRING_INDEX(fullname,' ',-1)
UPDATE people_exit SET middle_name = TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(fullname,last_name,1),' ',-2))
UPDATE people_exit SET middle_name = '' WHERE CHAR_LENGTH(middle_name)>3
UPDATE people_exit SET first_name = SUBSTRING_INDEX(fullname,concat(middle_name,' ',last_name),1)
UPDATE people_exit SET first_name = middle_name WHERE first_name = ''
UPDATE people_exit SET middle_name = '' WHERE first_name = middle_name
You might want to do one of the following:
Several libraries let you do that easily. Example below is written using my NoException library.
// Propagate checked exception
as.forEach(Exceptions.sneak().consumer(A::foo));
// Wrap and propagate unchecked exception
as.forEach(Exceptions.wrap().consumer(A::foo));
as.forEach(Exceptions.wrap(MyUncheckedException::new).consumer(A::foo));
// Catch the exception and stop propagation (using logging handler for example)
as.forEach(Exceptions.log().consumer(Exceptions.sneak().consumer(A::foo)));
You need to add quotes. VBA is translating
Rows(copyToRow & ":" & copyToRow).Select`
into
Rows(52:52).Select
Try changing
Rows(""" & copyToRow & ":" & copyToRow & """).Select
I was wondering why my class' destructor was not called. The reason was that I had forgot to include definition of that class (#include "class.h"). I only had a declaration like "class A;" and the compiler was happy with it and let me call "delete".
As a complement to the answers given above; do not forget about Form MinimumSize Property, in case you require to create smaller Forms.
Example Bellow:
private void SetDefaultWindowSize()
{
int sizeW, sizeH;
sizeW = 180;
sizeH = 100;
var size = new Size(sizeW, sizeH);
Size = size;
MinimumSize = size;
}
private void SetNewSize()
{
Size = new Size(Width, 10);
}
If you are in an ASP.NET MVC web controller it's as simple as:
string ladAsJson = Json(Lad);
Can't believe no one has mentioned this.
Use a Razor to dynamically change your URL by calling your action like this:
$.ajax({
type: "POST",
url: '@Url.Action("ActionName", "ControllerName")',
contentType: "application/json; charset=utf-8",
data: { data: "yourdata" },
dataType: "json",
success: function(recData) { alert('Success'); },
error: function() { alert('A error'); }
});
It could be something like:
var qry = from t in db.Lasttraces
group t by t.AccountId into g
orderby t.Date
select new { g.AccountId, Date = g.Max(e => e.Date) };
Answered code-snippet posted by Leandros seems bit old. I have fixed and made it compilable in Swift 5.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
let controller = UIViewController()
let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
view.backgroundColor = UIColor.red
controller.view = view
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
label.center = CGPoint(x: 160, y: 284)
label.textAlignment = NSTextAlignment.center
label.text = "I'am a test label"
controller.view.addSubview(label)
self.window!.rootViewController = controller
self.window!.makeKeyAndVisible()
return true
}
JavaScript is what you need. If you are loading iframe when loading the page, insert the test for iframe using the onload event. If iframe is inserted in realtime, then create a callback function on insertion and hook in whatever action you need to take :)
https://dev.mysql.com/doc/refman/8.0/en/insert-optimization.html
The time required for inserting a row is determined by the following factors, where the numbers indicate approximate proportions:
- Connecting: (3)
- Sending query to server: (2)
- Parsing query: (2)
- Inserting row: (1 × size of row)
- Inserting indexes: (1 × number of indexes)
- Closing: (1)
From this it should be obvious, that sending one large statement will save you an overhead of 7 per insert statement, which in further reading the text also says:
If you are inserting many rows from the same client at the same time, use INSERT statements with multiple VALUES lists to insert several rows at a time. This is considerably faster (many times faster in some cases) than using separate single-row INSERT statements.
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
response.sendRedirect("somePage.jsp");
The explanation to the answer for the one-liner sed.
[section1]
param1=123
param2=345
param3=678
[section2]
param1=abc
param2=def
param3=ghi
[section3]
param1=000
param2=111
param3=222
sed -nr "/^\[section2\]/ { :l /^\s*[^#].*/ p; n; /^\[/ q; b l; }" ./file.ini
To understand, it will be easier to format the line like this:
sed -nr "
# start processing when we found the word \"section2\"
/^\[section2\]/ { #the set of commands inside { } will be executed
#create a label \"l\" (https://www.grymoire.com/Unix/Sed.html#uh-58)
:l /^\s*[^#].*/ p;
# move on to the next line. For the first run it is the \"param1=abc\"
n;
# check if this line is beginning of new section. If yes - then exit.
/^\[/ q
#otherwise jump to the label \"l\"
b l
}
" file.ini
If not using C++14, then I find below the simplest solution.
#define METHOD(NAME, ...) auto NAME __VA_ARGS__ -> decltype(m_T.r##NAME) { return m_T.r##NAME; }
template<typename T>
struct Reverse
{
T& m_T;
METHOD(begin());
METHOD(end());
METHOD(begin(), const);
METHOD(end(), const);
};
#undef METHOD
template<typename T>
Reverse<T> MakeReverse (T& t) { return Reverse<T>{t}; }
Demo.
It doesn't work for the containers/data-types (like array), which doesn't have begin/rbegin, end/rend
functions.
There is a library for this BarCode PHP. You just need to include a few files:
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
You can generate many types of barcodes, namely 1D or 2D. Add the required library:
require_once('class/BCGcode39.barcode.php');
Generate the colours:
// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);
After you have added all the codes, you will get this way:
Example
Since several have asked for an example here is what I was able to do to get it done
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
require_once('class/BCGcode128.barcode.php');
header('Content-Type: image/png');
$color_white = new BCGColor(255, 255, 255);
$code = new BCGcode128();
$code->parse('HELLO');
$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);
$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
If you want to actually create the image file so you can save it then change
$drawing = new BCGDrawing('', $color_white);
to
$drawing = new BCGDrawing('image.png', $color_white);
It's safer to use *arguments.callee.caller
since arguments.caller
is deprecated...
Try this
sql = "select username from usermst where userid=2"
string getusername = Convert.ToString(command.ExecuteScalar());
One way might be;
<select name="listbox" id="listbox">
@foreach (var item in Model)
{
<option value="@item.UserRoleId">
@item.UserRole
</option>
}
</select>
Just my 2 cents regarding the divs option.
Famous/Infamous and SamsaraJS (and possibly others) use absolutely positioned non-nested divs (with non-trivial HTML/CSS content), combined with matrix2d/matrix3d for positioning and 2D/3D transformations, and achieve a stable 60FPS on moderate mobile hardware, so I'd argue against divs being a slow option.
There are plenty of screen recordings on Youtube and elsewhere, of high-performance 2D/3D stuff running in the browser with everything being an DOM element which you can Inspect Element on, at 60FPS (mixed with WebGL for certain effects, but not for the main part of the rendering).
You can do something like this:
<%
out.print("<p>Hey!</p>");
out.print("<p>How are you?</p>");
%>
$regex = '#<code>(.*?)</code>#';
Using #
as the delimiter instead of /
because then we don't need to escape the /
in </code>
As Phoenix posted below, .*?
is used to make the .*
("anything") match as few characters as possible before it comes across a </code>
(known as a "non-greedy quantifier"). That way, if your string is
<code>hello</code> something <code>again</code>
you'll match hello
and again
instead of just matching hello</code> something <code>again
.
Since version 1.3.0
AngularJS introduced extra filter parameter timezone
, like following:
{{ date_expression | date : format : timezone}}
But in versions 1.3.x
only supported timezone is UTC
, which can be used as following:
{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}
Since version 1.4.0-rc.0
AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):
{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}
Here you can find documentation of AngularJS date filters.
NOTE: this is working only with Angular 1.x
Here's working example
In Maven you can configure the surefire plugin
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<argLine>-Xmx256M</argLine>
</configuration>
</plugin>
If you use Maven for builds then this configuration will be carried in the source tree and applied when tests are carried out. See the Maven Surefire Plugin documentation.
Within PowerShell ISE you can hit Ctrl+J to open the Start Snipping menu and select Comment block:
$('#comboBx').append($("<option></option>").attr("value",key).text(value));
where comboBx is your combo box id.
or you can append options as string to the already existing innerHTML and then assign to the select innerHTML.
Edit
If you need to keep the first option and remove all other then you can use
var firstOption = $("#cmb1 option:first-child");
$("#cmb1").empty().append(firstOption);
OP's solution to his problem, as he says, has dubious output. That code still shows confusion about representations of time. To clear up this confusion, and make code that won't lead to wrong times, consider this extension of what he did:
public static void _testDateFormatting() {
SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfGMT2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
sdfGMT2.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfLocal1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
SimpleDateFormat sdfLocal2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
try {
Date d = new Date();
String s1 = d.toString();
String s2 = sdfLocal1.format(d);
// Store s3 or s4 in database.
String s3 = sdfGMT1.format(d);
String s4 = sdfGMT2.format(d);
// Retrieve s3 or s4 from database, using LOCAL sdf.
String s5 = sdfLocal1.parse(s3).toString();
//EXCEPTION String s6 = sdfLocal2.parse(s3).toString();
String s7 = sdfLocal1.parse(s4).toString();
String s8 = sdfLocal2.parse(s4).toString();
// Retrieve s3 from database, using GMT sdf.
// Note that this is the SAME sdf that created s3.
Date d2 = sdfGMT1.parse(s3);
String s9 = d2.toString();
String s10 = sdfGMT1.format(d2);
String s11 = sdfLocal2.format(d2);
} catch (Exception e) {
e.printStackTrace();
}
}
examining values in a debugger:
s1 "Mon Sep 07 06:11:53 EDT 2015" (id=831698113128)
s2 "2015.09.07 06:11:53" (id=831698114048)
s3 "2015.09.07 10:11:53" (id=831698114968)
s4 "2015.09.07 10:11:53 GMT+00:00" (id=831698116112)
s5 "Mon Sep 07 10:11:53 EDT 2015" (id=831698116944)
s6 -- omitted, gave parse exception
s7 "Mon Sep 07 10:11:53 EDT 2015" (id=831698118680)
s8 "Mon Sep 07 06:11:53 EDT 2015" (id=831698119584)
s9 "Mon Sep 07 06:11:53 EDT 2015" (id=831698120392)
s10 "2015.09.07 10:11:53" (id=831698121312)
s11 "2015.09.07 06:11:53 EDT" (id=831698122256)
sdf2 and sdfLocal2 include time zone, so we can see what is really going on. s1 & s2 are at 06:11:53 in zone EDT. s3 & s4 are at 10:11:53 in zone GMT -- equivalent to the original EDT time. Imagine we save s3 or s4 in a data base, where we are using GMT for consistency, so we can have times from anywhere in the world, without storing different time zones.
s5 parses the GMT time, but treats it as a local time. So it says "10:11:53" -- the GMT time -- but thinks it is 10:11:53 in local time. Not good.
s7 parses the GMT time, but ignores the GMT in the string, so still treats it as a local time.
s8 works, because now we include GMT in the string, and the local zone parser uses it to convert from one time zone to another.
Now suppose you don't want to store the zone, you want to be able to parse s3, but display it as a local time. The answer is to parse using the same time zone it was stored in -- so use the same sdf as it was created in, sdfGMT1. s9, s10, & s11 are all representations of the original time. They are all "correct". That is, d2 == d1. Then it is only a question of how you want to DISPLAY it. If you want to display what is stored in DB -- GMT time -- then you need to format it using a GMT sdf. Ths is s10.
So here is the final solution, if you don't want to explicitly store with " GMT" in the string, and want to display in GMT format:
public static void _testDateFormatting() {
SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
Date d = new Date();
String s3 = sdfGMT1.format(d);
// Store s3 in DB.
// ...
// Retrieve s3 from database, using GMT sdf.
Date d2 = sdfGMT1.parse(s3);
String s10 = sdfGMT1.format(d2);
} catch (Exception e) {
e.printStackTrace();
}
}
Assuming that onMove
is an event handler, it is likely that its context is something other than the instance of MyContainer
, i.e. this
points to something different.
You can manually bind the context of the function during the construction of the instance via Function.bind
:
class MyContainer extends Component {
constructor(props) {
super(props);
this.onMove = this.onMove.bind(this);
this.test = "this is a test";
}
onMove() {
console.log(this.test);
}
}
Also, test !== testVariable
.
SELECT ID, Col1, Col2, Col3,
(SELECT MIN(Col) FROM (VALUES (Col1), (Col2), (Col3)) AS X(Col)) AS TheMin
FROM Table
The ideal way is not to use ioutil.ReadAll
, but rather use a decoder on the reader directly. Here's a nice function that gets a url and decodes its response onto a target
structure.
var myClient = &http.Client{Timeout: 10 * time.Second}
func getJson(url string, target interface{}) error {
r, err := myClient.Get(url)
if err != nil {
return err
}
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(target)
}
Example use:
type Foo struct {
Bar string
}
func main() {
foo1 := new(Foo) // or &Foo{}
getJson("http://example.com", foo1)
println(foo1.Bar)
// alternately:
foo2 := Foo{}
getJson("http://example.com", &foo2)
println(foo2.Bar)
}
You should not be using the default *http.Client
structure in production as this answer originally demonstrated! (Which is what http.Get
/etc call to). The reason is that the default client has no timeout set; if the remote server is unresponsive, you're going to have a bad day.
You need to dig a bit deeper into the api to do this:
from matplotlib import pyplot as plt
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()
Integers are finite, so sadly you can't have set it to a true infinity. However you can set it to the max value of an int, this would mean that it would be greater or equal to any other int, ie:
a>=b
is always true.
You would do this by
#include <limits>
//your code here
int a = std::numeric_limits<int>::max();
//go off and lead a happy and productive life
This will normally be equal to 2,147,483,647
If you really need a true "infinite" value, you would have to use a double or a float. Then you can simply do this
float a = std::numeric_limits<float>::infinity();
Additional explanations of numeric limits can be found here
Happy Coding!
Note: As WTP mentioned, if it is absolutely necessary to have an int that is "infinite" you would have to write a wrapper class for an int and overload the comparison operators, though this is probably not necessary for most projects.
API is code based integration while web service is message based integration with interoperable standards having a contract such as WSDL.
Here is an example of callbacks in C.
Let's say you want to write some code that allows registering callbacks to be called when some event occurs.
First define the type of function used for the callback:
typedef void (*event_cb_t)(const struct event *evt, void *userdata);
Now, define a function that is used to register a callback:
int event_cb_register(event_cb_t cb, void *userdata);
This is what code would look like that registers a callback:
static void my_event_cb(const struct event *evt, void *data)
{
/* do stuff and things with the event */
}
...
event_cb_register(my_event_cb, &my_custom_data);
...
In the internals of the event dispatcher, the callback may be stored in a struct that looks something like this:
struct event_cb {
event_cb_t cb;
void *data;
};
This is what the code looks like that executes a callback.
struct event_cb *callback;
...
/* Get the event_cb that you want to execute */
callback->cb(event, callback->data);
If you are not in an Rails environment (ie. don't have ActiveRecord available), this may be helpful:
JSON.parse( object.to_json )